diff --git a/src/test/java/org/refactoringminer/test/TestRelatedStatementMappingsTest.java b/src/test/java/org/refactoringminer/test/TestRelatedStatementMappingsTest.java new file mode 100644 index 0000000000..941c132f86 --- /dev/null +++ b/src/test/java/org/refactoringminer/test/TestRelatedStatementMappingsTest.java @@ -0,0 +1,102 @@ +package org.refactoringminer.test; + +import gr.uom.java.xmi.decomposition.AbstractCodeMapping; +import gr.uom.java.xmi.decomposition.LeafExpression; +import gr.uom.java.xmi.diff.AssertThrowsRefactoring; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.refactoringminer.api.Refactoring; +import org.refactoringminer.api.RefactoringHandler; +import org.refactoringminer.rm1.GitHistoryRefactoringMinerImpl; + +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +import static org.refactoringminer.utils.Assertions.assertHasSameElementsAs; + +public class TestRelatedStatementMappingsTest { + public static final String REPOS = System.getProperty("user.dir") + "/src/test/resources/oracle/commits"; + private static final String EXPECTED_PATH = System.getProperty("user.dir") + "/src/test/resources/mappings/"; + private GitHistoryRefactoringMinerImpl miner; + private List actual; + private List expected; + + + @ParameterizedTest + @CsvSource({ + //Migrate Expected Exception + "https://github.com/apache/camel.git, c30deabcaed4726bce4371d76257db63f2eba87c, camel-c30deabcaed4726bce4371d76257db63f2eba87c.txt", + "https://github.com/apache/commons-csv.git, e2f0a4d8a83a41eaa984086636a3712c682307ea, commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.txt", + "https://github.com/apache/jmeter.git, d5b5b2f38c3341cbb934693c17d0574a241ad4f9, jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.txt", + "https://github.com/apache/plc4x.git, 4312eb178b6cb000ea8a3c78df70567182341331, plc4x-4312eb178b6cb000ea8a3c78df70567182341331.txt", + "https://github.com/eclipse/eclipse-collections.git, f26addbce8e843f208805aa22f45dcfb6f8177f7, eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.txt", + "https://github.com/EnMasseProject/enmasse.git, 5e0e683531b756ac62a497cca15ddb7211a34e24, enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.txt", + "https://github.com/apache/clerezza.git, d77dbe2085ffa89b2a933637c5432d113b7432b8, clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.txt", + "https://github.com/iluwatar/java-design-patterns.git, 6694d742a370e0f181530734481284de8d5dd8ef, java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.txt", + "https://github.com/LMAX-Exchange/disruptor.git, 340f23ef88a32ceb8341820c15bfd9537303219c, disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.txt", + "https://github.com/neo4j/neo4j.git, b44c62bcdd6f7218bc97dae183ea0f6587bacd29, neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.txt", + "https://github.com/RohanNagar/thunder.git, 48776d511a0152f7b9cbe4460c8967bdd5ec3dc4, thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.txt", + "https://github.com/SAP/olingo-jpa-processor-v4.git, 5e77141293d32b015a92e48d099195840f2b2e87, olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.txt", + "https://github.com/zalando/problem.git, 1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998, problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.txt", + //"https://github.com/apache/plc4x.git, 86da20c173ad291e5f3d5fe4c56f37d7f3c2c538, plc4x-86da20c173ad291e5f3d5fe4c56f37d7f3c2c538.txt", // FIXME: JUnit 5 to AssertJ expected exception not supported + //"https://github.com/assertj/assertj-swing.git, 033bdd7832ca9a9647c8f7b7ecaa985d3115b206, assertj-swing-033bdd7832ca9a9647c8f7b7ecaa985d3115b206.txt", // FIXME: TestNG to JUnit 4 expected exception not supported + //"https://github.com/alexruiz/fest-swing-1.x.git, 033bdd7832ca9a9647c8f7b7ecaa985d3115b206, fest-swing-1.x-033bdd7832ca9a9647c8f7b7ecaa985d3115b206.txt", // FIXME: TestNG to JUnit 4 expected exception not supported + //"https://github.com/apache/flink.git, 2c5bc580e6c10fb3a2724a945847b5cc6b28df27, flink-2c5bc580e6c10fb3a2724a945847b5cc6b28df27.txt", // FIXME: JUnit 4 to AssertJ expected exception not supported + //"https://github.com/apache/flink.git, 95c3499ea80d07c448c297e36fa5a1b5b4caea2b, flink-95c3499ea80d07c448c297e36fa5a1b5b4caea2b.txt", // FIXME: JUnit 4 to AssertJ expected exception not supported + //"https://github.com/apache/cassandra-java-driver.git, 7d962af9291f69f0da6115375efd5bd5224a2353, cassandra-java-driver-7d962af9291f69f0da6115375efd5bd5224a2353.txt", // FIXME: TestNG to JUnit 4 expected exception not supported + //"https://github.com/OpenGamma/Strata.git, e007f826c49075500def8638de8367960c054c19, Strata-e007f826c49075500def8638de8367960c054c19.txt", // FIXME: TestNG to AssertJ expected exception not supported + //"https://github.com/rapidoid/rapidoid.git, 8596c1d82e9f0a36f40cd7ec393c6829e697836d, rapidoid-8596c1d82e9f0a36f40cd7ec393c6829e697836d.txt", // FIXME: TestNG to JUnit 4 expected exception not supported + //"https://github.com/zanata/zanata-platform.git, 0297e0513ac1f487f1570b1cc38979a73ac97da8, zanata-platform-0297e0513ac1f487f1570b1cc38979a73ac97da8.txt", // FIXME: TestNG to JUnit 4 expected exception not supported + }) + public void testAssertThrowsMappings(String url, String commit, String testResultFileName) throws Exception { + testRefactoringMappings(url, commit, testResultFileName, ref -> { + if (ref instanceof AssertThrowsRefactoring) { + AssertThrowsRefactoring assertThrowsRefactoring = (AssertThrowsRefactoring) ref; + Set mapper = assertThrowsRefactoring.getAssertThrowsMappings(); + mapperInfo(mapper, assertThrowsRefactoring.getOperationBefore(), assertThrowsRefactoring.getOperationAfter()); + } + }); + } + + @BeforeEach + void setUp() { + miner = new GitHistoryRefactoringMinerImpl(); + actual = new ArrayList<>(); + expected = new ArrayList<>(); + } + + private void testRefactoringMappings(String url, String commit, String testResultFileName, final Consumer consumer) { + miner.detectAtCommitWithGitHubAPI(url, commit, new File(REPOS), new RefactoringHandler() { + @Override + public void handle(String commitId, List refactorings) { + for (Refactoring ref : refactorings) { + consumer.accept(ref); + } + } + }); + Supplier lazyErrorMessage = () -> actual.stream().collect(Collectors.joining(System.lineSeparator())); + Assertions.assertDoesNotThrow(() -> { + expected.addAll(IOUtils.readLines(new FileReader(EXPECTED_PATH + testResultFileName))); + }, lazyErrorMessage); + assertHasSameElementsAs(expected, actual, lazyErrorMessage); + } + + private void mapperInfo(Set mappings, T operationBefore, T operationAfter) { + actual.add(operationBefore + " -> " + operationAfter); + for(AbstractCodeMapping mapping : mappings) { + if(mapping.getFragment1() instanceof LeafExpression && mapping.getFragment2() instanceof LeafExpression) + continue; + String line = mapping.getFragment1().getLocationInfo() + "==" + mapping.getFragment2().getLocationInfo(); + actual.add(line); + } + } +} diff --git a/src/test/java/org/refactoringminer/utils/Assertions.java b/src/test/java/org/refactoringminer/utils/Assertions.java new file mode 100644 index 0000000000..d31aa38e87 --- /dev/null +++ b/src/test/java/org/refactoringminer/utils/Assertions.java @@ -0,0 +1,30 @@ +package org.refactoringminer.utils; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public class Assertions { + public static void assertHasSameElementsAs(List expected, List actual, Supplier lazyErrorMessage) { + var expectedSet = new LinkedHashSet<>(expected); + var actualSet = new LinkedHashSet<>(actual); + org.junit.jupiter.api.Assertions.assertAll( + () -> org.junit.jupiter.api.Assertions.assertEquals(expected.size(), actual.size(), () -> + "Expected size (" + expected.size() + ") != actual size (" + actual.size() + "):" + + System.lineSeparator() + lazyErrorMessage.get() + System.lineSeparator()), + () -> org.junit.jupiter.api.Assertions.assertTrue(actualSet.containsAll(expectedSet), () -> System.lineSeparator() + expectedSet.stream() + .filter((String s) -> !actualSet.contains(s)) + .map((String s) -> "+" + s) + .map((String s) -> s + System.lineSeparator()) + .collect(Collectors.joining())), + () -> org.junit.jupiter.api.Assertions.assertTrue(expectedSet.containsAll(actualSet), () -> System.lineSeparator() + actualSet.stream() + .filter((String s) -> !expectedSet.contains(s)) + .map((String s) -> "-" + s) + .map((String s) -> s + System.lineSeparator()) + .collect(Collectors.joining()))); + } + public static void assertHasSameElementsAs(List expected, List actual) { + assertHasSameElementsAs(expected, actual, () -> ""); + } +} diff --git a/src/test/resources/mappings/camel-c30deabcaed4726bce4371d76257db63f2eba87c.txt b/src/test/resources/mappings/camel-c30deabcaed4726bce4371d76257db63f2eba87c.txt new file mode 100644 index 0000000000..63508cf528 --- /dev/null +++ b/src/test/resources/mappings/camel-c30deabcaed4726bce4371d76257db63f2eba87c.txt @@ -0,0 +1,28 @@ +public testBodyOgnlExpression() : void -> public testBodyOgnlExpression() : void +line range:187-187==line range:187-187 +public testBodyOgnlExpression() : void -> public testBodyOgnlExpression() : void +line range:195-195==line range:190-190 +public httpDisableStreamCache() : void -> public httpDisableStreamCache() : void +line range:79-79==line range:78-78 +public testTransferExeption() : void -> public testTransferException() : void +line range:62-62==line range:62-62 +public testBadConfiguration() : void -> public testBadConfiguration() : void +line range:110-110==line range:113-113 +public testNoResponseDisconnectOnNoReplyFalse() : void -> public testNoResponseDisconnectOnNoReplyFalse() : void +line range:45-45==line range:45-45 +public testNoResponse() : void -> public testNoResponse() : void +line range:50-50==line range:51-51 +public testBadConfiguration() : void -> public testBadConfiguration() : void +line range:81-81==line range:82-82 +public testWriteByteArraySliceWithNegativeLength() : void -> public testWriteByteArraySliceWithNegativeLength() : void +line range:258-258==line range:258-258 +public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void -> public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void +line range:275-275==line range:273-273 +public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void -> public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void +line range:283-283==line range:280-280 +public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void -> public testWriteByteArraySliceWithLengthGreaterThanAvailable() : void +line range:292-292==line range:287-287 +public testKeepingTimeoutHeader() : void -> public testKeepingTimeoutHeader() : void +line range:60-60==line range:61-61 +public testFail() : void -> public testFail() : void +line range:41-48==line range:51-51 \ No newline at end of file diff --git a/src/test/resources/mappings/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.txt b/src/test/resources/mappings/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.txt new file mode 100644 index 0000000000..2bb0347dbd --- /dev/null +++ b/src/test/resources/mappings/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.txt @@ -0,0 +1,38 @@ +public unavailableConvertor() : void -> public unavailableConvertor() : void +line range:42-42==line range:49-49 +public testAcessGraph() : void -> public testAcessGraph() : void +line range:115-115==line range:127-127 +public testNoWildCard() : void -> public testNoWildCard() : void +line range:120-120==line range:133-133 +public testAllowedArea() : void -> public testAllowedArea() : void +line range:125-125==line range:139-139 +public testAcessForbiddenGraph() : void -> public testAcessForbiddenGraph() : void +line range:130-130==line range:145-145 +public testCustomPermissions() : void -> public testCustomPermissions() : void +line range:141-141==line range:158-158 +public testCustomPermissionsIncorrect() : void -> public testCustomPermissionsIncorrect() : void +line range:152-152==line range:171-171 +public testCreateMGraph() : void -> public testCreateMGraph() : void +line range:168-168==line range:189-189 +public testCreateMGraphWithoutWritePermission() : void -> public testCreateMGraphWithoutWritePermission() : void +line range:172-172==line range:195-195 +public testAddTripleToMGraph() : void -> public testAddTripleToMGraph() : void +line range:178-178==line range:202-202 +public executeSparqlQueryNoEngineWithString() : void -> public executeSparqlQueryNoEngineWithString() : void +line range:145-145==line range:153-153 +public executeSparqlQueryNoEngineWithQuery() : void -> public executeSparqlQueryNoEngineWithQuery() : void +line range:154-154==line range:163-163 +public executeSparqlQueryNoEngineWithSelectQuery() : void -> public executeSparqlQueryNoEngineWithSelectQuery() : void +line range:163-163==line range:173-173 +public executeSparqlQueryNoEngineWithAskQuery() : void -> public executeSparqlQueryNoEngineWithAskQuery() : void +line range:172-172==line range:183-183 +public executeSparqlQueryNoEngineWithDescribeQuery() : void -> public executeSparqlQueryNoEngineWithDescribeQuery() : void +line range:181-182==line range:193-193 +public executeSparqlQueryNoEngineWithConstructQuery() : void -> public executeSparqlQueryNoEngineWithConstructQuery() : void +line range:191-192==line range:203-203 +public testInvalidQuery() : void -> public testInvalidQuery() : void +line range:98-98==line range:107-107 +public removeIncompleteSubGraph() : void -> public removeIncompleteSubGraph() : void +line range:85-85==line range:92-92 +public removeInvalidSubGraph() : void -> public removeInvalidSubGraph() : void +line range:101-101==line range:109-109 \ No newline at end of file diff --git a/src/test/resources/mappings/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.txt b/src/test/resources/mappings/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.txt new file mode 100644 index 0000000000..ceff346d60 --- /dev/null +++ b/src/test/resources/mappings/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.txt @@ -0,0 +1,76 @@ +public testNotNullNull() : void -> public testNotNullNull() : void +line range:33-33==line range:35-35 +public testDelimiterSameAsCommentStartThrowsException() : void -> public testDelimiterSameAsCommentStartThrowsException() : void +line range:77-77==line range:78-78 +public testDelimiterSameAsEscapeThrowsException() : void -> public testDelimiterSameAsEscapeThrowsException() : void +line range:82-82==line range:83-83 +public testDuplicateHeaderElementsFalse() : void -> public testDuplicateHeaderElementsFalse() : void +line range:95-95==line range:98-98 +public testEscapeSameAsCommentStartThrowsException() : void -> public testEscapeSameAsCommentStartThrowsException() : void +line range:525-525==line range:528-528 +public testEscapeSameAsCommentStartThrowsExceptionForWrapperType() : void -> public testEscapeSameAsCommentStartThrowsExceptionForWrapperType() : void +line range:531-531==line range:536-536 +public testQuoteCharSameAsCommentStartThrowsException() : void -> public testQuoteCharSameAsCommentStartThrowsException() : void +line range:664-664==line range:669-669 +public testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() : void -> public testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() : void +line range:670-670==line range:677-677 +public testQuoteCharSameAsDelimiterThrowsException() : void -> public testQuoteCharSameAsDelimiterThrowsException() : void +line range:675-675==line range:682-682 +public testQuotePolicyNoneWithoutEscapeThrowsException() : void -> public testQuotePolicyNoneWithoutEscapeThrowsException() : void +line range:680-680==line range:687-687 +public testWithCommentStartCRThrowsException() : void -> public testWithCommentStartCRThrowsException() : void +line range:896-896==line range:903-903 +public testWithDelimiterLFThrowsException() : void -> public testWithDelimiterLFThrowsException() : void +line range:907-907==line range:914-914 +public testWithEscapeCRThrowsExceptions() : void -> public testWithEscapeCRThrowsExceptions() : void +line range:924-924==line range:931-931 +public testWithQuoteLFThrowsException() : void -> public testWithQuoteLFThrowsException() : void +line range:1143-1143==line range:1150-1150 +public testClose() : void -> public testClose() : void +line range:255-255==line range:255-255 +public testDuplicateHeadersNotAllowed() : void -> public testDuplicateHeadersNotAllowed() : void +line range:297-298==line range:299-300 +public testHeadersMissingException() : void -> public testHeadersMissingException() : void +line range:722-722==line range:724-724 +public testInvalidFormat() : void -> public testInvalidFormat() : void +line range:749-749==line range:751-751 +public testNewCSVParserNullReaderFormat() : void -> public testNewCSVParserNullReaderFormat() : void +line range:926-926==line range:925-925 +public testNewCSVParserReaderNullFormat() : void -> public testNewCSVParserReaderNullFormat() : void +line range:933-933==line range:930-930 +public testParseFileNullFormat() : void -> public testParseFileNullFormat() : void +line range:980-980==line range:977-977 +public testParseNullFileFormat() : void -> public testParseNullFileFormat() : void +line range:987-987==line range:984-984 +public testParseNullPathFormat() : void -> public testParseNullPathFormat() : void +line range:994-994==line range:991-991 +public testParseNullStringFormat() : void -> public testParseNullStringFormat() : void +line range:1001-1001==line range:996-996 +public testParseNullUrlCharsetFormat() : void -> public testParseNullUrlCharsetFormat() : void +line range:1008-1008==line range:1003-1003 +public testParserUrlNullCharsetFormat() : void -> public testParserUrlNullCharsetFormat() : void +line range:1015-1015==line range:1010-1010 +public testParseStringNullFormat() : void -> public testParseStringNullFormat() : void +line range:1022-1022==line range:1015-1015 +public testParseUrlCharsetNullFormat() : void -> public testParseUrlCharsetNullFormat() : void +line range:1029-1029==line range:1022-1022 +public testInvalidFormat() : void -> public testInvalidFormat() : void +line range:583-583==line range:583-583 +public testNewCsvPrinterAppendableNullFormat() : void -> public testNewCsvPrinterAppendableNullFormat() : void +line range:884-884==line range:881-881 +public testNewCsvPrinterNullAppendableFormat() : void -> public testNewCsvPrinterNullAppendableFormat() : void +line range:891-891==line range:886-886 +public testGetStringInconsistentRecord() : void -> public testGetStringInconsistentRecord() : void +line range:79-79==line range:79-79 +public testGetStringNoHeader() : void -> public testGetStringNoHeader() : void +line range:84-84==line range:84-84 +public testGetUnmappedEnum() : void -> public testGetUnmappedEnum() : void +line range:89-89==line range:89-89 +public testGetUnmappedName() : void -> public testGetUnmappedName() : void +line range:94-94==line range:94-94 +public testGetUnmappedNegativeInt() : void -> public testGetUnmappedNegativeInt() : void +line range:99-99==line range:99-99 +public testGetUnmappedPositiveInt() : void -> public testGetUnmappedPositiveInt() : void +line range:104-104==line range:104-104 +public testEscapingAtEOF() : void -> public testEscapingAtEOF() : void +line range:388-388==line range:389-389 \ No newline at end of file diff --git a/src/test/resources/mappings/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.txt b/src/test/resources/mappings/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.txt new file mode 100644 index 0000000000..caf55a00fa --- /dev/null +++ b/src/test/resources/mappings/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.txt @@ -0,0 +1,13 @@ +public shouldHandleFatalException() : void -> public shouldHandleFatalException() : void +line range:35-35==line range:34-34 +public shouldTimeoutWaitFor() : void -> public shouldTimeoutWaitFor() : void +line range:27-27==line range:24-24 +public shouldThrowExceptionIfBufferIsFull() : void -> public shouldThrowExceptionIfBufferIsFull() : void +line range:154-154==line range:144-144 +public shouldInterruptDuringBusySpin() : void -> public shouldInterruptDuringBusySpin() : void +line range:112-112==line range:109-109 +line range:107-122==line range:108-109 +public shouldTryNext(sequencer Sequencer) : void -> public shouldTryNext(sequencer Sequencer) : void +line range:250-250==line range:247-247 +public shouldTimeoutWaitFor() : void -> public shouldTimeoutWaitFor() : void +line range:28-28==line range:25-25 \ No newline at end of file diff --git a/src/test/resources/mappings/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.txt b/src/test/resources/mappings/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.txt new file mode 100644 index 0000000000..becec260c4 --- /dev/null +++ b/src/test/resources/mappings/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.txt @@ -0,0 +1,41 @@ +public Iterable_next_throws_on_empty() : void -> public Iterable_next_throws_on_empty() : void +line range:240-240==line range:240-240 +public OrderedIterable_getFirstOptional_null_element() : void -> public OrderedIterable_getFirstOptional_null_element() : void +line range:98-98==line range:99-99 +public MutableBagIterable_addOccurrences_throws() : void -> public MutableBagIterable_addOccurrences_throws() : void +line range:46-46==line range:47-47 +public MutableBagIterable_removeOccurrences_throws() : void -> public MutableBagIterable_removeOccurrences_throws() : void +line range:72-72==line range:74-74 +line range:73-73==line range:75-75 +public Iterable_iterator_throws() : void -> public Iterable_iterator_throws() : void +line range:24-24==line range:26-26 +public List_get_negative() : void -> public List_get_negative() : void +line range:64-64==line range:64-64 +public List_get_out_of_bounds() : void -> public List_get_out_of_bounds() : void +line range:70-70==line range:70-70 +public MutableList_sortThis() : void -> public MutableList_sortThis() : void +line range:27-27==line range:28-28 +public MutableList_shuffleThis() : void -> public MutableList_shuffleThis() : void +line range:34-34==line range:35-35 +public MutableList_shuffleThis() : void -> public MutableList_shuffleThis() : void +line range:35-35==line range:36-36 +public MutableList_sortThis_comparator() : void -> public MutableList_sortThis_comparator() : void +line range:49-49==line range:51-51 +public Collection_add() : void -> public Collection_add() : void +line range:46-46==line range:48-48 +public Collection_add() : void -> public Collection_add() : void +line range:50-50==line range:51-51 +public RichIterable_getFirst_empty_null() : void -> public RichIterable_getFirst_empty_null() : void +line range:72-72==line range:72-72 +public RichIterable_getLast_empty_null() : void -> public RichIterable_getLast_empty_null() : void +line range:79-79==line range:79-79 +public OrderedIterable_getLastOptional() : void -> public OrderedIterable_getLastOptional() : void +line range:123-123==line range:124-124 +public OrderedIterable_getLastOptional_null_element() : void -> public OrderedIterable_getLastOptional_null_element() : void +line range:130-130==line range:132-132 +public StackIterable_peek_throws() : void -> public StackIterable_peek_throws() : void +line range:142-142==line range:144-144 +public MutableStack_pop() : void -> public MutableStack_pop() : void +line range:31-31==line range:33-33 +public MutableStack_pop_throws() : void -> public MutableStack_pop_throws() : void +line range:39-39==line range:41-41 \ No newline at end of file diff --git a/src/test/resources/mappings/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.txt b/src/test/resources/mappings/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.txt new file mode 100644 index 0000000000..ebf2742e0d --- /dev/null +++ b/src/test/resources/mappings/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.txt @@ -0,0 +1,50 @@ +public testValidateBadKey() : void -> public testValidateBadKey() : void +line range:83-89==line range:84-90 +public testValidateBadCert() : void -> public testValidateBadCert() : void +line range:94-100==line range:95-101 +public testUnknownWildcardSecret() : void -> public testUnknownWildcardSecret() : void +line range:46-46==line range:50-50 +public testInvalidToken() : void -> public testInvalidToken() : void +line range:90-90==line range:89-89 +public testSerializeAddressSpaceWithIllegalName() : void -> public testSerializeAddressSpaceWithIllegalName() : void +line range:114-114==line range:115-115 +public testDeserializeAddressSpaceMissingDefaults() : void -> public testDeserializeAddressSpaceMissingDefaults() : void +line range:213-213==line range:214-214 +public testDeserializeAddressMissingDefaults() : void -> public testDeserializeAddressMissingDefaults() : void +line range:219-219==line range:220-220 +public testDeserializeAddressSpaceWithMissingAuthServiceValues() : void -> public testDeserializeAddressSpaceWithMissingAuthServiceValues() : void +line range:408-408==line range:409-409 +public testDeserializeAddressSpaceWithExtraAuthServiceValues() : void -> public testDeserializeAddressSpaceWithExtraAuthServiceValues() : void +line range:430-430==line range:431-431 +public testBadInitialResponse() : void -> public testBadInitialResponse() : void +line range:135-135==line range:126-126 +public testBadInitialResponse() : void -> public testBadInitialResponse() : void +line range:114-114==line range:113-113 +public testSyncProvisioningRequest() : void -> public testSyncProvisioningRequest() : void +line range:43-43==line range:45-45 +public testBindOnNonexistentService() : void -> public testBindOnNonexistentService() : void +line range:68-68==line range:71-71 +public testBindWithoutServiceId() : void -> public testBindWithoutServiceId() : void +line range:74-74==line range:78-78 +public testBindWithoutPlanId() : void -> public testBindWithoutPlanId() : void +line range:79-79==line range:85-85 +public testWrongServiceId() : void -> public testWrongServiceId() : void +line range:85-85==line range:92-92 +public testWrongPlanId() : void -> public testWrongPlanId() : void +line range:91-91==line range:99-99 +public testUnbindNonexistingBinding() : void -> public testUnbindNonexistingBinding() : void +line range:126-126==line range:135-135 +public testSyncProvisioningRequest() : void -> public testSyncProvisioningRequest() : void +line range:43-43==line range:45-45 +public testInvalidServiceUuid() : void -> public testInvalidServiceUuid() : void +line range:48-48==line range:51-51 +public testInvalidPlan() : void -> public testInvalidPlan() : void +line range:53-53==line range:57-57 +public testInvalidServiceInstandeUuid() : void -> public testInvalidServiceInstandeUuid() : void +line range:58-58==line range:63-63 +public testDeprovisionNonexistingServiceInstance() : void -> public testDeprovisionNonexistingServiceInstance() : void +line range:131-131==line range:137-137 +public testDeprovisionWithoutServiceId() : void -> public testDeprovisionWithoutServiceId() : void +line range:136-136==line range:143-143 +public testDeprovisionWithoutPlanId() : void -> public testDeprovisionWithoutPlanId() : void +line range:141-141==line range:149-149 \ No newline at end of file diff --git a/src/test/resources/mappings/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.txt b/src/test/resources/mappings/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.txt new file mode 100644 index 0000000000..a1589fe956 --- /dev/null +++ b/src/test/resources/mappings/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.txt @@ -0,0 +1,75 @@ +public testMissingProfession() : void -> public testMissingProfession() : void +line range:42-42==line range:43-43 +public testMissingName() : void -> public testMissingName() : void +line range:50-50==line range:51-51 +public addingACustomerFailsWithExceptionAsFeedbackToClient() : void -> public addingACustomerFailsWithExceptionAsFeedbackToClient() : void +line range:214-214==line range:213-213 +public deletingACustomerFailsWithExceptionAsFeedbackToTheClient() : void -> public deletingACustomerFailsWithExceptionAsFeedbackToTheClient() : void +line range:219-219==line range:220-220 +public updatingACustomerFailsWithFeedbackToTheClient() : void -> public updatingACustomerFailsWithFeedbackToTheClient() : void +line range:227-227==line range:229-229 +public retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() : void -> public retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() : void +line range:232-232==line range:236-236 +public retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() : void -> public retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() : void +line range:237-237==line range:243-243 +public testUnsuccessfulSynchronousEvent() : void -> public testUnsuccessfulSynchronousEvent() : void +line range:76-76==line range:78-78 +line range:78-78==line range:80-80 +line range:79-79==line range:81-81 +line range:80-80==line range:82-82 +line range:81-81==line range:83-83 +line range:83-83==line range:85-85 +line range:77-84==line range:79-86 +line range:82-84==line range:84-86 +public testIoException() : void -> public testIoException() : void +line range:90-90==line range:94-94 +line range:91-93==line range:95-97 +line range:92-92==line range:96-96 +line range:91-93==line range:95-97 +public testNullPropertiesPassed() : void -> public testNullPropertiesPassed() : void +line range:42-42==line range:45-45 +public testNonBooleanProperty() : void -> public testNonBooleanProperty() : void +line range:47-47==line range:52-52 +line range:48-48==line range:53-53 +line range:49-49==line range:54-54 +public testAddUserToPaidWhenOnFree() : void -> public testAddUserToPaidWhenOnFree() : void +line range:53-53==line range:55-55 +public testAddUserToFreeWhenOnPaid() : void -> public testAddUserToFreeWhenOnPaid() : void +line range:60-60==line range:64-64 +public testNumbersCantBeModified() : void -> public testNumbersCantBeModified() : void +line range:56-56==line range:58-58 +public testBakeCakeMissingTopping() : void -> public testBakeCakeMissingTopping() : void +line range:136-136==line range:138-138 +public testBakeCakeMissingLayer() : void -> public testBakeCakeMissingLayer() : void +line range:154-154==line range:158-158 +public testBakeCakesUsedLayer() : void -> public testBakeCakesUsedLayer() : void +line range:177-177==line range:182-182 +public testForInvalidName() : void -> public testForInvalidName() : void +line range:45-45==line range:41-41 +line range:45-45==line range:41-41 +line range:45-45==line range:41-41 +public testForInvalidAge() : void -> public testForInvalidAge() : void +line range:52-54==line range:49-51 +line range:53-53==line range:50-50 +line range:52-52==line range:49-49 +line range:52-52==line range:49-49 +line range:53-53==line range:50-50 +public muteShouldRethrowUnexpectedExceptionAsAssertionError() : void -> public muteShouldRethrowUnexpectedExceptionAsAssertionError() : void +line range:59-59==line range:54-54 +line range:59-59==line range:54-54 +public testAddHeader() : void -> public testAddHeader() : void +line range:39-39==line range:41-41 +public testGetHeader() : void -> public testGetHeader() : void +line range:44-44==line range:48-48 +public testGetHeaders() : void -> public testGetHeaders() : void +line range:49-49==line range:55-55 +public testSetBody() : void -> public testSetBody() : void +line range:54-54==line range:62-62 +public testGetBody() : void -> public testGetBody() : void +line range:59-59==line range:69-69 +public testUnModifiableHeaders() : void -> public testUnModifiableHeaders() : void +line range:58-58==line range:60-60 +public oneException() : void -> public oneException() : void +line range:55-55==line range:58-58 +public constructorTest() : void -> public constructorTest() : void +line range:38-38==line range:39-39 \ No newline at end of file diff --git a/src/test/resources/mappings/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.txt b/src/test/resources/mappings/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.txt new file mode 100644 index 0000000000..9641d2129c --- /dev/null +++ b/src/test/resources/mappings/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.txt @@ -0,0 +1,2 @@ +public test4() : void -> public test4() : void +line range:54-54==line range:54-54 \ No newline at end of file diff --git a/src/test/resources/mappings/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.txt b/src/test/resources/mappings/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.txt new file mode 100644 index 0000000000..912afa116b --- /dev/null +++ b/src/test/resources/mappings/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.txt @@ -0,0 +1,14 @@ +private assertNoMoreItems(iterator PrimitiveIntIterator) : void -> private assertNoMoreItems(iterator PrimitiveIntIterator) : void +line range:216-216==line range:207-207 +public iteratorAsSet() : void -> package iteratorAsSet() : void +line range:149-149==line range:147-147 +public failToRemoveElementFromNewEmptyQueue() : void -> package failToRemoveElementFromNewEmptyQueue() : void +line range:76-76==line range:77-77 +public failToGetNextOnEmptyQueueIterator() : void -> package failToGetNextOnEmptyQueueIterator() : void +line range:182-182==line range:183-183 +public doNotAllowCreationOfQueueWithRandomCapacity() : void -> package doNotAllowCreationOfQueueWithRandomCapacity() : void +line range:209-209==line range:210-210 +private assertNoMoreItems(iterator PrimitiveLongIterator) : void -> private assertNoMoreItems(iterator PrimitiveLongIterator) : void +line range:267-267==line range:265-265 +public throwExceptionOnAccessingNonExistentElement() : void -> package throwExceptionOnAccessingNonExistentElement() : void +line range:81-81==line range:82-82 \ No newline at end of file diff --git a/src/test/resources/mappings/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.txt b/src/test/resources/mappings/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.txt new file mode 100644 index 0000000000..f0a50beab0 --- /dev/null +++ b/src/test/resources/mappings/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.txt @@ -0,0 +1,46 @@ +public TestThrowsExceptionOnUnknownPath() : void -> public TestThrowsExceptionOnUnknownPath() : void +line range:76-76==line range:77-77 +public TestThrowsExceptionOnEmptyXML() : void -> public TestThrowsExceptionOnEmptyXML() : void +line range:82-82==line range:85-85 +public checkThrowsErrorOnIsFlagTrueAndNegativeValue() : void -> public checkThrowsErrorOnIsFlagTrueAndNegativeValue() : void +line range:120-120==line range:122-122 +public checkThrowsErrorOnNotSupportedUnderlyingType() : void -> public checkThrowsErrorOnNotSupportedUnderlyingType() : void +line range:126-126==line range:130-130 +public checkThrowsExcpetionForNonPrimitiveParameter() : void -> public checkThrowsExcpetionForNonPrimitiveParameter() : void +line range:294-294==line range:296-296 +public checkThrowsExceptionIfCollectionAndReturnTypeEmpty() : void -> public checkThrowsExceptionIfCollectionAndReturnTypeEmpty() : void +line range:300-300==line range:304-304 +public checkThrowsExcpetionOnPrivateConstructor() : void -> public checkThrowsExcpetionOnPrivateConstructor() : void +line range:305-305==line range:311-311 +public checkThrowsExcpetionOnNoConstructorAsSpecified() : void -> public checkThrowsExcpetionOnNoConstructorAsSpecified() : void +line range:311-311==line range:318-318 +public checkThrowsExcpetionOnIsBoundWithoutEntityTypeParameter() : void -> public checkThrowsExcpetionOnIsBoundWithoutEntityTypeParameter() : void +line range:318-318==line range:326-326 +public checkThrowsExcpetionOnIsBoundWithoutParameter() : void -> public checkThrowsExcpetionOnIsBoundWithoutParameter() : void +line range:324-324==line range:334-334 +public checkThrowsExcpetionOnIsBoundBindingParameterNotFirst() : void -> public checkThrowsExcpetionOnIsBoundBindingParameterNotFirst() : void +line range:330-330==line range:342-342 +public checkThrowsExcpetionOnEntitySetGivenUnbound() : void -> public checkThrowsExcpetionOnEntitySetGivenUnbound() : void +line range:336-336==line range:350-350 +public checkThrowsExcpetionOnEntitySetGivenNoEntityReturnType() : void -> public checkThrowsExcpetionOnEntitySetGivenNoEntityReturnType() : void +line range:342-342==line range:358-358 +public checkThrowsExcpetionForNonPrimitiveParameter() : void -> public checkThrowsExcpetionForNonPrimitiveParameter() : void +line range:71-71==line range:76-76 +public checkThrowsExceptionIfAnnotatedReturnTypeNEDeclairedType() : void -> public checkThrowsExceptionIfAnnotatedReturnTypeNEDeclairedType() : void +line range:135-135==line range:142-142 +public checkThrowsExceptionIfCollectionAndReturnTypeEmpty() : void -> public checkThrowsExceptionIfCollectionAndReturnTypeEmpty() : void +line range:165-165==line range:175-175 +public checkThrowsExcpetionOnNotSupportedReturnType() : void -> public checkThrowsExcpetionOnNotSupportedReturnType() : void +line range:207-207==line range:219-219 +public checkThrowsExcpetionOnPrivateConstructor() : void -> public checkThrowsExcpetionOnPrivateConstructor() : void +line range:224-224==line range:238-238 +public checkThrowsExcpetionOnNoConstructorAsSpecified() : void -> public checkThrowsExcpetionOnNoConstructorAsSpecified() : void +line range:230-230==line range:245-245 +public checkThrowsAnExceptionTimestampWithoutPrecision() : void -> public checkThrowsAnExceptionTimestampWithoutPrecision() : void +line range:423-423==line range:426-426 +public testThrowsExceptionIfBeforeIfManaged() : void -> public testThrowsExceptionIfBeforeIfManaged() : void +line range:59-59==line range:61-61 +public testSetForeignKeyTrhowsExceptionOnMissingGetter() : void -> public testSetForeignKeyTrhowsExceptionOnMissingGetter() : void +line range:340-340==line range:341-341 +public testSetForeignKeyTrhowsExceptionOnMissingSetter() : void -> public testSetForeignKeyTrhowsExceptionOnMissingSetter() : void +line range:351-351==line range:354-354 \ No newline at end of file diff --git a/src/test/resources/mappings/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.txt b/src/test/resources/mappings/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.txt new file mode 100644 index 0000000000..2a85bea1e1 --- /dev/null +++ b/src/test/resources/mappings/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.txt @@ -0,0 +1,10 @@ +public getNotExistingDriverTest() : void -> package getNotExistingDriverTest() : void +line range:61-61==line range:66-66 +public getInvalidUriTest() : void -> package getInvalidUriTest() : void +line range:69-69==line range:76-76 +public getDuplicateDriver() : void -> package getDuplicateDriver() : void +line range:85-85==line range:95-95 +public getConnectionInvalidUrlTest() : void -> package getConnectionInvalidUrlTest() : void +line range:57-57==line range:61-61 +public getConnectionWithAuthenticationTest() : void -> package getConnectionWithAuthenticationTest() : void +line range:68-69==line range:74-75 \ No newline at end of file diff --git a/src/test/resources/mappings/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.txt b/src/test/resources/mappings/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.txt new file mode 100644 index 0000000000..a1d1e324a1 --- /dev/null +++ b/src/test/resources/mappings/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.txt @@ -0,0 +1,20 @@ +public shouldUseMixinConstructor() : void -> package shouldUseMixinConstructor() : void +line range:17-24==line range:19-27 +public shouldThrowForDuplicateStatusCode() : void -> package shouldThrowForDuplicateStatusCode() : void +line range:16-16==line range:18-18 +public shouldCoverUnreachableThrowStatement() : void -> package shouldCoverUnreachableThrowStatement() : void +line range:18-18==line range:20-20 +public shouldNotBeInstantiable() : void -> package shouldNotBeInstantiable() : void +line range:9-9==line range:11-11 +public shouldThrowOnCustomType() : void -> package shouldThrowOnCustomType() : void +line range:105-105==line range:106-106 +public shouldThrowOnCustomTitle() : void -> package shouldThrowOnCustomTitle() : void +line range:110-110==line range:111-111 +public shouldThrowOnCustomStatus() : void -> package shouldThrowOnCustomStatus() : void +line range:115-115==line range:116-116 +public shouldThrowOnCustomDetail() : void -> package shouldThrowOnCustomDetail() : void +line range:120-120==line range:121-121 +public shouldThrowOnCustomInstance() : void -> package shouldThrowOnCustomInstance() : void +line range:125-125==line range:126-126 +public shouldThrowOnCustomCause() : void -> package shouldThrowOnCustomCause() : void +line range:130-130==line range:131-131 \ No newline at end of file diff --git a/src/test/resources/mappings/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.txt b/src/test/resources/mappings/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.txt new file mode 100644 index 0000000000..1f486b9050 --- /dev/null +++ b/src/test/resources/mappings/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.txt @@ -0,0 +1,6 @@ +public testJsonProcessingException() : void -> public testJsonProcessingException() : void +line range:28-28==line range:30-30 +public testIoException() : void -> public testIoException() : void +line range:35-35==line range:39-39 +public testNullDynamoObject() : void -> public testNullDynamoObject() : void +line range:34-34==line range:34-34 \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java new file mode 100644 index 0000000000..f110041da6 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java @@ -0,0 +1,573 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.BlankNodeOrIRI; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.Language; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.TypedLiteralImpl; +import org.junit.Assert; + + + +/** + * A generic abstract test class, implementations overwrite this class, + * providing an implementation of the getEmptyGraph method. + * + * @author reto, szalay, mir, hhn + */ +public abstract class GraphTest { + + private final IRI uriRef1 = + new IRI("http://example.org/ontology#res1"); + private final IRI uriRef2 = + new IRI("http://example.org/ontology#res2"); + private final IRI uriRef3 = + new IRI("http://example.org/ontology#res3"); + private final IRI uriRef4 = + new IRI("http://example.org/ontology#res4"); + private final IRI xmlLiteralType = + new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"); + private Literal literal1 = new PlainLiteralImpl("literal1"); + private Literal literal2 = new PlainLiteralImpl("literal2"); + private BlankNode bnode1 = new BlankNode(); + private BlankNode bnode2 = new BlankNode(); + private Triple trpl1 = new TripleImpl(uriRef2, uriRef2, literal1); + private Triple trpl2 = new TripleImpl(uriRef1, uriRef2, uriRef1); + private Triple trpl3 = new TripleImpl(bnode2, uriRef3, literal2); + private Triple trpl4 = new TripleImpl(uriRef3, uriRef4, literal2); + + /** + * Subclasses implement this method to provide implementation instances of + * Graph. This method may be called an arbitrary amount of time, + * independently whether previously returned Graph are still in use or not. + * + * @return an empty Graph of the implementation to be tested + */ + protected abstract Graph getEmptyGraph(); + + @Test + public void testAddCountAndGetTriples() { + Graph graph = getEmptyGraph(); + Assert.assertEquals(0, graph.size()); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + graph.add(triple1); + Assert.assertEquals(1, graph.size()); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, uriRef1); + Assert.assertTrue(tripleIter.hasNext()); + Triple tripleGot = tripleIter.next(); + Assert.assertEquals(triple1, tripleGot); + Assert.assertFalse(tripleIter.hasNext()); + BlankNode bnode = new BlankNode() {}; + graph.add(new TripleImpl(bnode, uriRef1, uriRef3)); + graph.add(new TripleImpl(bnode, uriRef1, uriRef4)); + tripleIter = graph.filter(null, uriRef1, null); + Set subjectInMatchingTriples = new HashSet(); + Set objectsInMatchingTriples = new HashSet(); + while (tripleIter.hasNext()) { + Triple triple = tripleIter.next(); + subjectInMatchingTriples.add(triple.getSubject()); + objectsInMatchingTriples.add(triple.getObject()); + } + Assert.assertEquals(1, subjectInMatchingTriples.size()); + Assert.assertEquals(2, objectsInMatchingTriples.size()); + Set expectedObjects = new HashSet(); + expectedObjects.add(uriRef3); + expectedObjects.add(uriRef4); + Assert.assertEquals(expectedObjects, objectsInMatchingTriples); + graph.add(new TripleImpl(bnode, uriRef4, bnode)); + tripleIter = graph.filter(null, uriRef4, null); + Assert.assertTrue(tripleIter.hasNext()); + Triple retrievedTriple = tripleIter.next(); + Assert.assertFalse(tripleIter.hasNext()); + Assert.assertEquals(retrievedTriple.getSubject(), retrievedTriple.getObject()); + tripleIter = graph.filter(uriRef1, uriRef2, null); + Assert.assertTrue(tripleIter.hasNext()); + retrievedTriple = tripleIter.next(); + Assert.assertFalse(tripleIter.hasNext()); + Assert.assertEquals(retrievedTriple.getSubject(), retrievedTriple.getObject()); + } + + @Test + public void testRemoveAllTriples() { + Graph graph = getEmptyGraph(); + Assert.assertEquals(0, graph.size()); + graph.add(new TripleImpl(uriRef1, uriRef2, uriRef3)); + graph.add(new TripleImpl(uriRef2, uriRef3, uriRef4)); + Assert.assertEquals(2, graph.size()); + graph.clear(); + Assert.assertEquals(0, graph.size()); + } + + @Test + public void testUseTypedLiterals() { + Graph graph = getEmptyGraph(); + Assert.assertEquals(0, graph.size()); + Literal value = new TypedLiteralImpl("value",xmlLiteralType); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, value); + graph.add(triple1); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, null); + Assert.assertTrue(tripleIter.hasNext()); + RDFTerm gotValue = tripleIter.next().getObject(); + Assert.assertEquals(value, gotValue); + } + + @Test + public void testUseLanguageLiterals() { + Graph graph = getEmptyGraph(); + Assert.assertEquals(0, graph.size()); + Language language = new Language("it"); + Literal value = new PlainLiteralImpl("value",language); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, value); + graph.add(triple1); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, null); + Assert.assertTrue(tripleIter.hasNext()); + RDFTerm gotValue = tripleIter.next().getObject(); + Assert.assertEquals(value, gotValue); + Assert.assertEquals(language, ((Literal)gotValue).getLanguage()); + } + + @Test + public void testRemoveViaIterator() { + Graph graph = getEmptyGraph(); + Assert.assertEquals(0, graph.size()); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + graph.add(triple1); + final TripleImpl triple2 = new TripleImpl(uriRef1, uriRef2, uriRef4); + graph.add(triple2); + Assert.assertEquals(2, graph.size()); + Iterator iterator = graph.iterator(); + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + Assert.assertEquals(0, graph.size()); + } + + @Test + public void testGetSize() throws Exception { + Graph graph = getEmptyGraph(); + // The test graph must always be empty after test fixture setup + Assert.assertEquals(0, graph.size()); + } + + + @Test + public void testAddSingleTriple() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertEquals(0, graph.size()); + Assert.assertTrue(graph.add(triple)); + Assert.assertEquals(1, graph.size()); + } + + + @Test + public void testAddSameTripleTwice() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertEquals(0, graph.size()); + Assert.assertTrue(graph.add(triple)); + Assert.assertFalse(graph.add(triple)); // ImmutableGraph does not change + Assert.assertEquals(1, graph.size()); + } + + + @Test + public void testRemoveSingleTriple() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertTrue(graph.add(triple)); + Assert.assertTrue(graph.remove(triple)); + Assert.assertEquals(0, graph.size()); + } + + @Test + public void testRemoveSameTripleTwice() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAlice= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleBob= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + Assert.assertTrue(graph.add(tripleAlice)); + Assert.assertTrue(graph.add(tripleBob)); + Assert.assertTrue(graph.remove(tripleAlice)); + Assert.assertFalse(graph.remove(tripleAlice)); + Assert.assertEquals(1, graph.size()); + } + + @Test + public void testGetSameBlankNode() throws Exception { + Graph graph = getEmptyGraph(); + BlankNode bNode = new BlankNode(); + final IRI HAS_NAME = new IRI("http://example.org/ontology/hasName"); + final PlainLiteralImpl name = new PlainLiteralImpl("http://example.org/people/alice"); + final PlainLiteralImpl name2 = new PlainLiteralImpl("http://example.org/people/bob"); + final Triple tripleAlice = new TripleImpl(bNode, HAS_NAME, name); + final Triple tripleBob = new TripleImpl(bNode, HAS_NAME, name2); + Assert.assertTrue(graph.add(tripleAlice)); + Assert.assertTrue(graph.add(tripleBob)); + Iterator result = graph.filter(null, HAS_NAME, name); + Assert.assertEquals(bNode, result.next().getSubject()); + } + + @Test + public void testContainsIfContained() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertTrue(graph.add(triple)); + Assert.assertTrue(graph.contains(triple)); + } + + + @Test + public void testContainsIfEmpty() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertFalse(graph.contains(triple)); + } + + + @Test + public void testContainsIfNotContained() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAdd= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleTest= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + Assert.assertTrue(graph.add(tripleAdd)); + Assert.assertFalse(graph.contains(tripleTest)); + } + + + @Test + public void testFilterEmptyGraph() throws Exception { + Graph graph = getEmptyGraph(); + Iterator i = graph.filter(null, null, null); + Assert.assertFalse(i.hasNext()); + } + + + @Test + public void testFilterSingleEntry() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + Assert.assertTrue(graph.add(triple)); + + Iterator i = graph.filter(null, null, null); + Collection resultSet= toCollection(i); + Assert.assertEquals(1, resultSet.size()); + Assert.assertTrue(resultSet.contains(triple)); + } + + + @Test + public void testFilterByObject() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAlice= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleBob= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + Assert.assertTrue(graph.add(tripleAlice)); + Assert.assertTrue(graph.add(tripleBob)); + + Iterator iterator; + Collection resultSet; + + // Find bob + iterator = graph.filter(null, null, + new IRI("http://example.org/people/bob")); + resultSet= toCollection(iterator); + Assert.assertEquals(1, resultSet.size()); + Assert.assertTrue(resultSet.contains(tripleBob)); + + // Find alice + iterator = graph.filter(null, null, + new IRI("http://example.org/people/alice")); + resultSet= toCollection(iterator); + Assert.assertEquals(1, resultSet.size()); + Assert.assertTrue(resultSet.contains(tripleAlice)); + + // Find both + iterator = graph.filter(null, null, null); + resultSet= toCollection(iterator); + Assert.assertEquals(2, resultSet.size()); + Assert.assertTrue(resultSet.contains(tripleAlice)); + Assert.assertTrue(resultSet.contains(tripleBob)); + } +/* + @Test + public void graphEventTestAddRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + Assert.assertNull(listener.getEvents()); + mGraph.add(trpl2); + Assert.assertEquals(1, listener.getEvents().size()); + Assert.assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof AddEvent); + listener.resetEvents(); + mGraph.remove(trpl2); + Assert.assertEquals(1, listener.getEvents().size()); + Assert.assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof RemoveEvent); + listener.resetEvents(); + mGraph.add(trpl3); + Assert.assertEquals(1, listener.getEvents().size()); + Assert.assertEquals(trpl3, listener.getEvents().get(0).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof AddEvent); + listener.resetEvents(); + mGraph.remove(trpl4); + Assert.assertNull(listener.getEvents()); + } + + @Test + public void graphEventTestAddAllRemoveAll() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + Graph triples = new SimpleGraph(); + triples.add(trpl1); + triples.add(trpl2); + triples.add(trpl3); + triples.add(trpl4); + mGraph.addAll(triples); + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + Assert.assertEquals(3, cumulatedEvents.size()); + Assert.assertTrue(cumulatedEvents.get(0) instanceof AddEvent); + Assert.assertTrue(cumulatedTriples.contains(trpl2)); + Assert.assertTrue(cumulatedTriples.contains(trpl3)); + Assert.assertTrue(cumulatedTriples.contains(trpl4)); + listener.resetCumulatedEvents(); + mGraph.removeAll(triples); + cumulatedEvents = listener.getCumulatedEvents(); + cumulatedTriples = getCumulatedTriples(cumulatedEvents); + Assert.assertEquals(3, cumulatedEvents.size()); + Assert.assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + Assert.assertTrue(cumulatedTriples.contains(trpl2)); + Assert.assertTrue(cumulatedTriples.contains(trpl3)); + Assert.assertTrue(cumulatedTriples.contains(trpl4)); + } + + @Test + public void graphEventTestFilterRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + Iterator result = mGraph.filter(null, uriRef2, null); + while (result.hasNext()) { + result.next(); + result.remove(); + } + List cumulatedEvents = listener.getCumulatedEvents(); + Assert.assertEquals(1, cumulatedEvents.size()); + Assert.assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + Assert.assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + } + + @Test + public void graphEventTestIteratorRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + Iterator result = mGraph.iterator(); + while (result.hasNext()) { + result.next(); + result.remove(); + } + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + Assert.assertEquals(3, cumulatedEvents.size()); + Assert.assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + Assert.assertTrue(cumulatedTriples.contains(trpl2)); + Assert.assertTrue(cumulatedTriples.contains(trpl3)); + Assert.assertTrue(cumulatedTriples.contains(trpl4)); + } + + @Test + public void graphEventTestClear() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + mGraph.clear(); + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + Assert.assertEquals(3, cumulatedEvents.size()); + Assert.assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + Assert.assertTrue(cumulatedTriples.contains(trpl2)); + Assert.assertTrue(cumulatedTriples.contains(trpl3)); + Assert.assertTrue(cumulatedTriples.contains(trpl4)); + } + + private Set getCumulatedTriples(List cumulatedEvents) { + Set triples = new HashSet(); + for(GraphEvent event: cumulatedEvents) { + triples.add(event.getTriple()); + } + return triples; + } + + @Test + public void graphEventTestWithDelay() throws Exception{ + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null), + 1000); + + Triple triple0 = new TripleImpl(uriRef2, uriRef2, literal1); + Triple triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + Triple triple2 = new TripleImpl(uriRef1, uriRef2, literal1); + Triple triple3 = new TripleImpl(uriRef1, uriRef2, bnode1); + mGraph.add(triple0); + mGraph.add(triple1); + mGraph.add(triple2); + mGraph.add(triple3); + Thread.sleep(1500); + Assert.assertEquals(3, listener.getEvents().size()); + Assert.assertEquals(triple1, listener.getEvents().get(0).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof AddEvent); + Assert.assertEquals(triple2, listener.getEvents().get(1).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof AddEvent); + Assert.assertEquals(triple3, listener.getEvents().get(2).getTriple()); + Assert.assertTrue(listener.getEvents().get(0) instanceof AddEvent); + } + + private static class TestGraphListener implements GraphListener { + private List events = null; + private List cumulatedEvents = new ArrayList(); + + @Override + public void graphChanged(List events) { + this.events = events; + Iterator eventIter = events.iterator(); + while (eventIter.hasNext()) { + GraphEvent graphEvent = eventIter.next(); + this.cumulatedEvents.add(graphEvent); + } + } + + public List getEvents() { + return events; + } + + public List getCumulatedEvents() { + return cumulatedEvents; + } + + public void resetEvents() { + events = null; + } + + public void resetCumulatedEvents() { + cumulatedEvents = new ArrayList(); + } + } +*/ + private Collection toCollection(Iterator iterator) { + Collection result = new ArrayList(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + return result; + } + + /** + * Creates a new Triple. + * @param subject the subject. + * @param predicate the predicate. + * @param object the object. + * @throws IllegalArgumentException If an attribute is null. + */ + private Triple createTriple(String subject, String predicate, + String object) { + return new TripleImpl(new IRI(subject), new IRI(predicate), + new IRI(object)); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java new file mode 100644 index 0000000000..bea479db02 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java @@ -0,0 +1,484 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.test; + +import java.util.HashSet; +import java.util.Iterator; + +import java.util.Set; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.ImmutableGraph; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.BlankNodeOrIRI; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException; +import org.apache.clerezza.rdf.core.access.NoSuchEntityException; + +import org.apache.clerezza.rdf.core.access.TcProvider; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import static org.junit.Assert.*; + +/** + * + * @author mir,rbn + */ +public abstract class TcProviderTest { + + protected final IRI uriRefA = generateUri("a"); + protected final IRI uriRefA1 = generateUri("a1"); + protected final IRI uriRefB = generateUri("b"); + protected final IRI uriRefB1 = generateUri("b1"); + protected final IRI uriRefC = generateUri("c"); + + protected final IRI graphIRI = generateUri("myGraph"); + protected final IRI otherGraphIRI = new IRI(graphIRI.getUnicodeString()); + + @Test + public void testCreateImmutableGraph() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + + ImmutableGraph createdGraph = simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + + Iterator iteratorInput = mGraph.iterator(); + Iterator iteratorCreated = createdGraph.iterator(); + assertEquals(iteratorInput.next(), iteratorCreated.next()); + assertFalse(iteratorCreated.hasNext()); + + try { + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + assertTrue(false); + } catch (EntityAlreadyExistsException e) { + assertTrue(true); + } + simpleTcmProvider.deleteGraph(uriRefA); + } + + @Test + public void testCreateGraph() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = simpleTcmProvider.createGraph(uriRefA); + assertTrue(mGraph.isEmpty()); + + try { + simpleTcmProvider.createGraph(uriRefA); + assertTrue(false); + } catch (EntityAlreadyExistsException e) { + assertTrue(true); + } + simpleTcmProvider.deleteGraph(uriRefA); + } + + @Test + public void testGetImmutableGraph() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + simpleTcmProvider.createImmutableGraph(uriRefA1, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + simpleTcmProvider.createImmutableGraph(uriRefB, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + simpleTcmProvider.createImmutableGraph(uriRefB1, mGraph); + + ImmutableGraph bGraph = simpleTcmProvider.getImmutableGraph(uriRefB); + Iterator iterator = bGraph.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + } + + @Test + public void testGetGraph() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = simpleTcmProvider.createGraph(uriRefA); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + mGraph = simpleTcmProvider.createGraph(uriRefA1); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + mGraph = simpleTcmProvider.createGraph(uriRefB); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefA)); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + mGraph.remove(new TripleImpl(uriRefB, uriRefB, uriRefA)); + assertEquals(1, mGraph.size()); + mGraph = simpleTcmProvider.createGraph(uriRefB1); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + + Graph bGraph = simpleTcmProvider.getGraph(uriRefB); + Iterator iterator = bGraph.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + + } + + @Test + public void testGetTriples() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + simpleTcmProvider.createImmutableGraph(uriRefB, mGraph); + // add Graphs + mGraph = simpleTcmProvider.createGraph(uriRefA1); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + mGraph = simpleTcmProvider.createGraph(uriRefB1); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + + // get a ImmutableGraph + Graph tripleCollection = simpleTcmProvider.getGraph(uriRefA); + // get a Graph + Graph tripleCollection2 = simpleTcmProvider.getGraph(uriRefB1); + + Iterator iterator = tripleCollection.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + + iterator = tripleCollection2.iterator(); + assertEquals(new TripleImpl(uriRefB1, uriRefB1, uriRefB1), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + } + + @Test + public void testDeleteEntity() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + ImmutableGraph graph = mGraph.getImmutableGraph(); + simpleTcmProvider.createImmutableGraph(uriRefA, graph); + simpleTcmProvider.createImmutableGraph(uriRefC, graph); + + simpleTcmProvider.deleteGraph(uriRefA); + try { + simpleTcmProvider.getGraph(uriRefA); + assertTrue(false); + } catch (NoSuchEntityException e) { + assertTrue(true); + } + + // Check that graph is still available under uriRefC + ImmutableGraph cGraph = simpleTcmProvider.getImmutableGraph(uriRefC); + assertNotNull(cGraph); + simpleTcmProvider.deleteGraph(uriRefC); + } + + /** + * Subclasses implement this method to provide implementation instances of + * TcProvider. The first call within a test method has to + * return a empty TcProvider. Subsequent calls within the test method + * should instantiate a new provider, but load the previously added data from + * its "persistent" store. + * + * @return a TcProvider of the implementation to be tested. + */ + protected abstract TcProvider getInstance(); + +// @Test +// public void testGetNames() { +// Graph mGraph = new SimpleGraph(); +// mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); +// simpleTcmProvider.createGraph(uriRefB, mGraph.getGraph()); +// +// mGraph = new SimpleGraph(); +// mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); +// ImmutableGraph graph = mGraph.getGraph(); +// simpleTcmProvider.createGraph(uriRefA, graph); +// simpleTcmProvider.createGraph(uriRefC, graph); +// +// Set names = simpleTcmProvider.getNames(graph); +// +// assertTrue(names.contains(uriRefA)); +// assertTrue(names.contains(uriRefC)); +// assertEquals(2, names.size()); +// +// assertFalse(names.contains(uriRefB)); +// } + + @Test + public void testCreateGraphExtended() throws Exception { + + TcProvider provider = getInstance(); + Graph graph = provider.createGraph(graphIRI); + assertNotNull(graph); + //get a new provider and check that graph is there + provider = getInstance(); + graph = provider.getGraph(graphIRI); + assertNotNull(graph); + //check that there is no such graph, but only the mgraph + boolean expThrown = false; + try { + ImmutableGraph g = provider.getImmutableGraph(graphIRI); + } catch(NoSuchEntityException e) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateImmutableGraphExtended() throws Exception { + + TcProvider provider = getInstance(); + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, null); + + assertNotNull(graph); + + //get a new provider and check that graph is there + provider = getInstance(); + graph = provider.getImmutableGraph(graphIRI); + assertNotNull(graph); + + //check that there is no such mgraph, but only the graph + boolean expThrown = false; + + try { + Graph g = provider.getMGraph(graphIRI); + } catch(NoSuchEntityException e) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphNoDuplicateNames() throws Exception { + + TcProvider provider = getInstance(); + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, null); + assertNotNull(graph); + boolean expThrown = false; + try { + ImmutableGraph other = provider.createImmutableGraph(otherGraphIRI, null); + } catch(EntityAlreadyExistsException eaee) { + expThrown = true; + } + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphNoDuplicateNames2() throws Exception { + + TcProvider provider = getInstance(); + Graph graph = provider.createGraph(graphIRI); + assertNotNull(graph); + boolean expThrown = false; + try { + Graph other = provider.createGraph(otherGraphIRI); + } catch(EntityAlreadyExistsException eaee) { + expThrown = true; + } + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphWithInitialCollection() throws Exception { + + Triple t1 = createTestTriple(); + + TcProvider provider = getInstance(); + + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, createTestTripleCollection(t1)); + + assertEquals(1, graph.size()); + assertTrue(graph.contains(t1)); + provider.deleteGraph(graphIRI); + } + + @Test + public void testGraphIsNotMutable() throws Exception { + + Triple t1 = createTestTriple(); + Set t = new HashSet(); + t.add(t1); + + TcProvider provider = getInstance(); + + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, createTestTripleCollection(t1)); + + boolean expThrown = false; + + try { + graph.add(t1); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + expThrown = false; + + try { + graph.remove(t1); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + expThrown = false; + + try { + graph.addAll(t); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + + expThrown = false; + + try { + graph.clear(); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + + expThrown = false; + + try { + graph.removeAll(t); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + +// This tests can not pass, because equals in AbstractGraph is not implemented +// yet. +// @Test +// public void testGraphHasName() throws Exception { +// +// TcProvider provider = getInstance(); +// +// Graph triples = createTestTripleCollection(createTestTriple()); +// ImmutableGraph graph = provider.createGraph(graphIRI, triples); +// +// provider = getInstance(); +// Set names = provider.getNames(graph); +// assertTrue(names.contains(graphIRI)); +// } +// +// @Test +// public void testCreateSameGraphWithDifferentNames() throws Exception { +// +// Graph triples = createTestTripleCollection(createTestTriple()); +// +// TcProvider provider = getInstance(); +// IRI name1 = new IRI("http://myGraph1"); +// ImmutableGraph graph = provider.createGraph(name1, triples); +// +// IRI name2 = new IRI("http://myGraph2"); +// ImmutableGraph secondGraph = provider.createGraph(name2, triples); +// +// Set names = provider.getNames(graph); +// assertNotNull(names); +// assertEquals(2, names.size()); +// } + + @Test + public void testGraphDeletion() throws Exception { + + Graph triples = createTestTripleCollection(createTestTriple()); + + TcProvider provider = getInstance(); + IRI name1 = new IRI("http://myGraph1"); + ImmutableGraph graph = provider.createImmutableGraph(name1, triples); + + IRI name2 = new IRI("http://myGraph2"); + ImmutableGraph secondGraph = provider.createImmutableGraph(name2, triples); + + //if we delete graph with name1, the second graph should still be there + provider.deleteGraph(name1); + + provider = getInstance(); + ImmutableGraph firstGraph = provider.getImmutableGraph(name2); + assertNotNull(firstGraph); + + //check second name is not there + boolean expThrown = false; + + try { + ImmutableGraph g = provider.getImmutableGraph(name1); + } catch(NoSuchEntityException nses) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(name2); + } + + + + @Test + public void testGetTriplesGraph() throws Exception { + TcProvider provider = getInstance(); + + Graph graph = provider.createGraph(graphIRI); + + Graph tc = provider.getGraph(graphIRI); + assertNotNull(tc); + provider.deleteGraph(graphIRI); + } + + private Triple createTestTriple() { + BlankNodeOrIRI subject = new BlankNode() {}; + IRI predicate = new IRI("http://test.com/"); + BlankNodeOrIRI object = new IRI("http://test.com/myObject"); + return new TripleImpl(subject, predicate, object); + } + + private Graph createTestTripleCollection(Triple t) { + Set ts = new HashSet(); + ts.add(t); + return new SimpleGraph(ts); + } + + protected IRI generateUri(String name) { + return new IRI("http://example.org/" + name); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java new file mode 100644 index 0000000000..21d53c367f --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + + +import org.apache.clerezza.commons.rdf.Language; +import org.junit.Assert; +import org.junit.Test; + + +/** + * + * @author reto + */ +public class LanguageTest { + + @Test + public void languageEqualityTest() { + Language lang1 = new Language("DE"); + Language lang2 = new Language("DE"); + Assert.assertEquals(lang1, lang2); + Assert.assertEquals(lang1.hashCode(), lang2.hashCode()); + Language lang3 = new Language("EN"); + Assert.assertFalse(lang1.equals(lang3)); + } + + @Test + public void toStringTest() { + final String id = "de"; + Language lang1 = new Language(id); + Assert.assertEquals(lang1.toString(), id); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java new file mode 100644 index 0000000000..f0dbd799d3 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java @@ -0,0 +1,122 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + + +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.IRI; +import java.util.Arrays; +import java.util.Date; +import org.junit.Test; + +import junit.framework.Assert; + +/** + * + * @author reto + */ +public class LiteralFactoryTest { + + /** + * Test that a NoConvertorException thrown for an unsupported convertor + */ + @Test(expected=NoConvertorException.class) + public void unavailableConvertor() { + Object value = new Object() {}; + LiteralFactory.getInstance().createTypedLiteral(value); + } + + /** + * Test conversion of byte[] to literal an back + */ + @Test + public void byteArrayConversion() { + byte[] bytes = new byte[5]; + for (byte i = 0; i < bytes.length; i++) { + bytes[i] = i; + } + Literal literal = LiteralFactory.getInstance().createTypedLiteral(bytes); + Assert.assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#base64Binary"), + literal.getDataType()); + //we are using bytes.getClass() but there should be a way to get + //that instance of Class without getting it from an instance + //but this is java-bug 4071439 (would like byte[].class or byte.class.getArrayType()) + byte[] bytesBack = LiteralFactory.getInstance().createObject(bytes.getClass(), literal); + Assert.assertTrue(Arrays.equals(bytes, bytesBack)); + + } + + /** + * Test conversion of java.util.Date to literal an back + */ + @Test + public void dateConversion() { + Date date = new Date(); + Literal literal = LiteralFactory.getInstance().createTypedLiteral(date); + Assert.assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#dateTime"), + literal.getDataType()); + Date dateBack = LiteralFactory.getInstance().createObject(Date.class, literal); + Assert.assertEquals(date.getTime(), dateBack.getTime()); + + } + + /** + * Test conversion of String to literal an back + */ + @Test + public void stringConversion() { + String value = "Hello world"; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + Assert.assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#string"), + literal.getDataType()); + String valueBack = LiteralFactory.getInstance().createObject(String.class, literal); + Assert.assertEquals(value, valueBack); + + } + + /** + * Test conversion of Integer to literal an back + */ + @Test + public void intConversion() { + int value = 3; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + Assert.assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#int"), + literal.getDataType()); + Integer valueBack = LiteralFactory.getInstance().createObject(Integer.class, literal); + Assert.assertEquals(value, valueBack.intValue()); + + } + + /** + * Test conversion of Long to literal an back + */ + @Test + public void longConversion() { + long value = 332314646; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + Assert.assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#long"), + literal.getDataType()); + Long valueBack = LiteralFactory.getInstance().createObject(Long.class, literal); + Assert.assertEquals(value, valueBack.longValue()); + + } + + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java new file mode 100644 index 0000000000..71d68467f6 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + +import org.apache.clerezza.commons.rdf.IRI; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import org.junit.Test; +import junit.framework.Assert; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author reto + */ +public class UriRefTest { + + private Logger logger = LoggerFactory.getLogger(UriRefTest.class); + + @Test + public void uriRefEqualityTest() { + try { + String uriRefString = "http://example.org/üöä"; + IRI uriRef1 = new IRI(uriRefString); + IRI uriRef2 = new IRI(uriRefString); + Assert.assertEquals(uriRef1, uriRef2); + IRI uriRef3 = + new IRI(URLEncoder.encode(uriRefString, "utf-8")); + Assert.assertFalse(uriRef1.equals(uriRef3)); + } catch (UnsupportedEncodingException ex) { + logger.error("Exception {} ", ex); + } + } + + @Test + public void toStringTest() { + String uriRefString = "http://example.org/üöä"; + IRI uriRef = new IRI(uriRefString); + Assert.assertEquals("<"+uriRefString+">", uriRef.toString()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java new file mode 100644 index 0000000000..36d869263d --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.access; + +import java.io.FilePermission; +import java.lang.reflect.ReflectPermission; +import java.security.AccessControlException; +import java.security.CodeSource; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Policy; +import java.util.Collections; +import java.util.PropertyPermission; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; +import org.apache.clerezza.rdf.core.access.providers.WeightedDummy; +import org.apache.clerezza.rdf.core.access.security.TcPermission; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; + +/** + * + * @author reto + */ +public class SecurityTest { + + public SecurityTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + ////needed to unbind because this is injected with META-INF/services - file + TcManager.getInstance().unbindWeightedTcProvider(new WeightedA()); + TcManager.getInstance().bindWeightedTcProvider(new WeightedDummy()); + TcManager.getInstance().createGraph(new IRI("http://example.org/ImmutableGraph/alreadyexists")); + TcManager.getInstance().createGraph(new IRI("http://example.org/read/ImmutableGraph")); + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() { + + Policy.setPolicy(new Policy() { + + @Override + public PermissionCollection getPermissions(CodeSource codeSource) { + PermissionCollection result = new Permissions(); + result.add(new TcPermission("http://example.org/permitted", "read")); + result.add(new TcPermission("http://example.org/ImmutableGraph/alreadyexists", "readwrite")); + result.add(new TcPermission("http://example.org/read/ImmutableGraph", "read")); + result.add(new TcPermission("http://example.org/area/allowed/*", "readwrite")); + result.add(new TcPermission("urn:x-localinstance:/graph-access.graph", "readwrite")); + //result.add(new AllPermission()); + result.add(new RuntimePermission("*")); + result.add(new ReflectPermission("suppressAccessChecks")); + result.add(new PropertyPermission("*", "read")); + //(java.util.PropertyPermission line.separator read) + result.add(new FilePermission("/-", "read,write")); + return result; + } + }); + System.setSecurityManager(new SecurityManager() { + + @Override + public void checkPermission(Permission perm) { + //System.out.println("Checking "+perm); + super.checkPermission(perm); + } + + @Override + public void checkPermission(Permission perm, Object context) { + //System.out.println("Checking "+perm); + super.checkPermission(perm, context); + } + + }); + } + + @After + public void tearDown() { + System.setSecurityManager(null); + } + + + @Test(expected=NoSuchEntityException.class) + public void testAcessGraph() { + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/permitted")); + } + + @Test(expected=AccessControlException.class) + public void testNoWildCard() { + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/permitted/subthing")); + } + + @Test(expected=NoSuchEntityException.class) + public void testAllowedArea() { + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/area/allowed/something")); + } + + @Test(expected=AccessControlException.class) + public void testAcessForbiddenGraph() { + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/forbidden")); + } + + @Test(expected=NoSuchEntityException.class) + public void testCustomPermissions() { + IRI graphUri = new IRI("http://example.org/custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadPermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + System.out.print(ag.toString()); + TcManager.getInstance().getMGraph(graphUri); + } + + @Test(expected=AccessControlException.class) + public void testCustomPermissionsIncorrect() { + IRI graphUri = new IRI("http://example.org/custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadPermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + System.out.print(ag.toString()); + TcManager.getInstance().createGraph(graphUri); + } + + @Test + public void testCustomReadWritePermissions() { + IRI graphUri = new IRI("http://example.org/read-write-custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadWritePermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + System.out.print(ag.toString()); + TcManager.getInstance().createGraph(graphUri); + } + + @Test(expected=EntityAlreadyExistsException.class) + public void testCreateMGraph() { + TcManager.getInstance().createGraph(new IRI("http://example.org/ImmutableGraph/alreadyexists")); + } + @Test(expected=AccessControlException.class) + public void testCreateMGraphWithoutWritePermission() { + TcManager.getInstance().createGraph(new IRI("http://example.org/read/ImmutableGraph")); + } + @Test(expected=ReadOnlyException.class) + public void testAddTripleToMGraph() { + Graph graph = TcManager.getInstance().getMGraph(new IRI("http://example.org/read/ImmutableGraph")); + Triple triple = new TripleImpl(new IRI("http://example.org/definition/isNonLiteral"), new IRI("http://example.org/definition/isTest"), new PlainLiteralImpl("test")); + graph.add(triple); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java new file mode 100644 index 0000000000..181e36fa37 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java @@ -0,0 +1,302 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.access; + +import java.lang.reflect.Field; +import java.util.Iterator; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.apache.clerezza.commons.rdf.ImmutableGraph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; +import org.apache.clerezza.rdf.core.access.providers.WeightedA1; +import org.apache.clerezza.rdf.core.access.providers.WeightedAHeavy; +import org.apache.clerezza.rdf.core.access.providers.WeightedBlight; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleMGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.core.sparql.NoQueryEngineException; +import org.apache.clerezza.rdf.core.sparql.QueryEngine; +import org.apache.clerezza.rdf.core.sparql.query.AskQuery; +import org.apache.clerezza.rdf.core.sparql.query.ConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.DescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.Query; +import org.apache.clerezza.rdf.core.sparql.query.SelectQuery; + +import static org.junit.Assert.*; + +/** + * + * @author reto + */ +public class TcManagerTest { + + public static IRI uriRefAHeavy = new IRI("http://example.org/aHeavy"); + public static IRI uriRefB = new IRI("http://example.org/b");; + public static final IRI uriRefA = new IRI("http://example.org/a"); + public static final IRI uriRefA1 = new IRI("http://example.org/a1"); + private TcManager graphAccess; + private QueryEngine queryEngine; + private final WeightedA weightedA = new WeightedA(); + private final WeightedA1 weightedA1 = new WeightedA1(); + private WeightedTcProvider weightedBlight = new WeightedBlight(); + + @Before + public void setUp() { + graphAccess = TcManager.getInstance(); + graphAccess.bindWeightedTcProvider(weightedA); + graphAccess.bindWeightedTcProvider(weightedA1); + graphAccess.bindWeightedTcProvider(weightedBlight); + + queryEngine = Mockito.mock(QueryEngine.class); + } + + @After + public void tearDown() { + graphAccess = TcManager.getInstance(); + graphAccess.unbindWeightedTcProvider(weightedA); + graphAccess.unbindWeightedTcProvider(weightedA1); + graphAccess.unbindWeightedTcProvider(weightedBlight); + + queryEngine = null; + } + + @Test + public void getGraphFromA() { + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromB() { + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefB); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefB); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromAAfterUnbinding() { + graphAccess.unbindWeightedTcProvider(weightedA); + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefA1, uriRefA1, uriRefA1), + iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefA1, uriRefA1, uriRefA1), + iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromAWithHeavy() { + final WeightedAHeavy weightedAHeavy = new WeightedAHeavy(); + graphAccess.bindWeightedTcProvider(weightedAHeavy); + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefAHeavy, uriRefAHeavy, uriRefAHeavy), + iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefAHeavy, uriRefAHeavy, uriRefAHeavy), + iterator.next()); + assertFalse(iterator.hasNext()); + graphAccess.unbindWeightedTcProvider(weightedAHeavy); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithString() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess.executeSparqlQuery("", new SimpleMGraph()); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess.executeSparqlQuery((Query) null, new SimpleMGraph()); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithSelectQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess.executeSparqlQuery((SelectQuery) null, new SimpleMGraph()); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithAskQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess.executeSparqlQuery((AskQuery) null, new SimpleMGraph()); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithDescribeQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess + .executeSparqlQuery((DescribeQuery) null, new SimpleMGraph()); + } + + @Test(expected = NoQueryEngineException.class) + public void executeSparqlQueryNoEngineWithConstructQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + graphAccess.executeSparqlQuery((ConstructQuery) null, + new SimpleMGraph()); + } + + @Test + public void executeSparqlQueryWithEngineWithString() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + + // Execute + graphAccess.executeSparqlQuery("", Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, ""); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), + (Query) Mockito.anyObject()); + } + + @Test + public void executeSparqlQueryWithEngineWithSelectQuery() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + SelectQuery query = Mockito.mock(SelectQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithAskQuery() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + AskQuery query = Mockito.mock(AskQuery.class); + + Mockito.when( + queryEngine.execute((TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), + (Query) Mockito.anyObject())).thenReturn(Boolean.TRUE); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithDescribeQuery() + throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + DescribeQuery query = Mockito.mock(DescribeQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithConstructQuery() + throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + ConstructQuery query = Mockito.mock(ConstructQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + // ------------------------------------------------------------------------ + // Implementing QueryableTcProvider + // ------------------------------------------------------------------------ + + private void injectQueryEngine(QueryEngine engine) + throws NoSuchFieldException, IllegalAccessException { + Field queryEngineField = TcManager.class + .getDeclaredField("queryEngine"); + queryEngineField.setAccessible(true); + queryEngineField.set(graphAccess, engine); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java new file mode 100644 index 0000000000..e8b16b8f29 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.impl.util; + +import junit.framework.Assert; +import org.apache.clerezza.rdf.core.impl.util.SimpleLiteralFactory; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.IRI; +import org.junit.Test; + +/** + * + * @author reto + */ +public class SimpleLiteralFactoryTest { + + final private static IRI xsdInteger = + new IRI("http://www.w3.org/2001/XMLSchema#integer"); + final private static IRI xsdInt = + new IRI("http://www.w3.org/2001/XMLSchema#int"); + final private static IRI xsdLong = + new IRI("http://www.w3.org/2001/XMLSchema#long"); + + SimpleLiteralFactory simpleLiteralFactory = new SimpleLiteralFactory(); + + @Test + public void longToXsdIntegerAndBackToMany() { + long value = 14l; + Literal tl = simpleLiteralFactory.createTypedLiteral(value); + Assert.assertEquals(xsdLong, tl.getDataType()); + long longValue = simpleLiteralFactory.createObject(Long.class, tl); + Assert.assertEquals(value, longValue); + int intValue = simpleLiteralFactory.createObject(Integer.class, tl); + Assert.assertEquals(value, intValue); + } + + @Test + public void intToXsdIntAndBackToMany() { + int value = 14; + Literal tl = simpleLiteralFactory.createTypedLiteral(value); + Assert.assertEquals(xsdInt, tl.getDataType()); + long longValue = simpleLiteralFactory.createObject(Long.class, tl); + Assert.assertEquals(value, longValue); + int intValue = simpleLiteralFactory.createObject(Integer.class, tl); + Assert.assertEquals(value, intValue); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java new file mode 100644 index 0000000000..897dde87e1 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.impl.util; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * + * @author reto + */ +public class W3CDateFormatTest { + + @Test + public void noMillis() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT+7:00")); + Date date = calendar.getTime(); + Date parsedDate = new W3CDateFormat().parse("2009-01-01T01:33:58+07:00"); + assertEquals(date, parsedDate); + } + + @Test + public void noMillisinZ() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT")); + Date date = calendar.getTime(); + Date parsedDate = new W3CDateFormat().parse("2009-01-01T01:33:58Z"); + assertEquals(date, parsedDate); + } + + @Test + public void dateObjectSerializedWithoutTimeZone() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT+7:00")); + Date date = calendar.getTime(); + String serializedDate = new W3CDateFormat().format(date); + assertEquals("2008-12-31T18:33:58Z", serializedDate); + } + + @Test + public void roundTrip() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, + 1, 33, 58); + Date date = calendar.getTime(); + String formattedDate = new W3CDateFormat().format(date); + Date parsedDate = new W3CDateFormat().parse(formattedDate); + assertEquals(date, parsedDate); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java new file mode 100644 index 0000000000..2745026fba --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.Graph; +import java.io.InputStream; +import junit.framework.Assert; + +import org.apache.clerezza.rdf.core.*; +import org.junit.Test; + +/** + * + * @author reto + */ +public class ParserTest { + + private static boolean providerAInvoked; + private static boolean providerBInvoked; + private ParsingProvider parsingProviderA = new ParsingProviderA(); + private ParsingProvider parsingProviderB = new ParsingProviderB(); + + @Test + public void registerOneProvider() { + Parser parser = new Parser(null); + parser.bindParsingProvider(parsingProviderA); + providerAInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + Assert.assertTrue(providerAInvoked); + } + + @Test + public void registerAndUnregisterSecond() { + Parser parser = new Parser(null); + parser.bindParsingProvider(parsingProviderA); + parser.bindParsingProvider(parsingProviderB); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + Assert.assertFalse(providerAInvoked); + Assert.assertTrue(providerBInvoked); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy1+rdf"); + Assert.assertTrue(providerAInvoked); + Assert.assertFalse(providerBInvoked); + parser.unbindParsingProvider(parsingProviderB); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + Assert.assertTrue(providerAInvoked); + Assert.assertFalse(providerBInvoked); + + } + + @SupportedFormat({"application/x-fantasy1+rdf", "application/x-fantasy2+rdf"}) + static class ParsingProviderA implements ParsingProvider { + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + providerAInvoked = true; + } + }; + @SupportedFormat("application/x-fantasy2+rdf") + static class ParsingProviderB implements ParsingProvider { + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + providerBInvoked = true; + } + }; +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java new file mode 100644 index 0000000000..0cc59a6118 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import org.apache.clerezza.commons.rdf.Graph; +import java.io.OutputStream; + +import junit.framework.Assert; + +import org.apache.clerezza.rdf.core.*; +import org.junit.Test; + +/** + * + * @author mir + */ +public class SerializerTest { + + private static boolean providerAInvoked; + private static boolean providerBInvoked; + private SerializingProvider serializingProviderA = new SerializingProviderA(); + private SerializingProvider serializingProviderB = new SerializingProviderB(); + + @Test + public void registerOneProvider() { + Serializer serializer = new Serializer(null); + serializer.bindSerializingProvider(serializingProviderA); + providerAInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + Assert.assertTrue(providerAInvoked); + } + + @Test + public void registerAndUnregisterSecond() { + Serializer serializer = new Serializer(null); + serializer.bindSerializingProvider(serializingProviderA); + serializer.bindSerializingProvider(serializingProviderB); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + Assert.assertFalse(providerAInvoked); + Assert.assertTrue(providerBInvoked); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy1+rdf"); + Assert.assertTrue(providerAInvoked); + Assert.assertFalse(providerBInvoked); + serializer.unbindSerializingProvider(serializingProviderB); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + Assert.assertTrue(providerAInvoked); + Assert.assertFalse(providerBInvoked); + + } + + @SupportedFormat({"application/x-fantasy1+rdf", "application/x-fantasy2+rdf"}) + static class SerializingProviderA implements SerializingProvider { + + @Override + public void serialize(OutputStream serializedGraph, Graph tc, String formatIdentifier) { + providerAInvoked = true; + } + }; + @SupportedFormat("application/x-fantasy2+rdf") + static class SerializingProviderB implements SerializingProvider { + + @Override + public void serialize(OutputStream serializedGraph, Graph tc, String formatIdentifier) { + providerBInvoked = true; + } + }; +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java new file mode 100644 index 0000000000..7e7adb7fc3 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java @@ -0,0 +1,49 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import java.io.InputStream; +import org.apache.clerezza.commons.rdf.Graph; +import org.junit.Assert; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.IRI; + +/** + * This class is listed in + * META-INF/services/org.apache.clerezza.serializedform.ParsingProvider + * + * @author reto + */ +@SupportedFormat("application/x-test+rdf") +public class TestServiceManagedProvider implements ParsingProvider { + + private static boolean parseInvoked; + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + parseInvoked = true; + } + + @Test + public void registerOneProvider() { + Parser parser = Parser.getInstance(); + parser.parse(null, "application/x-test+rdf"); + Assert.assertTrue(parseInvoked); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java new file mode 100644 index 0000000000..50eeee5a9f --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java @@ -0,0 +1,140 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import org.apache.clerezza.rdf.core.sparql.query.Query; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * + * @author hasan + */ +public class QueryParserSerializerCombinationTest { + + public QueryParserSerializerCombinationTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + @Test + public void testPatternOrderPreservation() throws Exception { + String queryString = + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description \n" + + "WHERE\n" + + "{ ?property .\n" + + "{ { ?property ?superclass .\n" + + " ?superclass .\n" + + "} UNION { ?property ?dunion .\n" + + "?dunion ?dlist .\n" + + "?dlist ?superclass .\n" + + " ?superclass .\n" + + "} } { { ?property ?superrange .\n" + + "?range ?superrange .\n" + + "FILTER (! (isBLANK(?range)))\n" + + "} UNION { ?property ?range .\n" + + "FILTER (! (isBLANK(?range)))\n" + + "} } OPTIONAL { ?somesub ?range .\n" + + "FILTER (((?somesub) != ()) && ((?somesub) != (?range)))\n" + + "} OPTIONAL { ?subproperty ?property .\n" + + " OPTIONAL { ?subproperty ?subproperty_description .\n" + + "} FILTER (((?subproperty) != ()) && ((?subproperty) != (?property)))\n" + + "} OPTIONAL { ?property ?property_description .\n" + + "} FILTER ((?property) != ())\n" + + "FILTER ((?range) != ())\n" + + "FILTER (! (BOUND(?somesub)))\n" + + "} \n"; + + Query query = QueryParser.getInstance().parse(queryString); + Assert.assertEquals(queryString.replaceAll("\\s", "").trim(), query.toString().replaceAll("\\s", "").trim()); + } + + @Test + public void testParsingAndSerializationStability() throws Exception { + String queryString = + "PREFIX mo: \n" + + "PREFIX list: \n" + + "PREFIX owl: \n" + + "PREFIX rdf: \n" + + "PREFIX rdfs: \n" + + "PREFIX dc: \n" + + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description\n" + + "WHERE {\n" + + " ?property a owl:ObjectProperty .\n" + + " FILTER (?property != owl:bottomObjectProperty) .\n" + + " {\n" + + " {\n" + + " ?property rdfs:domain ?superclass .\n" + + " mo:Company rdfs:subClassOf ?superclass .\n" + + " }\n" + + " UNION\n" + + " {\n" + + " ?property rdfs:domain ?dunion .\n" + + " ?dunion owl:unionOf ?dlist .\n" + + " ?dlist list:member ?superclass .\n" + + " mo:Company rdfs:subClassOf ?superclass .\n" + + " }\n" + + " }\n" + + " {\n" + + " {\n" + + " ?property rdfs:range ?superrange .\n" + + " ?range rdfs:subClassOf ?superrange .\n" + + " FILTER (!isBlank(?range)) .\n" + + " }\n" + + " UNION\n" + + " {\n" + + " ?property rdfs:range ?range .\n" + + " FILTER (!isBlank(?range)) .\n" + + " }\n" + + " } .\n" + + " FILTER (?range != owl:Nothing) .\n" + + " OPTIONAL { ?somesub rdfs:subClassOf ?range . FILTER(?somesub != owl:Nothing && ?somesub != ?range)}\n" + + " FILTER (!bound(?somesub)) .\n" + + " OPTIONAL {\n" + + " ?subproperty rdfs:subPropertyOf ?property .\n" + + " FILTER(?subproperty != owl:bottomObjectProperty && ?subproperty != ?property)\n" + + " OPTIONAL { ?subproperty dc:description ?subproperty_description . }\n" + + " }\n" + + " OPTIONAL { ?property dc:description ?property_description . }\n" + + "} "; + + Query query1 = QueryParser.getInstance().parse(queryString); + Thread.sleep(5000l); + Query query2 = QueryParser.getInstance().parse(queryString); + Assert.assertEquals(query1.toString(), query2.toString()); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java new file mode 100644 index 0000000000..f39e33861c --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java @@ -0,0 +1,383 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Assert; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.Language; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.rdf.core.sparql.query.AskQuery; +import org.apache.clerezza.rdf.core.sparql.query.BasicGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.BuiltInCall; +import org.apache.clerezza.rdf.core.sparql.query.ConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.DescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.Expression; +import org.apache.clerezza.rdf.core.sparql.query.GraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.GroupGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.OptionalGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.OrderCondition; +import org.apache.clerezza.rdf.core.sparql.query.Query; +import org.apache.clerezza.rdf.core.sparql.query.QueryWithSolutionModifier; +import org.apache.clerezza.rdf.core.sparql.query.ResourceOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.SelectQuery; +import org.apache.clerezza.rdf.core.sparql.query.TriplePattern; +import org.apache.clerezza.rdf.core.sparql.query.UnaryOperation; +import org.apache.clerezza.rdf.core.sparql.query.UriRefOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.Variable; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleTriplePattern; + +/** + * + * @author hasan + */ +public class QueryParserTest { + + @Test + public void testSelectQuery() throws ParseException { + +// SELECT ?title FROM +// WHERE { ?title . } + + final String variable = "title"; + final String defaultGraph = "http://example.org/library"; + final String subject = "http://example.org/book/book1"; + final String predicate = "http://purl.org/dc/elements/1.1/title"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("SELECT ?").append(variable) + .append(" FROM <").append(defaultGraph) + .append("> WHERE { <").append(subject).append("> <") + .append(predicate).append("> ?").append(variable).append(" . }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + Assert.assertTrue(selectQuery.getSelection().get(0) + .equals(new Variable(variable))); + Assert.assertTrue(selectQuery.getDataSet().getDefaultGraphs().toArray()[0] + .equals(new IRI(defaultGraph))); + + GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(subject)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); + + Assert.assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test(expected=ParseException.class) + public void testInvalidQuery() throws ParseException { + Query q = QueryParser.getInstance().parse("Hello"); + } + + @Test + public void testSelectQuerySelection() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT ?a ?b WHERE {?a ?x ?b}"); + Set selectionSet = new HashSet( + q.getSelection()); + Set expected = new HashSet(); + expected.add(new Variable("a")); + expected.add(new Variable("b")); + Assert.assertEquals(expected, selectionSet); + Assert.assertFalse(q.isSelectAll()); + + } + + @Test + public void testSelectAll() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x ?b}"); + Set selectionSet = new HashSet( + q.getSelection()); + Set expected = new HashSet(); + expected.add(new Variable("a")); + expected.add(new Variable("b")); + expected.add(new Variable("x")); + Assert.assertEquals(expected, selectionSet); + Assert.assertTrue(q.isSelectAll()); + + } + + @Test + public void testPlainLiteral() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x 'tiger' . ?a ?x 'lion'@en . }"); + + GraphPattern gp = (GraphPattern) q.getQueryPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size()==2); + + Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern( + new Variable("a"), new Variable("x"), + new PlainLiteralImpl("tiger")))); + + Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern( + new Variable("a"), new Variable("x"), + new PlainLiteralImpl("lion", new Language("en"))))); + } + + @Test + public void testOrderBy() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x ?b} ORDER BY DESC(?b)"); + + List oc = ((QueryWithSolutionModifier) q).getOrderConditions(); + Assert.assertTrue(oc.size()==1); + Assert.assertFalse(oc.get(0).isAscending()); + Variable b = new Variable("b"); + Assert.assertEquals(b, oc.get(0).getExpression()); + } + + @Test + public void testConstructQuery() throws ParseException { + +// CONSTRUCT { ?name} +// WHERE { ?x ?name} + + + final String variable1 = "name"; + final String variable2 = "x"; + final String subject1 = "http://example.org/person#Alice"; + final String predicate1 = "http://www.w3.org/2001/vcard-rdf/3.0#FN"; + final String predicate2 = "http://xmlns.com/foaf/0.1/name"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("CONSTRUCT { <").append(subject1).append("> <") + .append(predicate1).append("> ?").append(variable1) + .append("} WHERE { ?").append(variable2).append(" <") + .append(predicate2).append("> ?").append(variable1).append("}"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(ConstructQuery.class.isAssignableFrom(q.getClass())); + ConstructQuery constructQuery = (ConstructQuery) q; + Set triplePatterns = constructQuery + .getConstructTemplate(); + Assert.assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(subject1)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate1)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable1)); + + Assert.assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + + GraphPattern gp = (GraphPattern) constructQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size()==1); + + s = new ResourceOrVariable(new Variable(variable2)); + p = new UriRefOrVariable(new IRI(predicate2)); + + Assert.assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test + public void testDescribeQuery() throws ParseException { + +// DESCRIBE + + final String resource = "http://example.org/book/book1"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("DESCRIBE <").append(resource).append(">"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(DescribeQuery.class.isAssignableFrom(q.getClass())); + DescribeQuery describeQuery = (DescribeQuery) q; + Assert.assertTrue(describeQuery.getResourcesToDescribe().get(0) + .getResource().equals(new IRI(resource))); + } + + @Test + public void testAskQuery() throws ParseException { + +// ASK { ?x "Alice" } + + final String variable = "x"; + final String predicate = "http://xmlns.com/foaf/0.1/name"; + final String object = "Alice"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("ASK { ?").append(variable).append(" <") + .append(predicate).append("> \"").append(object).append("\" }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(AskQuery.class.isAssignableFrom(q.getClass())); + AskQuery askQuery = (AskQuery) q; + + GraphPattern gp = (GraphPattern) askQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size()==1); + + Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(new Variable(variable), + new IRI(predicate), new PlainLiteralImpl(object)))); + } + + @Test + public void testBaseAndPrefix() throws ParseException { + +// BASE +// PREFIX dc: +// +// SELECT $title +// WHERE { dc:title ?title } + + final String base = "http://example.org/book/"; + final String prefix = "dc"; + final String prefixUri = "http://purl.org/dc/elements/1.1/"; + final String variable = "title"; + final String subject = "book1"; + final String predicate = "title"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("BASE <").append(base).append(">") + .append(" PREFIX ").append(prefix).append(": <") + .append(prefixUri).append("> SELECT $").append(variable) + .append(" WHERE { <").append(subject).append("> ") + .append(prefix).append(":").append(predicate).append(" ?") + .append(variable).append(" }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + Assert.assertTrue(selectQuery.getSelection().get(0) + .equals(new Variable(variable))); + + GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(base+subject)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(prefixUri+predicate)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); + + Assert.assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test + public void testOptionalAndFilter() throws ParseException { + +// PREFIX dc: +// PREFIX books: +// +// SELECT ?book ?title +// WHERE +// { ?book dc:title ?title . +// OPTIONAL +// { ?book books:author ?author .} +// FILTER ( ! bound(?author) ) +// } + final String prefix1 = "dc"; + final String prefix1Uri = "http://purl.org/dc/elements/1.1/"; + final String prefix2 = "books"; + final String prefix2Uri = "http://example.org/book/"; + final String variable1 = "book"; + final String variable2 = "title"; + final String variable3 = "author"; + final String predicate1 = "title"; + final String predicate2 = "author"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("PREFIX ").append(prefix1).append(": <").append(prefix1Uri) + .append("> PREFIX ").append(prefix2).append(": <").append(prefix2Uri) + .append("> SELECT ?").append(variable1).append(" ?").append(variable2) + .append(" WHERE { ?").append(variable1).append(" ") + .append(prefix1).append(":").append(predicate1) + .append(" ?").append(variable2).append(" . OPTIONAL { ?") + .append(variable1).append(" ").append(prefix2).append(":") + .append(predicate2).append(" ?").append(variable3) + .append(" .} FILTER ( ! bound(?").append(variable3).append(") ) }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + Assert.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + Assert.assertTrue(selectQuery.getSelection().size() == 2); + Set vars = new HashSet(2); + Variable var1 = new Variable(variable1); + Variable var2 = new Variable(variable2); + vars.add(var1); + vars.add(var2); + Assert.assertTrue(selectQuery.getSelection().containsAll(vars)); + + GroupGraphPattern ggp = selectQuery.getQueryPattern(); + List constraints = ggp.getFilter(); + Assert.assertTrue(UnaryOperation.class.isAssignableFrom(constraints + .get(0).getClass())); + UnaryOperation uop = (UnaryOperation) constraints.get(0); + Assert.assertTrue(uop.getOperatorString().equals("!")); + Assert.assertTrue(BuiltInCall.class.isAssignableFrom(uop.getOperand() + .getClass())); + BuiltInCall bic = (BuiltInCall) uop.getOperand(); + Assert.assertTrue(bic.getName().equals("BOUND")); + Variable var3 = new Variable(variable3); + Assert.assertTrue(bic.getArguements().get(0).equals(var3)); + + GraphPattern gp = (GraphPattern) ggp.getGraphPatterns().toArray()[0]; + Assert.assertTrue(OptionalGraphPattern.class.isAssignableFrom(gp.getClass())); + OptionalGraphPattern ogp = (OptionalGraphPattern) gp; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom( + ogp.getMainGraphPattern().getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) ogp.getMainGraphPattern(); + + Set triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size() == 1); + Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix1Uri + predicate1), + var2))); + + GraphPattern gp2 = (GraphPattern) ogp.getOptionalGraphPattern() + .getGraphPatterns().toArray()[0]; + Assert.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp2.getClass())); + bgp = (BasicGraphPattern) gp2; + + triplePatterns = bgp.getTriplePatterns(); + Assert.assertTrue(triplePatterns.size() == 1); + Assert.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix2Uri + predicate2), + var3))); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java new file mode 100644 index 0000000000..eccf13f27c --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java @@ -0,0 +1,318 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.apache.clerezza.rdf.core.LiteralFactory; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.sparql.query.BinaryOperation; +import org.apache.clerezza.rdf.core.sparql.query.BuiltInCall; +import org.apache.clerezza.rdf.core.sparql.query.Expression; +import org.apache.clerezza.rdf.core.sparql.query.LiteralExpression; +import org.apache.clerezza.rdf.core.sparql.query.ResourceOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.TriplePattern; +import org.apache.clerezza.rdf.core.sparql.query.UriRefExpression; +import org.apache.clerezza.rdf.core.sparql.query.UriRefOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.Variable; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleAskQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleBasicGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleDescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleGroupGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleOptionalGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleOrderCondition; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleSelectQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleTriplePattern; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * + * @author hasan + */ +public class QuerySerializerTest { + + @Test + public void testSelectQuery() { + + final String queryString = "SELECT ?title FROM " + + " WHERE { " + + " ?title . }"; + + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + Variable variable = new Variable("title"); + selectQuery.addSelection(variable); + IRI defaultGraph = new IRI("http://example.org/library"); + selectQuery.addDefaultGraph(defaultGraph); + ResourceOrVariable subject = new ResourceOrVariable( + new IRI("http://example.org/book/book1")); + UriRefOrVariable predicate = new UriRefOrVariable( + new IRI("http://purl.org/dc/elements/1.1/title")); + ResourceOrVariable object = new ResourceOrVariable(variable); + TriplePattern triplePattern = new SimpleTriplePattern(subject, predicate, object); + Set triplePatterns = new HashSet(); + triplePatterns.add(triplePattern); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + selectQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testConstructQuery() { + + final String queryString = "CONSTRUCT { " + + " ?name . } " + + "WHERE { ?x ?name . }"; + + ResourceOrVariable s = new ResourceOrVariable( + new IRI("http://example.org/person#Alice")); + UriRefOrVariable p = new UriRefOrVariable( + new IRI("http://www.w3.org/2001/vcard-rdf/3.0#FN")); + ResourceOrVariable o = new ResourceOrVariable(new Variable("name")); + Set constructTriplePatterns = new HashSet(); + constructTriplePatterns.add(new SimpleTriplePattern(s, p, o)); + SimpleConstructQuery constructQuery = new SimpleConstructQuery(constructTriplePatterns); + + s = new ResourceOrVariable(new Variable("x")); + p = new UriRefOrVariable(new IRI("http://xmlns.com/foaf/0.1/name")); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(s, p, o)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + constructQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(constructQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testDescribeQuery() { + + final String queryString = "DESCRIBE "; + + SimpleDescribeQuery describeQuery = new SimpleDescribeQuery(); + describeQuery.addResourceToDescribe(new ResourceOrVariable( + new IRI("http://example.org/book/book1"))); + + Assert.assertTrue(describeQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testAskQuery() { + + final String queryString = "ASK WHERE { ?x " + + "\"Alice\"^^ . }"; + + ResourceOrVariable s = new ResourceOrVariable(new Variable("x")); + UriRefOrVariable p = new UriRefOrVariable( + new IRI("http://xmlns.com/foaf/0.1/name")); + ResourceOrVariable o = new ResourceOrVariable( + LiteralFactory.getInstance().createTypedLiteral("Alice")); + + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(s, p, o)); + SimpleAskQuery askQuery = new SimpleAskQuery(); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + askQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(askQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + /** + * Ignoring: given that triplePatterns is a Set I don't see what is supposed + * to guarantee the expected ordering. + */ + @Ignore + @Test + public void testFilter() { + + final String queryString = "SELECT ?title ?price WHERE { " + + "?x ?title . " + + "?x ?price . " + + "FILTER ((?price) < (\"30.5\"^^)) " + + "}"; + + Variable price = new Variable("price"); + Variable title = new Variable("title"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(title); + selectQuery.addSelection(price); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://example.org/ns#price"), price)); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://purl.org/dc/elements/1.1/title"), title)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + BinaryOperation constraint = new BinaryOperation("<", + price, new LiteralExpression(LiteralFactory.getInstance().createTypedLiteral(30.5))); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testUriRefExpression() { + + final String queryString = "SELECT ?resource WHERE { " + + "?resource ?myType . " + + "FILTER ((?resource) = ()) " + + "}"; + + Variable resource = new Variable("resource"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(resource); + + Variable myType = new Variable("myType"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(resource, + new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), myType)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + BinaryOperation constraint = new BinaryOperation("=", + resource, new UriRefExpression(new IRI("http://example.org/ontology#special"))); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testOrderBy() { + + final String queryString = "SELECT * WHERE { ?a ?b ?c . } ORDER BY DESC(?c)"; + + Variable a = new Variable("a"); + Variable b = new Variable("b"); + Variable c = new Variable("c"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.setSelectAll(); + selectQuery.addSelection(a); + selectQuery.addSelection(b); + selectQuery.addSelection(c); + + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(a, b, c)); + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + selectQuery.setQueryPattern(queryPattern); + selectQuery.addOrderCondition(new SimpleOrderCondition(c, false)); + + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testOptional() { + + final String queryString = "SELECT ?title ?price WHERE { " + + "?x ?title . " + + "OPTIONAL { ?x ?price . } " + + "}"; + + Variable title = new Variable("title"); + Variable price = new Variable("price"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(title); + selectQuery.addSelection(price); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://purl.org/dc/elements/1.1/title"), title)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + + Set triplePatternsOpt = new HashSet(); + triplePatternsOpt.add(new SimpleTriplePattern(x, + new IRI("http://example.org/ns#price"), price)); + + SimpleBasicGraphPattern bgpOpt = + new SimpleBasicGraphPattern(triplePatternsOpt); + + SimpleGroupGraphPattern ggpOpt = new SimpleGroupGraphPattern(); + ggpOpt.addGraphPattern(bgpOpt); + + SimpleOptionalGraphPattern ogp = new SimpleOptionalGraphPattern(bgp, ggpOpt); + + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(ogp); + selectQuery.setQueryPattern(queryPattern); + + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testRegex() { + + final String queryString = "SELECT ?p WHERE { " + + " ?p ?x . " + + "FILTER REGEX(?x,\".*uni.*\"^^) }"; + + Variable p = new Variable("p"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(p); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern( + new IRI("http://localhost/testitem"), p, x)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + + List arguments = new ArrayList(); + arguments.add(x); + arguments.add(new LiteralExpression(LiteralFactory.getInstance(). + createTypedLiteral(".*uni.*"))); + BuiltInCall constraint = new BuiltInCall("REGEX", arguments); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + Assert.assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java new file mode 100644 index 0000000000..c56170c1f1 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java @@ -0,0 +1,505 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import java.util.HashSet; +import java.util.Set; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.TcManager; +import org.apache.clerezza.rdf.core.access.TcManagerTest; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author hasan + */ +public class SparqlPreParserTest { + + private TcManager graphAccess; + private final WeightedA weightedA = new WeightedA(); + private final static IRI DEFAULT_GRAPH = new IRI("http://example.org/default.graph"); + private final static IRI TEST_GRAPH = new IRI("http://example.org/test.graph"); + + @Before + public void setUp() { + graphAccess = TcManager.getInstance(); + graphAccess.addWeightedTcProvider(weightedA); + } + + @After + public void tearDown() { + graphAccess = TcManager.getInstance(); + graphAccess.removeWeightedTcProvider(weightedA); + } + + @Test + public void testDefaultGraphInSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append( + "PREFIX : \n" + + "SELECT ?x \n" + + "{\n" + + ":order :item/:price ?x\n" + + "}\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testAllGraphReferenceInSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append("SELECT DISTINCT ?g { GRAPH ?g { ?s ?p ?o } }\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs == null); + } + + @Test + public void testSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append( + "PREFIX : \n" + + "SELECT ?x (foo(2*3, ?x < ?y) AS ?f) (GROUP_CONCAT(?x ; separator=\"|\") AS ?gc) (sum(distinct *) AS ?total)\n" + + "FROM " + TEST_GRAPH.toString() + "\n" + + "{\n" + + ":order :item/:price ?x\n" + + "}\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testSimpleDescribe() throws ParseException { + + String queryStr = "DESCRIBE "; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testLoadingToDefaultGraph() throws ParseException { + + String queryStr = "LOAD SILENT "; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(new IRI("http://example.org/mydata")); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testLoadingToGraph() throws ParseException { + + String queryStr = "LOAD SILENT INTO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(TEST_GRAPH); + expected.add(new IRI("http://example.org/mydata")); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testClearingDefaultGraph() throws ParseException { + + String queryStr = "CLEAR SILENT DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testClearingNamedGraph() throws ParseException { + + String queryStr = "CLEAR SILENT NAMED"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.contains(TcManagerTest.uriRefA)); + } + + @Test + public void testClearingGraph() throws ParseException { + + String queryStr = "CLEAR SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testDroppingDefaultGraph() throws ParseException { + + String queryStr = "DROP SILENT DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDroppingNamedGraph() throws ParseException { + + String queryStr = "DROP SILENT NAMED"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.contains(TcManagerTest.uriRefA)); + } + + @Test + public void testDroppingGraph() throws ParseException { + + String queryStr = "DROP SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testCreatingGraph() throws ParseException { + + String queryStr = "CREATE SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testAddingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "ADD SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testAddingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "ADD SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testMovingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "MOVE SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testMovingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "MOVE SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testCopyingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "COPY SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testCopyingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "COPY SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testInsertDataToDefaultGraph() throws ParseException { + + String queryStr = "PREFIX dc: INSERT DATA { \n" + + " dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testInsertDataToNamedGraph() throws ParseException { + + String queryStr = "PREFIX ns: \n" + + "INSERT DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testDeleteDataInDefaultGraph() throws ParseException { + + String queryStr = "PREFIX dc: DELETE DATA { \n" + + " dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDeleteDataInNamedGraph() throws ParseException { + + String queryStr = "PREFIX ns: \n" + + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testInsertAndDeleteData() throws ParseException { + + String queryStr = "PREFIX ns: " + + "INSERT DATA { ns:price 42 }; " + + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testDeleteWhereInDefaultGraph() throws ParseException { + + String queryStr = "PREFIX foaf: " + + "DELETE WHERE { ?person foaf:givenName 'Fred'; ?property ?value }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDeleteWhereInNamedGraphs() throws ParseException { + + String queryStr = "PREFIX foaf: DELETE WHERE " + + "{ GRAPH { ?person foaf:givenName 'Fred' ; ?property1 ?value1 } " + + " GRAPH { ?person ?property2 ?value2 } }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example.com/names")); + expected.add(new IRI("http://example.com/addresses")); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testModifyOperationWithFallbackGraph() throws ParseException { + String queryStr = "PREFIX foaf: WITH " + TEST_GRAPH.toString() + + " DELETE { ?person foaf:givenName 'Bill' } INSERT { ?person foaf:givenName 'William' }" + + " WHERE { ?person foaf:givenName 'Bill' }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(TEST_GRAPH); + expected.add(DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testDeleteOperationInDefaultGraph() throws ParseException { + String queryStr = "PREFIX dc: PREFIX xsd: " + + "DELETE { ?book ?p ?v } WHERE { ?book dc:date ?date . " + + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testInsertOperationToNamedGraph() throws ParseException { + String queryStr = "PREFIX dc: PREFIX xsd: " + + "INSERT { GRAPH { ?book ?p ?v } } " + + "WHERE { GRAPH { ?book dc:date ?date . " + + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v } }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example/bookStore2")); + expected.add(new IRI("http://example/bookStore")); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testInsertAndDeleteWithCommonPrefix() throws ParseException { + String queryStr = "PREFIX dc: \n" + + "PREFIX dcmitype: \n" + + "PREFIX xsd: \n\n" + + "INSERT\n" + + " { GRAPH { ?book ?p ?v } }\n" + + "WHERE\n" + + " { GRAPH \n" + + " { ?book dc:date ?date . \n" + + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime )\n" + + " ?book ?p ?v\n" + + " }\n" + + " } ;\n\n" + + "WITH \n" + + "DELETE\n" + + " { ?book ?p ?v }\n" + + "WHERE\n" + + " { ?book dc:date ?date ;\n" + + " dc:type dcmitype:PhysicalObject .\n" + + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime ) \n" + + " ?book ?p ?v\n" + + " }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example/bookStore2")); + expected.add(new IRI("http://example/bookStore")); + Assert.assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testExistsFunction() throws ParseException { + String queryStr = "PREFIX rdf: \n" + + "PREFIX foaf: \n\n" + + "SELECT ?person\n" + + "WHERE \n" + + "{\n" + + " ?person rdf:type foaf:Person .\n" + + " FILTER EXISTS { ?person foaf:name ?name }\n" + + "}"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testNotExistsFunction() throws ParseException { + String queryStr = "PREFIX rdf: \n" + + "PREFIX foaf: \n\n" + + "SELECT ?person\n" + + "WHERE \n" + + "{\n" + + " ?person rdf:type foaf:Person .\n" + + " FILTER NOT EXISTS { ?person foaf:name ?name }\n" + + "}"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Assert.assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java new file mode 100644 index 0000000000..8714b97953 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java @@ -0,0 +1,37 @@ +/* + * Copyright 2015 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.clerezza.rdf.simple.storage; + +import org.apache.clerezza.rdf.core.access.TcManager; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * @author developer + */ +public class AccessViaTcManager { + + @Test + public void simple() { + Graph g = TcManager.getInstance().createGraph(new IRI("http://example.org/foo")); + Assert.assertTrue(g instanceof SimpleGraph); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java new file mode 100644 index 0000000000..a7a3250372 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.simple.storage; + +import org.junit.After; +import org.apache.clerezza.rdf.core.access.TcProvider; +import org.apache.clerezza.rdf.core.test.TcProviderTest; + +/** + * + * @author mir + */ +public class GenericTcProviderTest extends TcProviderTest { + + SimpleTcProvider provider = new SimpleTcProvider(); + + @After + public void cleanUp() { + provider = new SimpleTcProvider(); + } + + @Override + protected TcProvider getInstance() { + return provider; + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java new file mode 100644 index 0000000000..2ec8af8fb6 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.clerezza.rdf.utils; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.utils.GraphUtils.NoSuchSubGraphException; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * @author reto + */ +public class GraphUtilsTest { + + final IRI u1 = new IRI("http://ex.org/1"); + final IRI u2 = new IRI("http://ex.org/2"); + final IRI u3 = new IRI("http://ex.org/3"); + + @Test + public void removeSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode1)); + } + GraphUtils.removeSubGraph(baseGraph, subGraph); + Assert.assertEquals(1, baseGraph.size()); + } + + private Graph createBaseGraph() { + Graph baseGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + baseGraph.add(new TripleImpl(u1, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); + baseGraph.add(new TripleImpl(u3, u2, u1)); + } + return baseGraph; + } + + /** It is required that the subgraph comprises the whole context of the Bnodes it ioncludes + * + * @throws org.apache.clerezza.rdf.utils.GraphUtils.NoSuchSubGraphException + */ + @Test(expected=NoSuchSubGraphException.class) + public void removeIncompleteSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + } + GraphUtils.removeSubGraph(baseGraph, subGraph); + } + + @Test(expected=NoSuchSubGraphException.class) + public void removeInvalidSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); + baseGraph.add(new TripleImpl(bNode2, u2, new BlankNode())); + } + GraphUtils.removeSubGraph(baseGraph, subGraph); + } +} + diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java new file mode 100644 index 0000000000..2d9e4c6685 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * @author reto + */ +public class IfpSmushTest { + + private Graph ontology = new SimpleGraph(); + { + ontology.add(new TripleImpl(FOAF.mbox, RDF.type, OWL.InverseFunctionalProperty)); + } + + @Test + public void simpleBlankNode() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final BlankNode bNode1 = new BlankNode(); + mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + Assert.assertEquals(3, mGraph.size()); + } + + @Test + public void overlappingEquivalenceClasses() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final BlankNode bNode1 = new BlankNode(); + mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + IRI mbox2 = new IRI("mailto:bar@example.org"); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox2)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + final BlankNode bNode3 = new BlankNode(); + mGraph.add(new TripleImpl(bNode3, FOAF.mbox, mbox2)); + mGraph.add(new TripleImpl(bNode3, RDFS.comment, + new PlainLiteralImpl("yet another comment"))); + Smusher.smush(mGraph, ontology); + Assert.assertEquals(5, mGraph.size()); + } + + @Test + public void oneIRI() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final IRI resource = new IRI("http://example.org/"); + mGraph.add(new TripleImpl(resource, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + Assert.assertEquals(3, mGraph.size()); + } + + @Test + public void twoIRIs() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final IRI resource1 = new IRI("http://example.org/"); + mGraph.add(new TripleImpl(resource1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final IRI resource2 = new IRI("http://2.example.org/"); + mGraph.add(new TripleImpl(resource2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + Assert.assertEquals(4, mGraph.size()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java new file mode 100644 index 0000000000..c81547dc1f --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java @@ -0,0 +1,183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import java.util.List; +import java.util.Set; + +import junit.framework.Assert; + +import org.junit.Test; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import static org.junit.Assert.*; + +/** + * + * @author rbn + */ +public class RdfListTest { + + @Test + public void listCreationAndAccess() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + assertEquals(new PlainLiteralImpl("hello"), list.get(0)); + assertEquals(new PlainLiteralImpl("world"), list.get(1)); + assertEquals(2, list.size()); + list.add(new PlainLiteralImpl("welcome")); + assertEquals(3, list.size()); + assertEquals(new PlainLiteralImpl("welcome"), list.get(2)); + list.add(1, new PlainLiteralImpl("interesting")); + assertEquals(4, list.size()); + assertEquals(new PlainLiteralImpl("interesting"), list.get(1)); + assertEquals(new PlainLiteralImpl("world"), list.get(2)); + assertEquals(new PlainLiteralImpl("welcome"), list.get(3)); + list.add(0, new PlainLiteralImpl("start")); + assertEquals(5, list.size()); + assertEquals(new PlainLiteralImpl("hello"), list.get(1)); + assertEquals(new PlainLiteralImpl("interesting"), list.get(2)); + List list2 = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(5, list2.size()); + assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); + assertEquals(new PlainLiteralImpl("interesting"), list2.get(2)); + list2.remove(2); + assertEquals(4, list2.size()); + assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); + assertEquals(new PlainLiteralImpl("world"), list2.get(2)); + while (list2.size() > 0) { + list2.remove(0); + } + assertEquals(1, tc.size()); //list = rdf:nil statement + list2.add(0, new PlainLiteralImpl("restart")); + list2.add(1, new PlainLiteralImpl("over")); + assertEquals(2, list2.size()); + list2.add(new PlainLiteralImpl("2")); + list2.add(new PlainLiteralImpl("3")); + assertEquals(4, list2.size()); + list2.add(new PlainLiteralImpl("4")); + list2.add(new PlainLiteralImpl("5")); + assertEquals(new PlainLiteralImpl("3"), list2.get(3)); + } + + @Test + public void listCreationAndAccess2() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + list.add(0,new PlainLiteralImpl("world")); + list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(0,new PlainLiteralImpl("beautifuly")); + list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(0,new PlainLiteralImpl("hello")); + assertEquals(new PlainLiteralImpl("hello"), list.get(0)); + assertEquals(new PlainLiteralImpl("beautifuly"), list.get(1)); + assertEquals(new PlainLiteralImpl("world"), list.get(2)); + } + + @Test + public void listCreationAndAccess3() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + BlankNode node0 = new BlankNode() {}; + BlankNode node1 = new BlankNode() {}; + BlankNode node2 = new BlankNode() {}; + list.add(0,node2); + list.add(0,node1); + list.add(0,node0); + assertEquals(node0, list.get(0)); + assertEquals(node1, list.get(1)); + assertEquals(node2, list.get(2)); + } + + @Test + public void secondButLastElementAccessTest() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest2"), tc); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + list.remove(1); + assertEquals(1, list.size()); + } + + @Test + public void cleanGraphAfterRemoval() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + list.remove(1); + Assert.assertEquals(2, tc.size()); + + } + + @Test + public void findContainingListNodesAndfindContainingListsTest() { + Graph tc = new SimpleGraph(); + GraphNode listA = new GraphNode(new IRI("http:///listA"), tc); + GraphNode listB = new GraphNode(new IRI("http:///listB"), tc); + BlankNode element1 = new BlankNode(); + BlankNode element2 = new BlankNode(); + BlankNode element3 = new BlankNode(); + BlankNode element4 = new BlankNode(); + BlankNode element5 = new BlankNode(); + + RdfList rdfListA = new RdfList(listA); + rdfListA.add(element1); + rdfListA.add(element2); + rdfListA.add(element3); + rdfListA.add(element4); + + RdfList rdfListB = new RdfList(listB); + rdfListB.add(element2); + rdfListB.add(element4); + rdfListB.add(element5); + + Set containingListNodes = RdfList.findContainingListNodes( + new GraphNode(element3, tc)); + Assert.assertEquals(1, containingListNodes.size()); + Assert.assertTrue(containingListNodes.contains(listA)); + + Set containingLists = RdfList.findContainingLists( + new GraphNode(element3, tc)); + Assert.assertEquals(1, containingLists.size()); + Assert.assertTrue(containingLists.contains(rdfListA)); + + containingListNodes = RdfList.findContainingListNodes( + new GraphNode(element4, tc)); + Assert.assertEquals(2, containingListNodes.size()); + Assert.assertTrue(containingListNodes.contains(listA)); + Assert.assertTrue(containingListNodes.contains(listB)); + + containingLists = RdfList.findContainingLists( + new GraphNode(element4, tc)); + Assert.assertEquals(2, containingLists.size()); + Assert.assertTrue(containingLists.contains(rdfListA)); + Assert.assertTrue(containingLists.contains(rdfListB)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java new file mode 100644 index 0000000000..fc44ec2252 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import java.util.Iterator; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * @author reto + */ +public class SameAsSmushTest { + + private final IRI uriA = new IRI("http://example.org/A"); + private final IRI uriB = new IRI("http://example.org/B"); + private final Literal lit = new PlainLiteralImpl("That's me (and you)"); + + private Graph sameAsStatements = new SimpleGraph(); + { + sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); + } + + private Graph dataGraph = new SimpleGraph(); + { + dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); + dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); + dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); + } + + @Test + public void simple() { + Assert.assertEquals(3, dataGraph.size()); + Smusher.sameAsSmush(dataGraph, sameAsStatements); + Assert.assertEquals(3, dataGraph.size()); + Assert.assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); + //exactly one statement with literal + Iterator litStmts = dataGraph.filter(null, null, lit); + Assert.assertTrue(litStmts.hasNext()); + Triple litStmt = litStmts.next(); + Assert.assertFalse(litStmts.hasNext()); + Iterator knowsStmts = dataGraph.filter(null, FOAF.knows, null); + Assert.assertTrue(knowsStmts.hasNext()); + Triple knowStmt = knowsStmts.next(); + Assert.assertEquals(knowStmt.getSubject(), knowStmt.getObject()); + Assert.assertEquals(litStmt.getSubject(), knowStmt.getObject()); + Assert.assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java new file mode 100644 index 0000000000..2fdd2f4c87 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java @@ -0,0 +1,271 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import junit.framework.Assert; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.core.test.RandomGraph; + +/** + * + * @author reto, mir + */ +public class TestGraphNode { + + @Test + public void nodeContext() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(bNode2, property2, bNode1)); + g.add(new TripleImpl(property1, property1, bNode2)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + Assert.assertEquals(4, n.getNodeContext().size()); + n.deleteNodeContext(); + Assert.assertEquals(1, g.size()); + Assert.assertFalse(n.getObjects(property2).hasNext()); + } + + @Test + public void addNode() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + Assert.assertEquals(1, g.size()); + } + + @Test + public void testGetSubjectAndObjectNodes() { + RandomGraph graph = new RandomGraph(500, 20, new SimpleGraph()); + for (int j = 0; j < 200; j++) { + Triple randomTriple = graph.getRandomTriple(); + GraphNode node = new GraphNode(randomTriple.getSubject(), graph); + Iterator properties = node.getProperties(); + while (properties.hasNext()) { + IRI property = properties.next(); + Set objects = createSet(node.getObjects(property)); + Iterator objectNodes = node.getObjectNodes(property); + while (objectNodes.hasNext()) { + GraphNode graphNode = objectNodes.next(); + Assert.assertTrue(objects.contains(graphNode.getNode())); + } + } + } + + for (int j = 0; j < 200; j++) { + Triple randomTriple = graph.getRandomTriple(); + GraphNode node = new GraphNode(randomTriple.getObject(), graph); + Iterator properties = node.getProperties(); + while (properties.hasNext()) { + IRI property = properties.next(); + Set subjects = createSet(node.getSubjects(property)); + Iterator subjectNodes = node.getSubjectNodes(property); + while (subjectNodes.hasNext()) { + GraphNode graphNode = subjectNodes.next(); + Assert.assertTrue(subjects.contains(graphNode.getNode())); + } + } + } + } + + @Test + public void getAvailableProperties(){ + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + IRI property3 = new IRI("http://example.org/property3"); + IRI property4 = new IRI("http://example.org/property4"); + ArrayList props = new ArrayList(); + props.add(property1); + props.add(property2); + props.add(property3); + props.add(property4); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + n.addProperty(property2, bNode2); + n.addProperty(property3, bNode2); + n.addProperty(property4, bNode2); + Iterator properties = n.getProperties(); + int i = 0; + while(properties.hasNext()){ + i++; + IRI prop = properties.next(); + Assert.assertTrue(props.contains(prop)); + props.remove(prop); + } + Assert.assertEquals(i, 4); + Assert.assertEquals(props.size(), 0); + + } + + @Test + public void deleteAll() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + //the two properties two be deleted + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); + //this 3 properties should stay + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + n.deleteProperties(property1); + Assert.assertEquals(3, g.size()); + } + + @Test + public void deleteSingleProperty() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + //the properties two be deleted + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + //this 4 properties should stay + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + n.deleteProperty(property1, new PlainLiteralImpl("literal")); + Assert.assertEquals(4, g.size()); + } + + @Test + public void replaceWith() { + Graph initialGraph = new SimpleGraph(); + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + BlankNode newBnode = new BlankNode(); + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + IRI newIRI = new IRI("http://example.org/newName"); + Literal literal1 = new PlainLiteralImpl("literal"); + Literal literal2 = new PlainLiteralImpl("bla bla"); + + Triple triple1 = new TripleImpl(bNode1, property1, literal1); + Triple triple2 = new TripleImpl(bNode1, property2, property1); + Triple triple3 = new TripleImpl(bNode2, property2, bNode1); + Triple triple4 = new TripleImpl(property1, property1, bNode2); + Triple triple5 = new TripleImpl(property1, property1, literal2); + initialGraph.add(triple1); + initialGraph.add(triple2); + initialGraph.add(triple3); + initialGraph.add(triple4); + initialGraph.add(triple5); + GraphNode node = new GraphNode(property1, + new SimpleGraph(initialGraph.iterator())); + + node.replaceWith(newIRI, true); + Assert.assertEquals(5, node.getGraph().size()); + Triple expectedTriple1 = new TripleImpl(bNode1, newIRI, literal1); + Triple expectedTriple2 = new TripleImpl(bNode1, property2, newIRI); + Triple expectedTriple3 = new TripleImpl(newIRI, newIRI, bNode2); + Triple expectedTriple4 = new TripleImpl(newIRI, newIRI, literal2); + + Assert.assertTrue(node.getGraph().contains(expectedTriple1)); + Assert.assertTrue(node.getGraph().contains(expectedTriple2)); + Assert.assertTrue(node.getGraph().contains(expectedTriple3)); + Assert.assertTrue(node.getGraph().contains(expectedTriple4)); + + Assert.assertFalse(node.getGraph().contains(triple1)); + Assert.assertFalse(node.getGraph().contains(triple2)); + Assert.assertFalse(node.getGraph().contains(triple4)); + Assert.assertFalse(node.getGraph().contains(triple5)); + + node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newBnode); + Triple expectedTriple5 = new TripleImpl(bNode1, property2, newBnode); + Triple expectedTriple6 = new TripleImpl(newBnode, property1, bNode2); + Triple expectedTriple7 = new TripleImpl(newBnode, property1, literal2); + + Assert.assertTrue(node.getGraph().contains(triple1)); + Assert.assertTrue(node.getGraph().contains(expectedTriple5)); + Assert.assertTrue(node.getGraph().contains(expectedTriple6)); + Assert.assertTrue(node.getGraph().contains(expectedTriple7)); + + node = new GraphNode(literal1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newBnode); + Triple expectedTriple8 = new TripleImpl(bNode1, property1, newBnode); + Assert.assertTrue(node.getGraph().contains(expectedTriple8)); + + node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newIRI); + Triple expectedTriple9 = new TripleImpl(bNode1, property2, newIRI); + Triple expectedTriple10 = new TripleImpl(newIRI, property1, bNode2); + Triple expectedTriple11 = new TripleImpl(newIRI, property1, literal2); + Assert.assertTrue(node.getGraph().contains(triple1)); + Assert.assertTrue(node.getGraph().contains(expectedTriple9)); + Assert.assertTrue(node.getGraph().contains(expectedTriple10)); + Assert.assertTrue(node.getGraph().contains(expectedTriple11)); + } + + @Test + public void equality() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + Assert.assertTrue(n.equals(new GraphNode(bNode1, g))); + Assert.assertFalse(n.equals(new GraphNode(bNode2, g))); + GraphNode n2 = null; + Assert.assertFalse(n.equals(n2)); + } + + private Set createSet(Iterator resources) { + Set set = new HashSet(); + while (resources.hasNext()) { + RDFTerm resource = resources.next(); + set.add(resource); + } + return set; + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java new file mode 100644 index 0000000000..53173f4e3d --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java @@ -0,0 +1,78 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import java.util.Iterator; +import org.junit.Test; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.junit.Assert; + +/** + * + * @author hasan + */ +public class UnionGraphTest { + + private final IRI uriRef1 = + new IRI("http://example.org/ontology#res1"); + private final IRI uriRef2 = + new IRI("http://example.org/ontology#res2"); + private final IRI uriRef3 = + new IRI("http://example.org/ontology#res3"); + private final IRI uriRef4 = + new IRI("http://example.org/ontology#res4"); + + @Test + public void readAccess() { + Graph graph = new SimpleGraph(); + Graph graph2 = new SimpleGraph(); + BlankNode bnode = new BlankNode() { + }; + graph.add(new TripleImpl(uriRef1, uriRef2, uriRef1)); + graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); + Graph unionGraph = new UnionGraph(graph, graph2); + Iterator unionTriples = unionGraph.iterator(); + Assert.assertTrue(unionTriples.hasNext()); + unionTriples.next(); + Assert.assertTrue(unionTriples.hasNext()); + unionTriples.next(); + Assert.assertFalse(unionTriples.hasNext()); + Assert.assertEquals(2, unionGraph.size()); + } + + @Test + public void writeAccess() { + Graph graph = new SimpleGraph(); + Graph graph2 = new SimpleGraph(); + BlankNode bnode = new BlankNode() { + }; + graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); + Graph unionGraph = new UnionGraph(graph, graph2); + Assert.assertEquals(1, unionGraph.size()); + unionGraph.add(new TripleImpl(uriRef4, uriRef1, uriRef3)); + Assert.assertEquals(1, graph.size()); + Assert.assertEquals(2, unionGraph.size()); + Assert.assertEquals(1, graph2.size()); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java new file mode 100644 index 0000000000..6e67ed40e5 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-14575ea321a737f68732783e8248221b3efcef1c/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils.smushing; + +import java.util.Iterator; +import java.util.Set; +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; +import org.junit.Assert; +import org.junit.Test; + +/** + * + * @author reto + */ +public class SameAsSmushTest { + + private final IRI uriA = new IRI("http://example.org/A"); + private final IRI uriB = new IRI("http://example.org/B"); + private final IRI uriC = new IRI("http://example.org/C"); + + private final Literal lit = new PlainLiteralImpl("That's me (and you)"); + + private Graph sameAsStatements = new SimpleGraph(); + { + sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); + } + + private Graph dataGraph = new SimpleGraph(); + { + dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); + dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); + dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); + } + + @Test + public void simple() { + SameAsSmusher smusher = new SameAsSmusher() { + + @Override + protected IRI getPreferedIRI(Set uriRefs) { + if (!uriRefs.contains(uriA)) throw new RuntimeException("not the set we excpect"); + if (!uriRefs.contains(uriB)) throw new RuntimeException("not the set we excpect"); + return uriC; + } + + }; + Assert.assertEquals(3, dataGraph.size()); + smusher.smush(dataGraph, sameAsStatements, true); + Assert.assertEquals(4, dataGraph.size()); + Assert.assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); + //exactly one statement with literal + Iterator litStmts = dataGraph.filter(null, null, lit); + Assert.assertTrue(litStmts.hasNext()); + Triple litStmt = litStmts.next(); + Assert.assertFalse(litStmts.hasNext()); + Iterator knowsStmts = dataGraph.filter(null, FOAF.knows, null); + Assert.assertTrue(knowsStmts.hasNext()); + Triple knowStmt = knowsStmts.next(); + Assert.assertEquals(knowStmt.getSubject(), knowStmt.getObject()); + Assert.assertEquals(litStmt.getSubject(), knowStmt.getObject()); + Assert.assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); + Assert.assertEquals(knowStmt.getSubject(), uriC); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.json b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.json new file mode 100644 index 0000000000..47fbaad52d --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8.json @@ -0,0 +1 @@ +{"parentCommitId":"14575ea321a737f68732783e8248221b3efcef1c","currentCommitId":"d77dbe2085ffa89b2a933637c5432d113b7432b8","filesBefore":["rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java"],"filesCurrent":["rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["rdf/core/src/test/java/org/apache/clerezza/rdf/core/access","rdf/core/src/test/java/org/apache/clerezza/rdf/core","rdf/simple.storage/src/test/java/org/apache/clerezza","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test","rdf/core/src/test/java/org/apache/clerezza","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform","rdf/simple.storage/src/test/java/org","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple","rdf/utils/src/test/java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage","rdf/core.test/src/main/java/org/apache/clerezza","rdf/simple.storage","rdf/core","rdf/core.test/src","rdf/utils","rdf/core.test/src/main/java/org/apache/clerezza/rdf","rdf/core.test/src/main/java/org","rdf/simple.storage/src/test/java/org/apache","rdf/simple.storage/src/test","rdf/core/src/test/java","rdf/core.test/src/main/java/org/apache","rdf/core/src/test/java/org/apache","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl","rdf/utils/src/test/java/org/apache/clerezza","rdf/simple.storage/src","rdf/utils/src","rdf/core/src/test/java/org","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf","rdf/utils/src/test/java/org/apache/clerezza/rdf","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils","rdf/simple.storage/src/test/java","rdf/utils/src/test/java/org","rdf/utils/src/test","rdf/core/src/test","rdf/core/src","rdf","rdf/core.test","rdf/core/src/test/java/org/apache/clerezza/rdf","rdf/utils/src/test/java/org/apache","rdf/core.test/src/main/java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql","rdf/core.test/src/main"],"repositoryDirectoriesCurrent":["rdf/core/src/test/java/org/apache/clerezza/rdf/core/access","rdf/core/src/test/java/org/apache/clerezza/rdf/core","rdf/simple.storage/src/test/java/org/apache/clerezza","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test","rdf/core/src/test/java/org/apache/clerezza","rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform","rdf/simple.storage/src/test/java/org","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple","rdf/utils/src/test/java","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage","rdf/core.test/src/main/java/org/apache/clerezza","rdf/simple.storage","rdf/core","rdf/core.test/src","rdf/utils","rdf/core.test/src/main/java/org/apache/clerezza/rdf","rdf/core.test/src/main/java/org","rdf/simple.storage/src/test/java/org/apache","rdf/simple.storage/src/test","rdf/core/src/test/java","rdf/core.test/src/main/java/org/apache","rdf/core/src/test/java/org/apache","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util","rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl","rdf/utils/src/test/java/org/apache/clerezza","rdf/simple.storage/src","rdf/utils/src","rdf/core/src/test/java/org","rdf/simple.storage/src/test/java/org/apache/clerezza/rdf","rdf/utils/src/test/java/org/apache/clerezza/rdf","rdf/core.test/src/main/java/org/apache/clerezza/rdf/core","rdf/utils/src/test/java/org/apache/clerezza/rdf/utils","rdf/simple.storage/src/test/java","rdf/utils/src/test/java/org","rdf/utils/src/test","rdf/core/src/test","rdf/core/src","rdf","rdf/core.test","rdf/core/src/test/java/org/apache/clerezza/rdf","rdf/utils/src/test/java/org/apache","rdf/core.test/src/main/java","rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql","rdf/core.test/src/main"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java new file mode 100644 index 0000000000..3de63dabb8 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/GraphTest.java @@ -0,0 +1,580 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.BlankNodeOrIRI; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.Language; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.commons.rdf.impl.utils.TypedLiteralImpl; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * A generic abstract test class, implementations overwrite this class, + * providing an implementation of the getEmptyGraph method. + * + * @author reto, szalay, mir, hhn + */ +@RunWith(JUnitPlatform.class) +public abstract class GraphTest { + + private final IRI uriRef1 = + new IRI("http://example.org/ontology#res1"); + private final IRI uriRef2 = + new IRI("http://example.org/ontology#res2"); + private final IRI uriRef3 = + new IRI("http://example.org/ontology#res3"); + private final IRI uriRef4 = + new IRI("http://example.org/ontology#res4"); + private final IRI xmlLiteralType = + new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral"); + private Literal literal1 = new PlainLiteralImpl("literal1"); + private Literal literal2 = new PlainLiteralImpl("literal2"); + private BlankNode bnode1 = new BlankNode(); + private BlankNode bnode2 = new BlankNode(); + private Triple trpl1 = new TripleImpl(uriRef2, uriRef2, literal1); + private Triple trpl2 = new TripleImpl(uriRef1, uriRef2, uriRef1); + private Triple trpl3 = new TripleImpl(bnode2, uriRef3, literal2); + private Triple trpl4 = new TripleImpl(uriRef3, uriRef4, literal2); + + /** + * Subclasses implement this method to provide implementation instances of + * Graph. This method may be called an arbitrary amount of time, + * independently whether previously returned Graph are still in use or not. + * + * @return an empty Graph of the implementation to be tested + */ + protected abstract Graph getEmptyGraph(); + + @Test + public void testAddCountAndGetTriples() { + Graph graph = getEmptyGraph(); + assertEquals(0, graph.size()); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + graph.add(triple1); + assertEquals(1, graph.size()); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, uriRef1); + assertTrue(tripleIter.hasNext()); + Triple tripleGot = tripleIter.next(); + assertEquals(triple1, tripleGot); + assertFalse(tripleIter.hasNext()); + BlankNode bnode = new BlankNode() {}; + graph.add(new TripleImpl(bnode, uriRef1, uriRef3)); + graph.add(new TripleImpl(bnode, uriRef1, uriRef4)); + tripleIter = graph.filter(null, uriRef1, null); + Set subjectInMatchingTriples = new HashSet(); + Set objectsInMatchingTriples = new HashSet(); + while (tripleIter.hasNext()) { + Triple triple = tripleIter.next(); + subjectInMatchingTriples.add(triple.getSubject()); + objectsInMatchingTriples.add(triple.getObject()); + } + assertEquals(1, subjectInMatchingTriples.size()); + assertEquals(2, objectsInMatchingTriples.size()); + Set expectedObjects = new HashSet(); + expectedObjects.add(uriRef3); + expectedObjects.add(uriRef4); + assertEquals(expectedObjects, objectsInMatchingTriples); + graph.add(new TripleImpl(bnode, uriRef4, bnode)); + tripleIter = graph.filter(null, uriRef4, null); + assertTrue(tripleIter.hasNext()); + Triple retrievedTriple = tripleIter.next(); + assertFalse(tripleIter.hasNext()); + assertEquals(retrievedTriple.getSubject(), retrievedTriple.getObject()); + tripleIter = graph.filter(uriRef1, uriRef2, null); + assertTrue(tripleIter.hasNext()); + retrievedTriple = tripleIter.next(); + assertFalse(tripleIter.hasNext()); + assertEquals(retrievedTriple.getSubject(), retrievedTriple.getObject()); + } + + @Test + public void testRemoveAllTriples() { + Graph graph = getEmptyGraph(); + assertEquals(0, graph.size()); + graph.add(new TripleImpl(uriRef1, uriRef2, uriRef3)); + graph.add(new TripleImpl(uriRef2, uriRef3, uriRef4)); + assertEquals(2, graph.size()); + graph.clear(); + assertEquals(0, graph.size()); + } + + @Test + public void testUseTypedLiterals() { + Graph graph = getEmptyGraph(); + assertEquals(0, graph.size()); + Literal value = new TypedLiteralImpl("value",xmlLiteralType); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, value); + graph.add(triple1); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, null); + assertTrue(tripleIter.hasNext()); + RDFTerm gotValue = tripleIter.next().getObject(); + assertEquals(value, gotValue); + } + + @Test + public void testUseLanguageLiterals() { + Graph graph = getEmptyGraph(); + assertEquals(0, graph.size()); + Language language = new Language("it"); + Literal value = new PlainLiteralImpl("value",language); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, value); + graph.add(triple1); + Iterator tripleIter = graph.filter(uriRef1, uriRef2, null); + assertTrue(tripleIter.hasNext()); + RDFTerm gotValue = tripleIter.next().getObject(); + assertEquals(value, gotValue); + assertEquals(language, ((Literal)gotValue).getLanguage()); + } + + @Test + public void testRemoveViaIterator() { + Graph graph = getEmptyGraph(); + assertEquals(0, graph.size()); + final TripleImpl triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + graph.add(triple1); + final TripleImpl triple2 = new TripleImpl(uriRef1, uriRef2, uriRef4); + graph.add(triple2); + assertEquals(2, graph.size()); + Iterator iterator = graph.iterator(); + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + assertEquals(0, graph.size()); + } + + @Test + public void testGetSize() throws Exception { + Graph graph = getEmptyGraph(); + // The test graph must always be empty after test fixture setup + assertEquals(0, graph.size()); + } + + + @Test + public void testAddSingleTriple() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertEquals(0, graph.size()); + assertTrue(graph.add(triple)); + assertEquals(1, graph.size()); + } + + + @Test + public void testAddSameTripleTwice() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertEquals(0, graph.size()); + assertTrue(graph.add(triple)); + assertFalse(graph.add(triple)); // ImmutableGraph does not change + assertEquals(1, graph.size()); + } + + + @Test + public void testRemoveSingleTriple() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertTrue(graph.add(triple)); + assertTrue(graph.remove(triple)); + assertEquals(0, graph.size()); + } + + @Test + public void testRemoveSameTripleTwice() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAlice= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleBob= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + assertTrue(graph.add(tripleAlice)); + assertTrue(graph.add(tripleBob)); + assertTrue(graph.remove(tripleAlice)); + assertFalse(graph.remove(tripleAlice)); + assertEquals(1, graph.size()); + } + + @Test + public void testGetSameBlankNode() throws Exception { + Graph graph = getEmptyGraph(); + BlankNode bNode = new BlankNode(); + final IRI HAS_NAME = new IRI("http://example.org/ontology/hasName"); + final PlainLiteralImpl name = new PlainLiteralImpl("http://example.org/people/alice"); + final PlainLiteralImpl name2 = new PlainLiteralImpl("http://example.org/people/bob"); + final Triple tripleAlice = new TripleImpl(bNode, HAS_NAME, name); + final Triple tripleBob = new TripleImpl(bNode, HAS_NAME, name2); + assertTrue(graph.add(tripleAlice)); + assertTrue(graph.add(tripleBob)); + Iterator result = graph.filter(null, HAS_NAME, name); + assertEquals(bNode, result.next().getSubject()); + } + + @Test + public void testContainsIfContained() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertTrue(graph.add(triple)); + assertTrue(graph.contains(triple)); + } + + + @Test + public void testContainsIfEmpty() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertFalse(graph.contains(triple)); + } + + + @Test + public void testContainsIfNotContained() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAdd= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleTest= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + assertTrue(graph.add(tripleAdd)); + assertFalse(graph.contains(tripleTest)); + } + + + @Test + public void testFilterEmptyGraph() throws Exception { + Graph graph = getEmptyGraph(); + Iterator i = graph.filter(null, null, null); + assertFalse(i.hasNext()); + } + + + @Test + public void testFilterSingleEntry() throws Exception { + Graph graph = getEmptyGraph(); + final Triple triple= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + assertTrue(graph.add(triple)); + + Iterator i = graph.filter(null, null, null); + Collection resultSet= toCollection(i); + assertEquals(1, resultSet.size()); + assertTrue(resultSet.contains(triple)); + } + + + @Test + public void testFilterByObject() throws Exception { + Graph graph = getEmptyGraph(); + final Triple tripleAlice= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/alice"); + final Triple tripleBob= createTriple( + "http://example.org/ontology/Person", + "http://example.org/ontology/hasName", + "http://example.org/people/bob"); + assertTrue(graph.add(tripleAlice)); + assertTrue(graph.add(tripleBob)); + + Iterator iterator; + Collection resultSet; + + // Find bob + iterator = graph.filter(null, null, + new IRI("http://example.org/people/bob")); + resultSet= toCollection(iterator); + assertEquals(1, resultSet.size()); + assertTrue(resultSet.contains(tripleBob)); + + // Find alice + iterator = graph.filter(null, null, + new IRI("http://example.org/people/alice")); + resultSet= toCollection(iterator); + assertEquals(1, resultSet.size()); + assertTrue(resultSet.contains(tripleAlice)); + + // Find both + iterator = graph.filter(null, null, null); + resultSet= toCollection(iterator); + assertEquals(2, resultSet.size()); + assertTrue(resultSet.contains(tripleAlice)); + assertTrue(resultSet.contains(tripleBob)); + } + +/* + @Test + public void graphEventTestAddRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + assertNull(listener.getEvents()); + mGraph.add(trpl2); + assertEquals(1, listener.getEvents().size()); + assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof AddEvent); + listener.resetEvents(); + mGraph.remove(trpl2); + assertEquals(1, listener.getEvents().size()); + assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof RemoveEvent); + listener.resetEvents(); + mGraph.add(trpl3); + assertEquals(1, listener.getEvents().size()); + assertEquals(trpl3, listener.getEvents().get(0).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof AddEvent); + listener.resetEvents(); + mGraph.remove(trpl4); + assertNull(listener.getEvents()); + } + + @Test + public void graphEventTestAddAllRemoveAll() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + Graph triples = new SimpleGraph(); + triples.add(trpl1); + triples.add(trpl2); + triples.add(trpl3); + triples.add(trpl4); + mGraph.addAll(triples); + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + assertEquals(3, cumulatedEvents.size()); + assertTrue(cumulatedEvents.get(0) instanceof AddEvent); + assertTrue(cumulatedTriples.contains(trpl2)); + assertTrue(cumulatedTriples.contains(trpl3)); + assertTrue(cumulatedTriples.contains(trpl4)); + listener.resetCumulatedEvents(); + mGraph.removeAll(triples); + cumulatedEvents = listener.getCumulatedEvents(); + cumulatedTriples = getCumulatedTriples(cumulatedEvents); + assertEquals(3, cumulatedEvents.size()); + assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + assertTrue(cumulatedTriples.contains(trpl2)); + assertTrue(cumulatedTriples.contains(trpl3)); + assertTrue(cumulatedTriples.contains(trpl4)); + } + + @Test + public void graphEventTestFilterRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + Iterator result = mGraph.filter(null, uriRef2, null); + while (result.hasNext()) { + result.next(); + result.remove(); + } + List cumulatedEvents = listener.getCumulatedEvents(); + assertEquals(1, cumulatedEvents.size()); + assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + assertEquals(trpl2, listener.getEvents().get(0).getTriple()); + } + + @Test + public void graphEventTestIteratorRemove() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + Iterator result = mGraph.iterator(); + while (result.hasNext()) { + result.next(); + result.remove(); + } + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + assertEquals(3, cumulatedEvents.size()); + assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + assertTrue(cumulatedTriples.contains(trpl2)); + assertTrue(cumulatedTriples.contains(trpl3)); + assertTrue(cumulatedTriples.contains(trpl4)); + } + + @Test + public void graphEventTestClear() { + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null)); + mGraph.addGraphListener(listener, new FilterTriple(bnode2, null, literal2)); + mGraph.addGraphListener(listener, new FilterTriple(null, uriRef4, literal2)); + mGraph.add(trpl1); + mGraph.add(trpl2); + mGraph.add(trpl3); + mGraph.add(trpl4); + listener.resetCumulatedEvents(); + mGraph.clear(); + List cumulatedEvents = listener.getCumulatedEvents(); + Set cumulatedTriples = getCumulatedTriples(cumulatedEvents); + assertEquals(3, cumulatedEvents.size()); + assertTrue(cumulatedEvents.get(0) instanceof RemoveEvent); + assertTrue(cumulatedTriples.contains(trpl2)); + assertTrue(cumulatedTriples.contains(trpl3)); + assertTrue(cumulatedTriples.contains(trpl4)); + } + + private Set getCumulatedTriples(List cumulatedEvents) { + Set triples = new HashSet(); + for(GraphEvent event: cumulatedEvents) { + triples.add(event.getTriple()); + } + return triples; + } + + @Test + public void graphEventTestWithDelay() throws Exception{ + Graph mGraph = getEmptyGraph(); + TestGraphListener listener = new TestGraphListener(); + mGraph.addGraphListener(listener, new FilterTriple(uriRef1, uriRef2, null), + 1000); + + Triple triple0 = new TripleImpl(uriRef2, uriRef2, literal1); + Triple triple1 = new TripleImpl(uriRef1, uriRef2, uriRef1); + Triple triple2 = new TripleImpl(uriRef1, uriRef2, literal1); + Triple triple3 = new TripleImpl(uriRef1, uriRef2, bnode1); + mGraph.add(triple0); + mGraph.add(triple1); + mGraph.add(triple2); + mGraph.add(triple3); + Thread.sleep(1500); + assertEquals(3, listener.getEvents().size()); + assertEquals(triple1, listener.getEvents().get(0).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof AddEvent); + assertEquals(triple2, listener.getEvents().get(1).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof AddEvent); + assertEquals(triple3, listener.getEvents().get(2).getTriple()); + assertTrue(listener.getEvents().get(0) instanceof AddEvent); + } + + private static class TestGraphListener implements GraphListener { + private List events = null; + private List cumulatedEvents = new ArrayList(); + + @Override + public void graphChanged(List events) { + this.events = events; + Iterator eventIter = events.iterator(); + while (eventIter.hasNext()) { + GraphEvent graphEvent = eventIter.next(); + this.cumulatedEvents.add(graphEvent); + } + } + + public List getEvents() { + return events; + } + + public List getCumulatedEvents() { + return cumulatedEvents; + } + + public void resetEvents() { + events = null; + } + + public void resetCumulatedEvents() { + cumulatedEvents = new ArrayList(); + } + } +*/ + private Collection toCollection(Iterator iterator) { + Collection result = new ArrayList(); + while (iterator.hasNext()) { + result.add(iterator.next()); + } + return result; + } + + /** + * Creates a new Triple. + * @param subject the subject. + * @param predicate the predicate. + * @param object the object. + * @throws IllegalArgumentException If an attribute is null. + */ + private Triple createTriple(String subject, String predicate, + String object) { + return new TripleImpl(new IRI(subject), new IRI(predicate), + new IRI(object)); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java new file mode 100644 index 0000000000..631a52877e --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core.test/src/main/java/org/apache/clerezza/rdf/core/test/TcProviderTest.java @@ -0,0 +1,491 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.ImmutableGraph; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.BlankNodeOrIRI; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.core.access.EntityAlreadyExistsException; +import org.apache.clerezza.rdf.core.access.NoSuchEntityException; +import org.apache.clerezza.rdf.core.access.TcProvider; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author mir,rbn + */ +@RunWith(JUnitPlatform.class) +public abstract class TcProviderTest { + + protected final IRI uriRefA = generateUri("a"); + protected final IRI uriRefA1 = generateUri("a1"); + protected final IRI uriRefB = generateUri("b"); + protected final IRI uriRefB1 = generateUri("b1"); + protected final IRI uriRefC = generateUri("c"); + + protected final IRI graphIRI = generateUri("myGraph"); + protected final IRI otherGraphIRI = new IRI(graphIRI.getUnicodeString()); + + @Test + public void testCreateImmutableGraph() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + + ImmutableGraph createdGraph = simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + + Iterator iteratorInput = mGraph.iterator(); + Iterator iteratorCreated = createdGraph.iterator(); + assertEquals(iteratorInput.next(), iteratorCreated.next()); + assertFalse(iteratorCreated.hasNext()); + + try { + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + assertTrue(false); + } catch (EntityAlreadyExistsException e) { + assertTrue(true); + } + simpleTcmProvider.deleteGraph(uriRefA); + } + + @Test + public void testCreateGraph() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = simpleTcmProvider.createGraph(uriRefA); + assertTrue(mGraph.isEmpty()); + + try { + simpleTcmProvider.createGraph(uriRefA); + assertTrue(false); + } catch (EntityAlreadyExistsException e) { + assertTrue(true); + } + simpleTcmProvider.deleteGraph(uriRefA); + } + + @Test + public void testGetImmutableGraph() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + simpleTcmProvider.createImmutableGraph(uriRefA1, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + simpleTcmProvider.createImmutableGraph(uriRefB, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + simpleTcmProvider.createImmutableGraph(uriRefB1, mGraph); + + ImmutableGraph bGraph = simpleTcmProvider.getImmutableGraph(uriRefB); + Iterator iterator = bGraph.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + } + + @Test + public void testGetGraph() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = simpleTcmProvider.createGraph(uriRefA); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + mGraph = simpleTcmProvider.createGraph(uriRefA1); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + mGraph = simpleTcmProvider.createGraph(uriRefB); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefA)); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + mGraph.remove(new TripleImpl(uriRefB, uriRefB, uriRefA)); + assertEquals(1, mGraph.size()); + mGraph = simpleTcmProvider.createGraph(uriRefB1); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + + Graph bGraph = simpleTcmProvider.getGraph(uriRefB); + Iterator iterator = bGraph.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + + } + + @Test + public void testGetTriples() { + TcProvider simpleTcmProvider = getInstance(); + // add Graphs + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + simpleTcmProvider.createImmutableGraph(uriRefA, mGraph); + mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); + simpleTcmProvider.createImmutableGraph(uriRefB, mGraph); + // add Graphs + mGraph = simpleTcmProvider.createGraph(uriRefA1); + mGraph.add(new TripleImpl(uriRefA1, uriRefA1, uriRefA1)); + mGraph = simpleTcmProvider.createGraph(uriRefB1); + mGraph.add(new TripleImpl(uriRefB1, uriRefB1, uriRefB1)); + + // get a ImmutableGraph + Graph tripleCollection = simpleTcmProvider.getGraph(uriRefA); + // get a Graph + Graph tripleCollection2 = simpleTcmProvider.getGraph(uriRefB1); + + Iterator iterator = tripleCollection.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + + iterator = tripleCollection2.iterator(); + assertEquals(new TripleImpl(uriRefB1, uriRefB1, uriRefB1), iterator.next()); + assertFalse(iterator.hasNext()); + simpleTcmProvider.deleteGraph(uriRefA); + simpleTcmProvider.deleteGraph(uriRefA1); + simpleTcmProvider.deleteGraph(uriRefB); + simpleTcmProvider.deleteGraph(uriRefB1); + } + + @Test + public void testDeleteEntity() { + TcProvider simpleTcmProvider = getInstance(); + Graph mGraph = new SimpleGraph(); + mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); + ImmutableGraph graph = mGraph.getImmutableGraph(); + simpleTcmProvider.createImmutableGraph(uriRefA, graph); + simpleTcmProvider.createImmutableGraph(uriRefC, graph); + + simpleTcmProvider.deleteGraph(uriRefA); + try { + simpleTcmProvider.getGraph(uriRefA); + assertTrue(false); + } catch (NoSuchEntityException e) { + assertTrue(true); + } + + // Check that graph is still available under uriRefC + ImmutableGraph cGraph = simpleTcmProvider.getImmutableGraph(uriRefC); + assertNotNull(cGraph); + simpleTcmProvider.deleteGraph(uriRefC); + } + + /** + * Subclasses implement this method to provide implementation instances of + * TcProvider. The first call within a test method has to + * return a empty TcProvider. Subsequent calls within the test method + * should instantiate a new provider, but load the previously added data from + * its "persistent" store. + * + * @return a TcProvider of the implementation to be tested. + */ + protected abstract TcProvider getInstance(); + +// @Test +// public void testGetNames() { +// Graph mGraph = new SimpleGraph(); +// mGraph.add(new TripleImpl(uriRefB, uriRefB, uriRefB)); +// simpleTcmProvider.createGraph(uriRefB, mGraph.getGraph()); +// +// mGraph = new SimpleGraph(); +// mGraph.add(new TripleImpl(uriRefA, uriRefA, uriRefA)); +// ImmutableGraph graph = mGraph.getGraph(); +// simpleTcmProvider.createGraph(uriRefA, graph); +// simpleTcmProvider.createGraph(uriRefC, graph); +// +// Set names = simpleTcmProvider.getNames(graph); +// +// assertTrue(names.contains(uriRefA)); +// assertTrue(names.contains(uriRefC)); +// assertEquals(2, names.size()); +// +// assertFalse(names.contains(uriRefB)); +// } + + @Test + public void testCreateGraphExtended() throws Exception { + + TcProvider provider = getInstance(); + Graph graph = provider.createGraph(graphIRI); + assertNotNull(graph); + //get a new provider and check that graph is there + provider = getInstance(); + graph = provider.getGraph(graphIRI); + assertNotNull(graph); + //check that there is no such graph, but only the mgraph + boolean expThrown = false; + try { + ImmutableGraph g = provider.getImmutableGraph(graphIRI); + } catch(NoSuchEntityException e) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateImmutableGraphExtended() throws Exception { + + TcProvider provider = getInstance(); + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, null); + + assertNotNull(graph); + + //get a new provider and check that graph is there + provider = getInstance(); + graph = provider.getImmutableGraph(graphIRI); + assertNotNull(graph); + + //check that there is no such mgraph, but only the graph + boolean expThrown = false; + + try { + Graph g = provider.getMGraph(graphIRI); + } catch(NoSuchEntityException e) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphNoDuplicateNames() throws Exception { + + TcProvider provider = getInstance(); + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, null); + assertNotNull(graph); + boolean expThrown = false; + try { + ImmutableGraph other = provider.createImmutableGraph(otherGraphIRI, null); + } catch(EntityAlreadyExistsException eaee) { + expThrown = true; + } + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphNoDuplicateNames2() throws Exception { + + TcProvider provider = getInstance(); + Graph graph = provider.createGraph(graphIRI); + assertNotNull(graph); + boolean expThrown = false; + try { + Graph other = provider.createGraph(otherGraphIRI); + } catch(EntityAlreadyExistsException eaee) { + expThrown = true; + } + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + + @Test + public void testCreateGraphWithInitialCollection() throws Exception { + + Triple t1 = createTestTriple(); + + TcProvider provider = getInstance(); + + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, createTestTripleCollection(t1)); + + assertEquals(1, graph.size()); + assertTrue(graph.contains(t1)); + provider.deleteGraph(graphIRI); + } + + @Test + public void testGraphIsNotMutable() throws Exception { + + Triple t1 = createTestTriple(); + Set t = new HashSet(); + t.add(t1); + + TcProvider provider = getInstance(); + + ImmutableGraph graph = provider.createImmutableGraph(graphIRI, createTestTripleCollection(t1)); + + boolean expThrown = false; + + try { + graph.add(t1); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + expThrown = false; + + try { + graph.remove(t1); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + expThrown = false; + + try { + graph.addAll(t); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + + expThrown = false; + + try { + graph.clear(); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + + expThrown = false; + + try { + graph.removeAll(t); + } catch(UnsupportedOperationException uoe) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(graphIRI); + } + +// This tests can not pass, because equals in AbstractGraph is not implemented +// yet. +// @Test +// public void testGraphHasName() throws Exception { +// +// TcProvider provider = getInstance(); +// +// Graph triples = createTestTripleCollection(createTestTriple()); +// ImmutableGraph graph = provider.createGraph(graphIRI, triples); +// +// provider = getInstance(); +// Set names = provider.getNames(graph); +// assertTrue(names.contains(graphIRI)); +// } +// +// @Test +// public void testCreateSameGraphWithDifferentNames() throws Exception { +// +// Graph triples = createTestTripleCollection(createTestTriple()); +// +// TcProvider provider = getInstance(); +// IRI name1 = new IRI("http://myGraph1"); +// ImmutableGraph graph = provider.createGraph(name1, triples); +// +// IRI name2 = new IRI("http://myGraph2"); +// ImmutableGraph secondGraph = provider.createGraph(name2, triples); +// +// Set names = provider.getNames(graph); +// assertNotNull(names); +// assertEquals(2, names.size()); +// } + + @Test + public void testGraphDeletion() throws Exception { + + Graph triples = createTestTripleCollection(createTestTriple()); + + TcProvider provider = getInstance(); + IRI name1 = new IRI("http://myGraph1"); + ImmutableGraph graph = provider.createImmutableGraph(name1, triples); + + IRI name2 = new IRI("http://myGraph2"); + ImmutableGraph secondGraph = provider.createImmutableGraph(name2, triples); + + //if we delete graph with name1, the second graph should still be there + provider.deleteGraph(name1); + + provider = getInstance(); + ImmutableGraph firstGraph = provider.getImmutableGraph(name2); + assertNotNull(firstGraph); + + //check second name is not there + boolean expThrown = false; + + try { + ImmutableGraph g = provider.getImmutableGraph(name1); + } catch(NoSuchEntityException nses) { + expThrown = true; + } + + assertTrue(expThrown); + provider.deleteGraph(name2); + } + + + + @Test + public void testGetTriplesGraph() throws Exception { + TcProvider provider = getInstance(); + + Graph graph = provider.createGraph(graphIRI); + + Graph tc = provider.getGraph(graphIRI); + assertNotNull(tc); + provider.deleteGraph(graphIRI); + } + + private Triple createTestTriple() { + BlankNodeOrIRI subject = new BlankNode() {}; + IRI predicate = new IRI("http://test.com/"); + BlankNodeOrIRI object = new IRI("http://test.com/myObject"); + return new TripleImpl(subject, predicate, object); + } + + private Graph createTestTripleCollection(Triple t) { + Set ts = new HashSet(); + ts.add(t); + return new SimpleGraph(ts); + } + + protected IRI generateUri(String name) { + return new IRI("http://example.org/" + name); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java new file mode 100644 index 0000000000..04474a208a --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LanguageTest.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.apache.clerezza.commons.rdf.Language; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class LanguageTest { + + @Test + public void languageEqualityTest() { + Language lang1 = new Language("DE"); + Language lang2 = new Language("DE"); + assertEquals(lang1, lang2); + assertEquals(lang1.hashCode(), lang2.hashCode()); + Language lang3 = new Language("EN"); + assertFalse(lang1.equals(lang3)); + } + + @Test + public void toStringTest() { + final String id = "de"; + Language lang1 = new Language(id); + assertEquals(lang1.toString(), id); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java new file mode 100644 index 0000000000..12adb8ea5a --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/LiteralFactoryTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.Date; + +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.IRI; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class LiteralFactoryTest { + + /** + * Test that a NoConvertorException thrown for an unsupported convertor + */ + @Test + public void unavailableConvertor() { + Object value = new Object() {}; + assertThrows(NoConvertorException.class, () -> + LiteralFactory.getInstance().createTypedLiteral(value)); + } + + /** + * Test conversion of byte[] to literal an back + */ + @Test + public void byteArrayConversion() { + byte[] bytes = new byte[5]; + for (byte i = 0; i < bytes.length; i++) { + bytes[i] = i; + } + Literal literal = LiteralFactory.getInstance().createTypedLiteral(bytes); + assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#base64Binary"), + literal.getDataType()); + //we are using bytes.getClass() but there should be a way to get + //that instance of Class without getting it from an instance + //but this is java-bug 4071439 (would like byte[].class or byte.class.getArrayType()) + byte[] bytesBack = LiteralFactory.getInstance().createObject(bytes.getClass(), literal); + assertTrue(Arrays.equals(bytes, bytesBack)); + + } + + /** + * Test conversion of java.util.Date to literal an back + */ + @Test + public void dateConversion() { + Date date = new Date(); + Literal literal = LiteralFactory.getInstance().createTypedLiteral(date); + assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#dateTime"), + literal.getDataType()); + Date dateBack = LiteralFactory.getInstance().createObject(Date.class, literal); + assertEquals(date.getTime(), dateBack.getTime()); + + } + + /** + * Test conversion of String to literal an back + */ + @Test + public void stringConversion() { + String value = "Hello world"; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#string"), + literal.getDataType()); + String valueBack = LiteralFactory.getInstance().createObject(String.class, literal); + assertEquals(value, valueBack); + + } + + /** + * Test conversion of Integer to literal an back + */ + @Test + public void intConversion() { + int value = 3; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#int"), + literal.getDataType()); + Integer valueBack = LiteralFactory.getInstance().createObject(Integer.class, literal); + assertEquals(value, valueBack.intValue()); + + } + + /** + * Test conversion of Long to literal an back + */ + @Test + public void longConversion() { + long value = 332314646; + Literal literal = LiteralFactory.getInstance().createTypedLiteral(value); + assertEquals(new IRI("http://www.w3.org/2001/XMLSchema#long"), + literal.getDataType()); + Long valueBack = LiteralFactory.getInstance().createObject(Long.class, literal); + assertEquals(value, valueBack.longValue()); + + } + + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java new file mode 100644 index 0000000000..cd8501c1d5 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/UriRefTest.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; + +import org.apache.clerezza.commons.rdf.IRI; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author reto + */ +public class UriRefTest { + + private Logger logger = LoggerFactory.getLogger(UriRefTest.class); + + @Test + public void uriRefEqualityTest() { + try { + String uriRefString = "http://example.org/üöä"; + IRI uriRef1 = new IRI(uriRefString); + IRI uriRef2 = new IRI(uriRefString); + assertEquals(uriRef1, uriRef2); + IRI uriRef3 = + new IRI(URLEncoder.encode(uriRefString, "utf-8")); + assertFalse(uriRef1.equals(uriRef3)); + } catch (UnsupportedEncodingException ex) { + logger.error("Exception {} ", ex); + } + } + + @Test + public void toStringTest() { + String uriRefString = "http://example.org/üöä"; + IRI uriRef = new IRI(uriRefString); + assertEquals("<"+uriRefString+">", uriRef.toString()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java new file mode 100644 index 0000000000..b0ca936395 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/SecurityTest.java @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.access; + +import static org.slf4j.LoggerFactory.getLogger; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.FilePermission; +import java.lang.reflect.ReflectPermission; +import java.security.AccessControlException; +import java.security.CodeSource; +import java.security.Permission; +import java.security.PermissionCollection; +import java.security.Permissions; +import java.security.Policy; +import java.util.Collections; +import java.util.PropertyPermission; + +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; +import org.apache.clerezza.rdf.core.access.providers.WeightedDummy; +import org.apache.clerezza.rdf.core.access.security.TcPermission; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.slf4j.Logger; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class SecurityTest { + + private static final Logger LOGGER = getLogger(SecurityTest.class); + + public SecurityTest() { + } + + @BeforeAll + public static void setUpClass() throws Exception { + ////needed to unbind because this is injected with META-INF/services - file + TcManager.getInstance().unbindWeightedTcProvider(new WeightedA()); + TcManager.getInstance().bindWeightedTcProvider(new WeightedDummy()); + TcManager.getInstance().createGraph(new IRI("http://example.org/ImmutableGraph/alreadyexists")); + TcManager.getInstance().createGraph(new IRI("http://example.org/read/ImmutableGraph")); + } + + @AfterAll + public static void tearDownClass() throws Exception { + } + + @BeforeEach + public void setUp() { + + Policy.setPolicy(new Policy() { + + @Override + public PermissionCollection getPermissions(CodeSource codeSource) { + PermissionCollection result = new Permissions(); + result.add(new TcPermission("http://example.org/permitted", "read")); + result.add(new TcPermission("http://example.org/ImmutableGraph/alreadyexists", "readwrite")); + result.add(new TcPermission("http://example.org/read/ImmutableGraph", "read")); + result.add(new TcPermission("http://example.org/area/allowed/*", "readwrite")); + result.add(new TcPermission("urn:x-localinstance:/graph-access.graph", "readwrite")); + //result.add(new AllPermission()); + result.add(new RuntimePermission("*")); + result.add(new ReflectPermission("suppressAccessChecks")); + result.add(new PropertyPermission("*", "read")); + //(java.util.PropertyPermission line.separator read) + result.add(new FilePermission("/-", "read,write")); + return result; + } + }); + System.setSecurityManager(new SecurityManager() { + + @Override + public void checkPermission(Permission perm) { + LOGGER.debug("Checking {}", perm); + super.checkPermission(perm); + } + + @Override + public void checkPermission(Permission perm, Object context) { + LOGGER.debug("Checking {}", perm); + super.checkPermission(perm, context); + } + + }); + } + + @AfterEach + public void tearDown() { + System.setSecurityManager(null); + } + + + @Test + public void testAcessGraph() { + assertThrows(NoSuchEntityException.class, () -> + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/permitted"))); + } + + @Test + public void testNoWildCard() { + assertThrows(AccessControlException.class, () -> + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/permitted/subthing"))); + } + + @Test + public void testAllowedArea() { + assertThrows(NoSuchEntityException.class, () -> + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/area/allowed/something"))); + } + + @Test + public void testAcessForbiddenGraph() { + assertThrows(AccessControlException.class, () -> + TcManager.getInstance().getImmutableGraph(new IRI("http://example.org/forbidden"))); + } + + @Test + public void testCustomPermissions() { + IRI graphUri = new IRI("http://example.org/custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadPermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + + LOGGER.info("Custom permissions graph: {}", ag); + assertThrows(NoSuchEntityException.class, () -> + TcManager.getInstance().getMGraph(graphUri)); + } + + @Test + public void testCustomPermissionsIncorrect() { + IRI graphUri = new IRI("http://example.org/custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadPermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + + LOGGER.info("Incorrect custom permissions graph: {}", ag); + assertThrows(AccessControlException.class, () -> + TcManager.getInstance().createGraph(graphUri)); + } + + @Test + public void testCustomReadWritePermissions() { + IRI graphUri = new IRI("http://example.org/read-write-custom"); + TcManager.getInstance().getTcAccessController().setRequiredReadWritePermissionStrings(graphUri, + Collections.singletonList("(java.io.FilePermission \"/etc\" \"write\")")); + //new FilePermission("/etc", "write").toString())); + Graph ag = TcManager.getInstance().getGraph(new IRI("urn:x-localinstance:/graph-access.graph")); + + LOGGER.info("Custom read/write permissions graph: {}", ag); + TcManager.getInstance().createGraph(graphUri); + } + + @Test + public void testCreateMGraph() { + assertThrows(EntityAlreadyExistsException.class, () -> + TcManager.getInstance().createGraph(new IRI("http://example.org/ImmutableGraph/alreadyexists"))); + } + + @Test + public void testCreateMGraphWithoutWritePermission() { + assertThrows(AccessControlException.class, () -> + TcManager.getInstance().createGraph(new IRI("http://example.org/read/ImmutableGraph"))); + } + + @Test + public void testAddTripleToMGraph() { + Graph graph = TcManager.getInstance().getMGraph(new IRI("http://example.org/read/ImmutableGraph")); + Triple triple = new TripleImpl(new IRI("http://example.org/definition/isNonLiteral"), new IRI("http://example.org/definition/isTest"), new PlainLiteralImpl("test")); + assertThrows(ReadOnlyException.class, () -> graph.add(triple)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java new file mode 100644 index 0000000000..a542b4060b --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/access/TcManagerTest.java @@ -0,0 +1,313 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.access; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.lang.reflect.Field; +import java.util.Iterator; + +import org.apache.clerezza.commons.rdf.ImmutableGraph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; +import org.apache.clerezza.rdf.core.access.providers.WeightedA1; +import org.apache.clerezza.rdf.core.access.providers.WeightedAHeavy; +import org.apache.clerezza.rdf.core.access.providers.WeightedBlight; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleMGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.core.sparql.NoQueryEngineException; +import org.apache.clerezza.rdf.core.sparql.QueryEngine; +import org.apache.clerezza.rdf.core.sparql.query.AskQuery; +import org.apache.clerezza.rdf.core.sparql.query.ConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.DescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.Query; +import org.apache.clerezza.rdf.core.sparql.query.SelectQuery; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; +import org.mockito.Mockito; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class TcManagerTest { + + public static IRI uriRefAHeavy = new IRI("http://example.org/aHeavy"); + public static IRI uriRefB = new IRI("http://example.org/b");; + public static final IRI uriRefA = new IRI("http://example.org/a"); + public static final IRI uriRefA1 = new IRI("http://example.org/a1"); + private TcManager graphAccess; + private QueryEngine queryEngine; + private final WeightedA weightedA = new WeightedA(); + private final WeightedA1 weightedA1 = new WeightedA1(); + private WeightedTcProvider weightedBlight = new WeightedBlight(); + + @BeforeEach + public void setUp() { + graphAccess = TcManager.getInstance(); + graphAccess.bindWeightedTcProvider(weightedA); + graphAccess.bindWeightedTcProvider(weightedA1); + graphAccess.bindWeightedTcProvider(weightedBlight); + + queryEngine = Mockito.mock(QueryEngine.class); + } + + @AfterEach + public void tearDown() { + graphAccess = TcManager.getInstance(); + graphAccess.unbindWeightedTcProvider(weightedA); + graphAccess.unbindWeightedTcProvider(weightedA1); + graphAccess.unbindWeightedTcProvider(weightedBlight); + + queryEngine = null; + } + + @Test + public void getGraphFromA() { + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefA, uriRefA, uriRefA), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromB() { + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefB); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefB); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefB, uriRefB, uriRefB), iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromAAfterUnbinding() { + graphAccess.unbindWeightedTcProvider(weightedA); + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefA1, uriRefA1, uriRefA1), + iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefA1, uriRefA1, uriRefA1), + iterator.next()); + assertFalse(iterator.hasNext()); + } + + @Test + public void getGraphFromAWithHeavy() { + final WeightedAHeavy weightedAHeavy = new WeightedAHeavy(); + graphAccess.bindWeightedTcProvider(weightedAHeavy); + ImmutableGraph graphA = graphAccess.getImmutableGraph(uriRefA); + Iterator iterator = graphA.iterator(); + assertEquals(new TripleImpl(uriRefAHeavy, uriRefAHeavy, uriRefAHeavy), + iterator.next()); + assertFalse(iterator.hasNext()); + Graph triplesA = graphAccess.getGraph(uriRefA); + iterator = triplesA.iterator(); + assertEquals(new TripleImpl(uriRefAHeavy, uriRefAHeavy, uriRefAHeavy), + iterator.next()); + assertFalse(iterator.hasNext()); + graphAccess.unbindWeightedTcProvider(weightedAHeavy); + } + + @Test + public void executeSparqlQueryNoEngineWithString() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery("", new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryNoEngineWithQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery((Query) null, new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryNoEngineWithSelectQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery((SelectQuery) null, new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryNoEngineWithAskQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery((AskQuery) null, new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryNoEngineWithDescribeQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery((DescribeQuery) null, new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryNoEngineWithConstructQuery() throws Exception { + // Prepare + injectQueryEngine(null); + + // Execute + assertThrows(NoQueryEngineException.class, () -> + graphAccess.executeSparqlQuery((ConstructQuery) null, new SimpleMGraph())); + } + + @Test + public void executeSparqlQueryWithEngineWithString() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + + // Execute + graphAccess.executeSparqlQuery("", Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, ""); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), + (Query) Mockito.anyObject()); + } + + @Test + public void executeSparqlQueryWithEngineWithSelectQuery() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + SelectQuery query = Mockito.mock(SelectQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithAskQuery() throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + AskQuery query = Mockito.mock(AskQuery.class); + + Mockito.when( + queryEngine.execute((TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), + (Query) Mockito.anyObject())).thenReturn(Boolean.TRUE); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithDescribeQuery() + throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + DescribeQuery query = Mockito.mock(DescribeQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + @Test + public void executeSparqlQueryWithEngineWithConstructQuery() + throws Exception { + // Prepare + injectQueryEngine(queryEngine); + Graph Graph = new SimpleMGraph(); + ConstructQuery query = Mockito.mock(ConstructQuery.class); + + // Execute + graphAccess.executeSparqlQuery(query, Graph); + + // Verify + Mockito.verify(queryEngine).execute(graphAccess, Graph, + (Query) query); + Mockito.verify(queryEngine, Mockito.never()).execute( + (TcManager) Mockito.anyObject(), + (Graph) Mockito.anyObject(), Mockito.anyString()); + } + + // ------------------------------------------------------------------------ + // Implementing QueryableTcProvider + // ------------------------------------------------------------------------ + + private void injectQueryEngine(QueryEngine engine) + throws NoSuchFieldException, IllegalAccessException { + Field queryEngineField = TcManager.class + .getDeclaredField("queryEngine"); + queryEngineField.setAccessible(true); + queryEngineField.set(graphAccess, engine); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java new file mode 100644 index 0000000000..83bb233cfd --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/SimpleLiteralFactoryTest.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.impl.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.clerezza.rdf.core.impl.util.SimpleLiteralFactory; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.IRI; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class SimpleLiteralFactoryTest { + + final private static IRI xsdInteger = + new IRI("http://www.w3.org/2001/XMLSchema#integer"); + final private static IRI xsdInt = + new IRI("http://www.w3.org/2001/XMLSchema#int"); + final private static IRI xsdLong = + new IRI("http://www.w3.org/2001/XMLSchema#long"); + + SimpleLiteralFactory simpleLiteralFactory = new SimpleLiteralFactory(); + + @Test + public void longToXsdIntegerAndBackToMany() { + long value = 14l; + Literal tl = simpleLiteralFactory.createTypedLiteral(value); + assertEquals(xsdLong, tl.getDataType()); + long longValue = simpleLiteralFactory.createObject(Long.class, tl); + assertEquals(value, longValue); + int intValue = simpleLiteralFactory.createObject(Integer.class, tl); + assertEquals(value, intValue); + } + + @Test + public void intToXsdIntAndBackToMany() { + int value = 14; + Literal tl = simpleLiteralFactory.createTypedLiteral(value); + assertEquals(xsdInt, tl.getDataType()); + long longValue = simpleLiteralFactory.createObject(Long.class, tl); + assertEquals(value, longValue); + int intValue = simpleLiteralFactory.createObject(Integer.class, tl); + assertEquals(value, intValue); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java new file mode 100644 index 0000000000..d20167d23e --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/impl/util/W3CDateFormatTest.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.impl.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class W3CDateFormatTest { + + @Test + public void noMillis() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT+7:00")); + Date date = calendar.getTime(); + Date parsedDate = new W3CDateFormat().parse("2009-01-01T01:33:58+07:00"); + assertEquals(date, parsedDate); + } + + @Test + public void noMillisinZ() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT")); + Date date = calendar.getTime(); + Date parsedDate = new W3CDateFormat().parse("2009-01-01T01:33:58Z"); + assertEquals(date, parsedDate); + } + + @Test + public void dateObjectSerializedWithoutTimeZone() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, 1, 33, 58); + calendar.setTimeZone(TimeZone.getTimeZone("GMT+7:00")); + Date date = calendar.getTime(); + String serializedDate = new W3CDateFormat().format(date); + assertEquals("2008-12-31T18:33:58Z", serializedDate); + } + + @Test + public void roundTrip() throws Exception { + Calendar calendar = new GregorianCalendar(2009, 0, 1, + 1, 33, 58); + Date date = calendar.getTime(); + String formattedDate = new W3CDateFormat().format(date); + Date parsedDate = new W3CDateFormat().parse(formattedDate); + assertEquals(date, parsedDate); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java new file mode 100644 index 0000000000..02197d3937 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/ParserTest.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.Graph; +import java.io.InputStream; + +import org.apache.clerezza.rdf.core.*; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class ParserTest { + + private static boolean providerAInvoked; + private static boolean providerBInvoked; + private ParsingProvider parsingProviderA = new ParsingProviderA(); + private ParsingProvider parsingProviderB = new ParsingProviderB(); + + @Test + public void registerOneProvider() { + Parser parser = new Parser(null); + parser.bindParsingProvider(parsingProviderA); + providerAInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + assertTrue(providerAInvoked); + } + + @Test + public void registerAndUnregisterSecond() { + Parser parser = new Parser(null); + parser.bindParsingProvider(parsingProviderA); + parser.bindParsingProvider(parsingProviderB); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + assertFalse(providerAInvoked); + assertTrue(providerBInvoked); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy1+rdf"); + assertTrue(providerAInvoked); + assertFalse(providerBInvoked); + parser.unbindParsingProvider(parsingProviderB); + providerAInvoked = false; + providerBInvoked = false; + parser.parse(null, "application/x-fantasy2+rdf"); + assertTrue(providerAInvoked); + assertFalse(providerBInvoked); + + } + + @SupportedFormat({"application/x-fantasy1+rdf", "application/x-fantasy2+rdf"}) + static class ParsingProviderA implements ParsingProvider { + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + providerAInvoked = true; + } + }; + @SupportedFormat("application/x-fantasy2+rdf") + static class ParsingProviderB implements ParsingProvider { + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + providerBInvoked = true; + } + }; +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java new file mode 100644 index 0000000000..fe6695f07c --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/SerializerTest.java @@ -0,0 +1,94 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.clerezza.commons.rdf.Graph; +import java.io.OutputStream; + +import org.apache.clerezza.rdf.core.*; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author mir + */ +@RunWith(JUnitPlatform.class) +public class SerializerTest { + + private static boolean providerAInvoked; + private static boolean providerBInvoked; + private SerializingProvider serializingProviderA = new SerializingProviderA(); + private SerializingProvider serializingProviderB = new SerializingProviderB(); + + @Test + public void registerOneProvider() { + Serializer serializer = new Serializer(null); + serializer.bindSerializingProvider(serializingProviderA); + providerAInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + assertTrue(providerAInvoked); + } + + @Test + public void registerAndUnregisterSecond() { + Serializer serializer = new Serializer(null); + serializer.bindSerializingProvider(serializingProviderA); + serializer.bindSerializingProvider(serializingProviderB); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + assertFalse(providerAInvoked); + assertTrue(providerBInvoked); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy1+rdf"); + assertTrue(providerAInvoked); + assertFalse(providerBInvoked); + serializer.unbindSerializingProvider(serializingProviderB); + providerAInvoked = false; + providerBInvoked = false; + serializer.serialize(null, null, "application/x-fantasy2+rdf"); + assertTrue(providerAInvoked); + assertFalse(providerBInvoked); + + } + + @SupportedFormat({"application/x-fantasy1+rdf", "application/x-fantasy2+rdf"}) + static class SerializingProviderA implements SerializingProvider { + + @Override + public void serialize(OutputStream serializedGraph, Graph tc, String formatIdentifier) { + providerAInvoked = true; + } + }; + @SupportedFormat("application/x-fantasy2+rdf") + static class SerializingProviderB implements SerializingProvider { + + @Override + public void serialize(OutputStream serializedGraph, Graph tc, String formatIdentifier) { + providerBInvoked = true; + } + }; +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java new file mode 100644 index 0000000000..869bdf1cf7 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/serializedform/TestServiceManagedProvider.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.serializedform; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.InputStream; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * This class is listed in + * META-INF/services/org.apache.clerezza.serializedform.ParsingProvider + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +@SupportedFormat("application/x-test+rdf") +public class TestServiceManagedProvider implements ParsingProvider { + + private static boolean parseInvoked; + + @Override + public void parse(Graph target, InputStream serializedGraph, String formatIdentifier, IRI baseUri) { + parseInvoked = true; + } + + @Test + public void registerOneProvider() { + Parser parser = Parser.getInstance(); + parser.parse(null, "application/x-test+rdf"); + assertTrue(parseInvoked); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java new file mode 100644 index 0000000000..3a6e34ee5f --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserSerializerCombinationTest.java @@ -0,0 +1,145 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.clerezza.rdf.core.sparql.query.Query; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author hasan + */ +@RunWith(JUnitPlatform.class) +public class QueryParserSerializerCombinationTest { + + public QueryParserSerializerCombinationTest() { + } + + @BeforeAll + public static void setUpClass() { + } + + @AfterAll + public static void tearDownClass() { + } + + @BeforeEach + public void setUp() { + } + + @AfterEach + public void tearDown() { + } + + @Test + public void testPatternOrderPreservation() throws Exception { + String queryString = + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description \n" + + "WHERE\n" + + "{ ?property .\n" + + "{ { ?property ?superclass .\n" + + " ?superclass .\n" + + "} UNION { ?property ?dunion .\n" + + "?dunion ?dlist .\n" + + "?dlist ?superclass .\n" + + " ?superclass .\n" + + "} } { { ?property ?superrange .\n" + + "?range ?superrange .\n" + + "FILTER (! (isBLANK(?range)))\n" + + "} UNION { ?property ?range .\n" + + "FILTER (! (isBLANK(?range)))\n" + + "} } OPTIONAL { ?somesub ?range .\n" + + "FILTER (((?somesub) != ()) && ((?somesub) != (?range)))\n" + + "} OPTIONAL { ?subproperty ?property .\n" + + " OPTIONAL { ?subproperty ?subproperty_description .\n" + + "} FILTER (((?subproperty) != ()) && ((?subproperty) != (?property)))\n" + + "} OPTIONAL { ?property ?property_description .\n" + + "} FILTER ((?property) != ())\n" + + "FILTER ((?range) != ())\n" + + "FILTER (! (BOUND(?somesub)))\n" + + "} \n"; + + Query query = QueryParser.getInstance().parse(queryString); + assertEquals(queryString.replaceAll("\\s", "").trim(), query.toString().replaceAll("\\s", "").trim()); + } + + @Test + public void testParsingAndSerializationStability() throws Exception { + String queryString = + "PREFIX mo: \n" + + "PREFIX list: \n" + + "PREFIX owl: \n" + + "PREFIX rdf: \n" + + "PREFIX rdfs: \n" + + "PREFIX dc: \n" + + "SELECT ?property ?range ?property_description ?subproperty ?subproperty_description\n" + + "WHERE {\n" + + " ?property a owl:ObjectProperty .\n" + + " FILTER (?property != owl:bottomObjectProperty) .\n" + + " {\n" + + " {\n" + + " ?property rdfs:domain ?superclass .\n" + + " mo:Company rdfs:subClassOf ?superclass .\n" + + " }\n" + + " UNION\n" + + " {\n" + + " ?property rdfs:domain ?dunion .\n" + + " ?dunion owl:unionOf ?dlist .\n" + + " ?dlist list:member ?superclass .\n" + + " mo:Company rdfs:subClassOf ?superclass .\n" + + " }\n" + + " }\n" + + " {\n" + + " {\n" + + " ?property rdfs:range ?superrange .\n" + + " ?range rdfs:subClassOf ?superrange .\n" + + " FILTER (!isBlank(?range)) .\n" + + " }\n" + + " UNION\n" + + " {\n" + + " ?property rdfs:range ?range .\n" + + " FILTER (!isBlank(?range)) .\n" + + " }\n" + + " } .\n" + + " FILTER (?range != owl:Nothing) .\n" + + " OPTIONAL { ?somesub rdfs:subClassOf ?range . FILTER(?somesub != owl:Nothing && ?somesub != ?range)}\n" + + " FILTER (!bound(?somesub)) .\n" + + " OPTIONAL {\n" + + " ?subproperty rdfs:subPropertyOf ?property .\n" + + " FILTER(?subproperty != owl:bottomObjectProperty && ?subproperty != ?property)\n" + + " OPTIONAL { ?subproperty dc:description ?subproperty_description . }\n" + + " }\n" + + " OPTIONAL { ?property dc:description ?property_description . }\n" + + "} "; + + Query query1 = QueryParser.getInstance().parse(queryString); + Thread.sleep(5000l); + Query query2 = QueryParser.getInstance().parse(queryString); + assertEquals(query1.toString(), query2.toString()); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java new file mode 100644 index 0000000000..1459b30eca --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QueryParserTest.java @@ -0,0 +1,392 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.Language; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.rdf.core.sparql.query.AskQuery; +import org.apache.clerezza.rdf.core.sparql.query.BasicGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.BuiltInCall; +import org.apache.clerezza.rdf.core.sparql.query.ConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.DescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.Expression; +import org.apache.clerezza.rdf.core.sparql.query.GraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.GroupGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.OptionalGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.OrderCondition; +import org.apache.clerezza.rdf.core.sparql.query.Query; +import org.apache.clerezza.rdf.core.sparql.query.QueryWithSolutionModifier; +import org.apache.clerezza.rdf.core.sparql.query.ResourceOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.SelectQuery; +import org.apache.clerezza.rdf.core.sparql.query.TriplePattern; +import org.apache.clerezza.rdf.core.sparql.query.UnaryOperation; +import org.apache.clerezza.rdf.core.sparql.query.UriRefOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.Variable; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleTriplePattern; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author hasan + */ +@RunWith(JUnitPlatform.class) +public class QueryParserTest { + + @Test + public void testSelectQuery() throws ParseException { + +// SELECT ?title FROM +// WHERE { ?title . } + + final String variable = "title"; + final String defaultGraph = "http://example.org/library"; + final String subject = "http://example.org/book/book1"; + final String predicate = "http://purl.org/dc/elements/1.1/title"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("SELECT ?").append(variable) + .append(" FROM <").append(defaultGraph) + .append("> WHERE { <").append(subject).append("> <") + .append(predicate).append("> ?").append(variable).append(" . }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + assertTrue(selectQuery.getSelection().get(0) + .equals(new Variable(variable))); + assertTrue(selectQuery.getDataSet().getDefaultGraphs().toArray()[0] + .equals(new IRI(defaultGraph))); + + GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(subject)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); + + assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test + public void testInvalidQuery() throws ParseException { + assertThrows(ParseException.class, () -> QueryParser.getInstance().parse("Hello")); + } + + @Test + public void testSelectQuerySelection() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT ?a ?b WHERE {?a ?x ?b}"); + Set selectionSet = new HashSet( + q.getSelection()); + Set expected = new HashSet(); + expected.add(new Variable("a")); + expected.add(new Variable("b")); + assertEquals(expected, selectionSet); + assertFalse(q.isSelectAll()); + + } + + @Test + public void testSelectAll() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x ?b}"); + Set selectionSet = new HashSet( + q.getSelection()); + Set expected = new HashSet(); + expected.add(new Variable("a")); + expected.add(new Variable("b")); + expected.add(new Variable("x")); + assertEquals(expected, selectionSet); + assertTrue(q.isSelectAll()); + + } + + @Test + public void testPlainLiteral() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x 'tiger' . ?a ?x 'lion'@en . }"); + + GraphPattern gp = (GraphPattern) q.getQueryPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size()==2); + + assertTrue(triplePatterns.contains(new SimpleTriplePattern( + new Variable("a"), new Variable("x"), + new PlainLiteralImpl("tiger")))); + + assertTrue(triplePatterns.contains(new SimpleTriplePattern( + new Variable("a"), new Variable("x"), + new PlainLiteralImpl("lion", new Language("en"))))); + } + + @Test + public void testOrderBy() throws ParseException { + SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( + "SELECT * WHERE {?a ?x ?b} ORDER BY DESC(?b)"); + + List oc = ((QueryWithSolutionModifier) q).getOrderConditions(); + assertTrue(oc.size()==1); + assertFalse(oc.get(0).isAscending()); + Variable b = new Variable("b"); + assertEquals(b, oc.get(0).getExpression()); + } + + @Test + public void testConstructQuery() throws ParseException { + +// CONSTRUCT { ?name} +// WHERE { ?x ?name} + + + final String variable1 = "name"; + final String variable2 = "x"; + final String subject1 = "http://example.org/person#Alice"; + final String predicate1 = "http://www.w3.org/2001/vcard-rdf/3.0#FN"; + final String predicate2 = "http://xmlns.com/foaf/0.1/name"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("CONSTRUCT { <").append(subject1).append("> <") + .append(predicate1).append("> ?").append(variable1) + .append("} WHERE { ?").append(variable2).append(" <") + .append(predicate2).append("> ?").append(variable1).append("}"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(ConstructQuery.class.isAssignableFrom(q.getClass())); + ConstructQuery constructQuery = (ConstructQuery) q; + Set triplePatterns = constructQuery + .getConstructTemplate(); + assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(subject1)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate1)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable1)); + + assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + + GraphPattern gp = (GraphPattern) constructQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size()==1); + + s = new ResourceOrVariable(new Variable(variable2)); + p = new UriRefOrVariable(new IRI(predicate2)); + + assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test + public void testDescribeQuery() throws ParseException { + +// DESCRIBE + + final String resource = "http://example.org/book/book1"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("DESCRIBE <").append(resource).append(">"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(DescribeQuery.class.isAssignableFrom(q.getClass())); + DescribeQuery describeQuery = (DescribeQuery) q; + assertTrue(describeQuery.getResourcesToDescribe().get(0) + .getResource().equals(new IRI(resource))); + } + + @Test + public void testAskQuery() throws ParseException { + +// ASK { ?x "Alice" } + + final String variable = "x"; + final String predicate = "http://xmlns.com/foaf/0.1/name"; + final String object = "Alice"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("ASK { ?").append(variable).append(" <") + .append(predicate).append("> \"").append(object).append("\" }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(AskQuery.class.isAssignableFrom(q.getClass())); + AskQuery askQuery = (AskQuery) q; + + GraphPattern gp = (GraphPattern) askQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size()==1); + + assertTrue(triplePatterns.contains(new SimpleTriplePattern(new Variable(variable), + new IRI(predicate), new PlainLiteralImpl(object)))); + } + + @Test + public void testBaseAndPrefix() throws ParseException { + +// BASE +// PREFIX dc: +// +// SELECT $title +// WHERE { dc:title ?title } + + final String base = "http://example.org/book/"; + final String prefix = "dc"; + final String prefixUri = "http://purl.org/dc/elements/1.1/"; + final String variable = "title"; + final String subject = "book1"; + final String predicate = "title"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("BASE <").append(base).append(">") + .append(" PREFIX ").append(prefix).append(": <") + .append(prefixUri).append("> SELECT $").append(variable) + .append(" WHERE { <").append(subject).append("> ") + .append(prefix).append(":").append(predicate).append(" ?") + .append(variable).append(" }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + assertTrue(selectQuery.getSelection().get(0) + .equals(new Variable(variable))); + + GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) gp; + + Set triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size()==1); + + ResourceOrVariable s = new ResourceOrVariable(new IRI(base+subject)); + UriRefOrVariable p = new UriRefOrVariable(new IRI(prefixUri+predicate)); + ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); + + assertTrue(triplePatterns.contains( + new SimpleTriplePattern(s, p, o))); + } + + @Test + public void testOptionalAndFilter() throws ParseException { + +// PREFIX dc: +// PREFIX books: +// +// SELECT ?book ?title +// WHERE +// { ?book dc:title ?title . +// OPTIONAL +// { ?book books:author ?author .} +// FILTER ( ! bound(?author) ) +// } + final String prefix1 = "dc"; + final String prefix1Uri = "http://purl.org/dc/elements/1.1/"; + final String prefix2 = "books"; + final String prefix2Uri = "http://example.org/book/"; + final String variable1 = "book"; + final String variable2 = "title"; + final String variable3 = "author"; + final String predicate1 = "title"; + final String predicate2 = "author"; + + StringBuffer queryStrBuf = new StringBuffer(); + queryStrBuf.append("PREFIX ").append(prefix1).append(": <").append(prefix1Uri) + .append("> PREFIX ").append(prefix2).append(": <").append(prefix2Uri) + .append("> SELECT ?").append(variable1).append(" ?").append(variable2) + .append(" WHERE { ?").append(variable1).append(" ") + .append(prefix1).append(":").append(predicate1) + .append(" ?").append(variable2).append(" . OPTIONAL { ?") + .append(variable1).append(" ").append(prefix2).append(":") + .append(predicate2).append(" ?").append(variable3) + .append(" .} FILTER ( ! bound(?").append(variable3).append(") ) }"); + + Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); + assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); + SelectQuery selectQuery = (SelectQuery) q; + assertTrue(selectQuery.getSelection().size() == 2); + Set vars = new HashSet(2); + Variable var1 = new Variable(variable1); + Variable var2 = new Variable(variable2); + vars.add(var1); + vars.add(var2); + assertTrue(selectQuery.getSelection().containsAll(vars)); + + GroupGraphPattern ggp = selectQuery.getQueryPattern(); + List constraints = ggp.getFilter(); + assertTrue(UnaryOperation.class.isAssignableFrom(constraints + .get(0).getClass())); + UnaryOperation uop = (UnaryOperation) constraints.get(0); + assertTrue(uop.getOperatorString().equals("!")); + assertTrue(BuiltInCall.class.isAssignableFrom(uop.getOperand() + .getClass())); + BuiltInCall bic = (BuiltInCall) uop.getOperand(); + assertTrue(bic.getName().equals("BOUND")); + Variable var3 = new Variable(variable3); + assertTrue(bic.getArguements().get(0).equals(var3)); + + GraphPattern gp = (GraphPattern) ggp.getGraphPatterns().toArray()[0]; + assertTrue(OptionalGraphPattern.class.isAssignableFrom(gp.getClass())); + OptionalGraphPattern ogp = (OptionalGraphPattern) gp; + assertTrue(BasicGraphPattern.class.isAssignableFrom( + ogp.getMainGraphPattern().getClass())); + BasicGraphPattern bgp = (BasicGraphPattern) ogp.getMainGraphPattern(); + + Set triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size() == 1); + assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix1Uri + predicate1), + var2))); + + GraphPattern gp2 = (GraphPattern) ogp.getOptionalGraphPattern() + .getGraphPatterns().toArray()[0]; + assertTrue(BasicGraphPattern.class.isAssignableFrom(gp2.getClass())); + bgp = (BasicGraphPattern) gp2; + + triplePatterns = bgp.getTriplePatterns(); + assertTrue(triplePatterns.size() == 1); + assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix2Uri + predicate2), + var3))); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java new file mode 100644 index 0000000000..0175a1ab68 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/QuerySerializerTest.java @@ -0,0 +1,324 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.clerezza.rdf.core.LiteralFactory; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.sparql.query.BinaryOperation; +import org.apache.clerezza.rdf.core.sparql.query.BuiltInCall; +import org.apache.clerezza.rdf.core.sparql.query.Expression; +import org.apache.clerezza.rdf.core.sparql.query.LiteralExpression; +import org.apache.clerezza.rdf.core.sparql.query.ResourceOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.TriplePattern; +import org.apache.clerezza.rdf.core.sparql.query.UriRefExpression; +import org.apache.clerezza.rdf.core.sparql.query.UriRefOrVariable; +import org.apache.clerezza.rdf.core.sparql.query.Variable; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleAskQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleBasicGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleConstructQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleDescribeQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleGroupGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleOptionalGraphPattern; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleOrderCondition; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleSelectQuery; +import org.apache.clerezza.rdf.core.sparql.query.impl.SimpleTriplePattern; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author hasan + */ +@RunWith(JUnitPlatform.class) +public class QuerySerializerTest { + + @Test + public void testSelectQuery() { + + final String queryString = "SELECT ?title FROM " + + " WHERE { " + + " ?title . }"; + + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + Variable variable = new Variable("title"); + selectQuery.addSelection(variable); + IRI defaultGraph = new IRI("http://example.org/library"); + selectQuery.addDefaultGraph(defaultGraph); + ResourceOrVariable subject = new ResourceOrVariable( + new IRI("http://example.org/book/book1")); + UriRefOrVariable predicate = new UriRefOrVariable( + new IRI("http://purl.org/dc/elements/1.1/title")); + ResourceOrVariable object = new ResourceOrVariable(variable); + TriplePattern triplePattern = new SimpleTriplePattern(subject, predicate, object); + Set triplePatterns = new HashSet(); + triplePatterns.add(triplePattern); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + selectQuery.setQueryPattern(queryPattern); + + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testConstructQuery() { + + final String queryString = "CONSTRUCT { " + + " ?name . } " + + "WHERE { ?x ?name . }"; + + ResourceOrVariable s = new ResourceOrVariable( + new IRI("http://example.org/person#Alice")); + UriRefOrVariable p = new UriRefOrVariable( + new IRI("http://www.w3.org/2001/vcard-rdf/3.0#FN")); + ResourceOrVariable o = new ResourceOrVariable(new Variable("name")); + Set constructTriplePatterns = new HashSet(); + constructTriplePatterns.add(new SimpleTriplePattern(s, p, o)); + SimpleConstructQuery constructQuery = new SimpleConstructQuery(constructTriplePatterns); + + s = new ResourceOrVariable(new Variable("x")); + p = new UriRefOrVariable(new IRI("http://xmlns.com/foaf/0.1/name")); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(s, p, o)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + constructQuery.setQueryPattern(queryPattern); + + assertTrue(constructQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testDescribeQuery() { + + final String queryString = "DESCRIBE "; + + SimpleDescribeQuery describeQuery = new SimpleDescribeQuery(); + describeQuery.addResourceToDescribe(new ResourceOrVariable( + new IRI("http://example.org/book/book1"))); + + assertTrue(describeQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testAskQuery() { + + final String queryString = "ASK WHERE { ?x " + + "\"Alice\"^^ . }"; + + ResourceOrVariable s = new ResourceOrVariable(new Variable("x")); + UriRefOrVariable p = new UriRefOrVariable( + new IRI("http://xmlns.com/foaf/0.1/name")); + ResourceOrVariable o = new ResourceOrVariable( + LiteralFactory.getInstance().createTypedLiteral("Alice")); + + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(s, p, o)); + SimpleAskQuery askQuery = new SimpleAskQuery(); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + askQuery.setQueryPattern(queryPattern); + + assertTrue(askQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + /** + * Ignoring: given that triplePatterns is a Set I don't see what is supposed + * to guarantee the expected ordering. + */ + @Disabled + @Test + public void testFilter() { + + final String queryString = "SELECT ?title ?price WHERE { " + + "?x ?title . " + + "?x ?price . " + + "FILTER ((?price) < (\"30.5\"^^)) " + + "}"; + + Variable price = new Variable("price"); + Variable title = new Variable("title"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(title); + selectQuery.addSelection(price); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://example.org/ns#price"), price)); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://purl.org/dc/elements/1.1/title"), title)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + BinaryOperation constraint = new BinaryOperation("<", + price, new LiteralExpression(LiteralFactory.getInstance().createTypedLiteral(30.5))); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testUriRefExpression() { + + final String queryString = "SELECT ?resource WHERE { " + + "?resource ?myType . " + + "FILTER ((?resource) = ()) " + + "}"; + + Variable resource = new Variable("resource"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(resource); + + Variable myType = new Variable("myType"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(resource, + new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), myType)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + BinaryOperation constraint = new BinaryOperation("=", + resource, new UriRefExpression(new IRI("http://example.org/ontology#special"))); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testOrderBy() { + + final String queryString = "SELECT * WHERE { ?a ?b ?c . } ORDER BY DESC(?c)"; + + Variable a = new Variable("a"); + Variable b = new Variable("b"); + Variable c = new Variable("c"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.setSelectAll(); + selectQuery.addSelection(a); + selectQuery.addSelection(b); + selectQuery.addSelection(c); + + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(a, b, c)); + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + selectQuery.setQueryPattern(queryPattern); + selectQuery.addOrderCondition(new SimpleOrderCondition(c, false)); + + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testOptional() { + + final String queryString = "SELECT ?title ?price WHERE { " + + "?x ?title . " + + "OPTIONAL { ?x ?price . } " + + "}"; + + Variable title = new Variable("title"); + Variable price = new Variable("price"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(title); + selectQuery.addSelection(price); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern(x, + new IRI("http://purl.org/dc/elements/1.1/title"), title)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + + Set triplePatternsOpt = new HashSet(); + triplePatternsOpt.add(new SimpleTriplePattern(x, + new IRI("http://example.org/ns#price"), price)); + + SimpleBasicGraphPattern bgpOpt = + new SimpleBasicGraphPattern(triplePatternsOpt); + + SimpleGroupGraphPattern ggpOpt = new SimpleGroupGraphPattern(); + ggpOpt.addGraphPattern(bgpOpt); + + SimpleOptionalGraphPattern ogp = new SimpleOptionalGraphPattern(bgp, ggpOpt); + + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(ogp); + selectQuery.setQueryPattern(queryPattern); + + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } + + @Test + public void testRegex() { + + final String queryString = "SELECT ?p WHERE { " + + " ?p ?x . " + + "FILTER REGEX(?x,\".*uni.*\"^^) }"; + + Variable p = new Variable("p"); + SimpleSelectQuery selectQuery = new SimpleSelectQuery(); + selectQuery.addSelection(p); + + Variable x = new Variable("x"); + Set triplePatterns = new HashSet(); + triplePatterns.add(new SimpleTriplePattern( + new IRI("http://localhost/testitem"), p, x)); + + SimpleBasicGraphPattern bgp = new SimpleBasicGraphPattern(triplePatterns); + SimpleGroupGraphPattern queryPattern = new SimpleGroupGraphPattern(); + queryPattern.addGraphPattern(bgp); + + List arguments = new ArrayList(); + arguments.add(x); + arguments.add(new LiteralExpression(LiteralFactory.getInstance(). + createTypedLiteral(".*uni.*"))); + BuiltInCall constraint = new BuiltInCall("REGEX", arguments); + queryPattern.addConstraint(constraint); + selectQuery.setQueryPattern(queryPattern); + assertTrue(selectQuery.toString() + .replaceAll("( |\n)+", " ").trim().equals(queryString)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java new file mode 100644 index 0000000000..3a0cee9f1d --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/core/src/test/java/org/apache/clerezza/rdf/core/sparql/SparqlPreParserTest.java @@ -0,0 +1,511 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.core.sparql; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.rdf.core.access.TcManager; +import org.apache.clerezza.rdf.core.access.TcManagerTest; +import org.apache.clerezza.rdf.core.access.providers.WeightedA; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author hasan + */ +@RunWith(JUnitPlatform.class) +public class SparqlPreParserTest { + + private TcManager graphAccess; + private final WeightedA weightedA = new WeightedA(); + private final static IRI DEFAULT_GRAPH = new IRI("http://example.org/default.graph"); + private final static IRI TEST_GRAPH = new IRI("http://example.org/test.graph"); + + @BeforeEach + public void setUp() { + graphAccess = TcManager.getInstance(); + graphAccess.addWeightedTcProvider(weightedA); + } + + @AfterEach + public void tearDown() { + graphAccess = TcManager.getInstance(); + graphAccess.removeWeightedTcProvider(weightedA); + } + + @Test + public void testDefaultGraphInSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append( + "PREFIX : \n" + + "SELECT ?x \n" + + "{\n" + + ":order :item/:price ?x\n" + + "}\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testAllGraphReferenceInSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append("SELECT DISTINCT ?g { GRAPH ?g { ?s ?p ?o } }\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + assertTrue(referredGraphs == null); + } + + @Test + public void testSelectQuery() throws ParseException { + + StringBuilder queryStrBuilder = new StringBuilder(); + queryStrBuilder.append( + "PREFIX : \n" + + "SELECT ?x (foo(2*3, ?x < ?y) AS ?f) (GROUP_CONCAT(?x ; separator=\"|\") AS ?gc) (sum(distinct *) AS ?total)\n" + + "FROM " + TEST_GRAPH.toString() + "\n" + + "{\n" + + ":order :item/:price ?x\n" + + "}\n"); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStrBuilder.toString(), DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testSimpleDescribe() throws ParseException { + + String queryStr = "DESCRIBE "; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testLoadingToDefaultGraph() throws ParseException { + + String queryStr = "LOAD SILENT "; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(new IRI("http://example.org/mydata")); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testLoadingToGraph() throws ParseException { + + String queryStr = "LOAD SILENT INTO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(TEST_GRAPH); + expected.add(new IRI("http://example.org/mydata")); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testClearingDefaultGraph() throws ParseException { + + String queryStr = "CLEAR SILENT DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testClearingNamedGraph() throws ParseException { + + String queryStr = "CLEAR SILENT NAMED"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.contains(TcManagerTest.uriRefA)); + } + + @Test + public void testClearingGraph() throws ParseException { + + String queryStr = "CLEAR SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testDroppingDefaultGraph() throws ParseException { + + String queryStr = "DROP SILENT DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDroppingNamedGraph() throws ParseException { + + String queryStr = "DROP SILENT NAMED"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.contains(TcManagerTest.uriRefA)); + } + + @Test + public void testDroppingGraph() throws ParseException { + + String queryStr = "DROP SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testCreatingGraph() throws ParseException { + + String queryStr = "CREATE SILENT GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testAddingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "ADD SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testAddingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "ADD SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testMovingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "MOVE SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testMovingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "MOVE SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testCopyingTriplesFromDefaultGraphToNamedGraph() throws ParseException { + + String queryStr = "COPY SILENT DEFAULT TO GRAPH " + TEST_GRAPH.toString(); + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testCopyingTriplesFromNamedGraphToDefaultGraph() throws ParseException { + + String queryStr = "COPY SILENT GRAPH " + TEST_GRAPH.toString() + " TO DEFAULT"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testInsertDataToDefaultGraph() throws ParseException { + + String queryStr = "PREFIX dc: INSERT DATA { \n" + + " dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testInsertDataToNamedGraph() throws ParseException { + + String queryStr = "PREFIX ns: \n" + + "INSERT DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testDeleteDataInDefaultGraph() throws ParseException { + + String queryStr = "PREFIX dc: DELETE DATA { \n" + + " dc:title \"A new book\" ; dc:creator \"A.N.Other\" . }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDeleteDataInNamedGraph() throws ParseException { + + String queryStr = "PREFIX ns: \n" + + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(TEST_GRAPH)); + } + + @Test + public void testInsertAndDeleteData() throws ParseException { + + String queryStr = "PREFIX ns: " + + "INSERT DATA { ns:price 42 }; " + + "DELETE DATA { GRAPH " + TEST_GRAPH.toString() + " { ns:price 42 } }"; + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(DEFAULT_GRAPH); + expected.add(TEST_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testDeleteWhereInDefaultGraph() throws ParseException { + + String queryStr = "PREFIX foaf: " + + "DELETE WHERE { ?person foaf:givenName 'Fred'; ?property ?value }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testDeleteWhereInNamedGraphs() throws ParseException { + + String queryStr = "PREFIX foaf: DELETE WHERE " + + "{ GRAPH { ?person foaf:givenName 'Fred' ; ?property1 ?value1 } " + + " GRAPH { ?person ?property2 ?value2 } }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example.com/names")); + expected.add(new IRI("http://example.com/addresses")); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testModifyOperationWithFallbackGraph() throws ParseException { + String queryStr = "PREFIX foaf: WITH " + TEST_GRAPH.toString() + + " DELETE { ?person foaf:givenName 'Bill' } INSERT { ?person foaf:givenName 'William' }" + + " WHERE { ?person foaf:givenName 'Bill' }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + Set expected = new HashSet<>(); + expected.add(TEST_GRAPH); + expected.add(DEFAULT_GRAPH); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testDeleteOperationInDefaultGraph() throws ParseException { + String queryStr = "PREFIX dc: PREFIX xsd: " + + "DELETE { ?book ?p ?v } WHERE { ?book dc:date ?date . " + + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testInsertOperationToNamedGraph() throws ParseException { + String queryStr = "PREFIX dc: PREFIX xsd: " + + "INSERT { GRAPH { ?book ?p ?v } } " + + "WHERE { GRAPH { ?book dc:date ?date . " + + "FILTER ( ?date > \"1970-01-01T00:00:00-02:00\"^^xsd:dateTime ) ?book ?p ?v } }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example/bookStore2")); + expected.add(new IRI("http://example/bookStore")); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testInsertAndDeleteWithCommonPrefix() throws ParseException { + String queryStr = "PREFIX dc: \n" + + "PREFIX dcmitype: \n" + + "PREFIX xsd: \n\n" + + "INSERT\n" + + " { GRAPH { ?book ?p ?v } }\n" + + "WHERE\n" + + " { GRAPH \n" + + " { ?book dc:date ?date . \n" + + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime )\n" + + " ?book ?p ?v\n" + + " }\n" + + " } ;\n\n" + + "WITH \n" + + "DELETE\n" + + " { ?book ?p ?v }\n" + + "WHERE\n" + + " { ?book dc:date ?date ;\n" + + " dc:type dcmitype:PhysicalObject .\n" + + " FILTER ( ?date < \"2000-01-01T00:00:00-02:00\"^^xsd:dateTime ) \n" + + " ?book ?p ?v\n" + + " }"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + + Set expected = new HashSet<>(); + expected.add(new IRI("http://example/bookStore2")); + expected.add(new IRI("http://example/bookStore")); + assertTrue(referredGraphs.containsAll(expected)); + } + + @Test + public void testExistsFunction() throws ParseException { + String queryStr = "PREFIX rdf: \n" + + "PREFIX foaf: \n\n" + + "SELECT ?person\n" + + "WHERE \n" + + "{\n" + + " ?person rdf:type foaf:Person .\n" + + " FILTER EXISTS { ?person foaf:name ?name }\n" + + "}"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } + + @Test + public void testNotExistsFunction() throws ParseException { + String queryStr = "PREFIX rdf: \n" + + "PREFIX foaf: \n\n" + + "SELECT ?person\n" + + "WHERE \n" + + "{\n" + + " ?person rdf:type foaf:Person .\n" + + " FILTER NOT EXISTS { ?person foaf:name ?name }\n" + + "}"; + + SparqlPreParser parser; + parser = new SparqlPreParser(TcManager.getInstance()); + Set referredGraphs = parser.getReferredGraphs(queryStr, DEFAULT_GRAPH); + assertTrue(referredGraphs.toArray()[0].equals(DEFAULT_GRAPH)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java new file mode 100644 index 0000000000..291b513b85 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/AccessViaTcManager.java @@ -0,0 +1,42 @@ +/* + * Copyright 2015 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.clerezza.rdf.simple.storage; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.clerezza.rdf.core.access.TcManager; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author developer + */ +@RunWith(JUnitPlatform.class) +public class AccessViaTcManager { + + @Test + public void simple() { + Graph g = TcManager.getInstance().createGraph(new IRI("http://example.org/foo")); + assertTrue(g instanceof SimpleGraph); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java new file mode 100644 index 0000000000..04052bae18 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/simple.storage/src/test/java/org/apache/clerezza/rdf/simple/storage/GenericTcProviderTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.simple.storage; + +import org.apache.clerezza.rdf.core.access.TcProvider; +import org.apache.clerezza.rdf.core.test.TcProviderTest; + +import org.junit.jupiter.api.AfterEach; + +/** + * + * @author mir + */ +public class GenericTcProviderTest extends TcProviderTest { + + SimpleTcProvider provider = new SimpleTcProvider(); + + @AfterEach + public void cleanUp() { + provider = new SimpleTcProvider(); + } + + @Override + protected TcProvider getInstance() { + return provider; + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java new file mode 100644 index 0000000000..557f46fa57 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/GraphUtilsTest.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.utils.GraphUtils.NoSuchSubGraphException; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class GraphUtilsTest { + + final IRI u1 = new IRI("http://ex.org/1"); + final IRI u2 = new IRI("http://ex.org/2"); + final IRI u3 = new IRI("http://ex.org/3"); + + @Test + public void removeSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode1)); + } + GraphUtils.removeSubGraph(baseGraph, subGraph); + assertEquals(1, baseGraph.size()); + } + + private Graph createBaseGraph() { + Graph baseGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + baseGraph.add(new TripleImpl(u1, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); + baseGraph.add(new TripleImpl(u3, u2, u1)); + } + return baseGraph; + } + + /** It is required that the subgraph comprises the whole context of the Bnodes it ioncludes + * + * @throws org.apache.clerezza.rdf.utils.GraphUtils.NoSuchSubGraphException + */ + @Test + public void removeIncompleteSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + } + assertThrows(NoSuchSubGraphException.class, () -> + GraphUtils.removeSubGraph(baseGraph, subGraph)); + } + + @Test + public void removeInvalidSubGraph() throws NoSuchSubGraphException { + Graph baseGraph = createBaseGraph(); + + Graph subGraph = new SimpleGraph(); + { + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + subGraph.add(new TripleImpl(u1, u2, bNode2)); + subGraph.add(new TripleImpl(bNode2, u2, bNode2)); + baseGraph.add(new TripleImpl(bNode2, u2, bNode1)); + baseGraph.add(new TripleImpl(bNode2, u2, new BlankNode())); + } + assertThrows(NoSuchSubGraphException.class, () -> + GraphUtils.removeSubGraph(baseGraph, subGraph)); + } +} + diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java new file mode 100644 index 0000000000..2071eef19b --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/IfpSmushTest.java @@ -0,0 +1,120 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class IfpSmushTest { + + private Graph ontology = new SimpleGraph(); + { + ontology.add(new TripleImpl(FOAF.mbox, RDF.type, OWL.InverseFunctionalProperty)); + } + + @Test + public void simpleBlankNode() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final BlankNode bNode1 = new BlankNode(); + mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + assertEquals(3, mGraph.size()); + } + + @Test + public void overlappingEquivalenceClasses() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final BlankNode bNode1 = new BlankNode(); + mGraph.add(new TripleImpl(bNode1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + IRI mbox2 = new IRI("mailto:bar@example.org"); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox2)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + final BlankNode bNode3 = new BlankNode(); + mGraph.add(new TripleImpl(bNode3, FOAF.mbox, mbox2)); + mGraph.add(new TripleImpl(bNode3, RDFS.comment, + new PlainLiteralImpl("yet another comment"))); + Smusher.smush(mGraph, ontology); + assertEquals(5, mGraph.size()); + } + + @Test + public void oneIRI() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final IRI resource = new IRI("http://example.org/"); + mGraph.add(new TripleImpl(resource, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final BlankNode bNode2 = new BlankNode(); + mGraph.add(new TripleImpl(bNode2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(bNode2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + assertEquals(3, mGraph.size()); + } + + @Test + public void twoIRIs() { + Graph mGraph = new SimpleGraph(); + IRI mbox1 = new IRI("mailto:foo@example.org"); + final IRI resource1 = new IRI("http://example.org/"); + mGraph.add(new TripleImpl(resource1, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource1, RDFS.comment, + new PlainLiteralImpl("a comment"))); + final IRI resource2 = new IRI("http://2.example.org/"); + mGraph.add(new TripleImpl(resource2, FOAF.mbox, mbox1)); + mGraph.add(new TripleImpl(resource2, RDFS.comment, + new PlainLiteralImpl("another comment"))); + Smusher.smush(mGraph, ontology); + assertEquals(4, mGraph.size()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java new file mode 100644 index 0000000000..fe7ce1a079 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/RdfListTest.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author rbn + */ +@RunWith(JUnitPlatform.class) +public class RdfListTest { + + @Test + public void listCreationAndAccess() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + assertEquals(new PlainLiteralImpl("hello"), list.get(0)); + assertEquals(new PlainLiteralImpl("world"), list.get(1)); + assertEquals(2, list.size()); + list.add(new PlainLiteralImpl("welcome")); + assertEquals(3, list.size()); + assertEquals(new PlainLiteralImpl("welcome"), list.get(2)); + list.add(1, new PlainLiteralImpl("interesting")); + assertEquals(4, list.size()); + assertEquals(new PlainLiteralImpl("interesting"), list.get(1)); + assertEquals(new PlainLiteralImpl("world"), list.get(2)); + assertEquals(new PlainLiteralImpl("welcome"), list.get(3)); + list.add(0, new PlainLiteralImpl("start")); + assertEquals(5, list.size()); + assertEquals(new PlainLiteralImpl("hello"), list.get(1)); + assertEquals(new PlainLiteralImpl("interesting"), list.get(2)); + List list2 = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(5, list2.size()); + assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); + assertEquals(new PlainLiteralImpl("interesting"), list2.get(2)); + list2.remove(2); + assertEquals(4, list2.size()); + assertEquals(new PlainLiteralImpl("hello"), list2.get(1)); + assertEquals(new PlainLiteralImpl("world"), list2.get(2)); + while (list2.size() > 0) { + list2.remove(0); + } + assertEquals(1, tc.size()); //list = rdf:nil statement + list2.add(0, new PlainLiteralImpl("restart")); + list2.add(1, new PlainLiteralImpl("over")); + assertEquals(2, list2.size()); + list2.add(new PlainLiteralImpl("2")); + list2.add(new PlainLiteralImpl("3")); + assertEquals(4, list2.size()); + list2.add(new PlainLiteralImpl("4")); + list2.add(new PlainLiteralImpl("5")); + assertEquals(new PlainLiteralImpl("3"), list2.get(3)); + } + + @Test + public void listCreationAndAccess2() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + list.add(0,new PlainLiteralImpl("world")); + list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(0,new PlainLiteralImpl("beautifuly")); + list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(0,new PlainLiteralImpl("hello")); + assertEquals(new PlainLiteralImpl("hello"), list.get(0)); + assertEquals(new PlainLiteralImpl("beautifuly"), list.get(1)); + assertEquals(new PlainLiteralImpl("world"), list.get(2)); + } + + @Test + public void listCreationAndAccess3() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + assertEquals(0, list.size()); + BlankNode node0 = new BlankNode() {}; + BlankNode node1 = new BlankNode() {}; + BlankNode node2 = new BlankNode() {}; + list.add(0,node2); + list.add(0,node1); + list.add(0,node0); + assertEquals(node0, list.get(0)); + assertEquals(node1, list.get(1)); + assertEquals(node2, list.get(2)); + } + + @Test + public void secondButLastElementAccessTest() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest2"), tc); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + list.remove(1); + assertEquals(1, list.size()); + } + + @Test + public void cleanGraphAfterRemoval() { + Graph tc = new SimpleGraph(); + List list = new RdfList(new IRI("http://example.org/mytest"), tc); + list.add(new PlainLiteralImpl("hello")); + list.add(new PlainLiteralImpl("world")); + list.remove(1); + assertEquals(2, tc.size()); + + } + + @Test + public void findContainingListNodesAndfindContainingListsTest() { + Graph tc = new SimpleGraph(); + GraphNode listA = new GraphNode(new IRI("http:///listA"), tc); + GraphNode listB = new GraphNode(new IRI("http:///listB"), tc); + BlankNode element1 = new BlankNode(); + BlankNode element2 = new BlankNode(); + BlankNode element3 = new BlankNode(); + BlankNode element4 = new BlankNode(); + BlankNode element5 = new BlankNode(); + + RdfList rdfListA = new RdfList(listA); + rdfListA.add(element1); + rdfListA.add(element2); + rdfListA.add(element3); + rdfListA.add(element4); + + RdfList rdfListB = new RdfList(listB); + rdfListB.add(element2); + rdfListB.add(element4); + rdfListB.add(element5); + + Set containingListNodes = RdfList.findContainingListNodes( + new GraphNode(element3, tc)); + assertEquals(1, containingListNodes.size()); + assertTrue(containingListNodes.contains(listA)); + + Set containingLists = RdfList.findContainingLists( + new GraphNode(element3, tc)); + assertEquals(1, containingLists.size()); + assertTrue(containingLists.contains(rdfListA)); + + containingListNodes = RdfList.findContainingListNodes( + new GraphNode(element4, tc)); + assertEquals(2, containingListNodes.size()); + assertTrue(containingListNodes.contains(listA)); + assertTrue(containingListNodes.contains(listB)); + + containingLists = RdfList.findContainingLists( + new GraphNode(element4, tc)); + assertEquals(2, containingLists.size()); + assertTrue(containingLists.contains(rdfListA)); + assertTrue(containingLists.contains(rdfListB)); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java new file mode 100644 index 0000000000..25fdbcd22b --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/SameAsSmushTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Iterator; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class SameAsSmushTest { + + private final IRI uriA = new IRI("http://example.org/A"); + private final IRI uriB = new IRI("http://example.org/B"); + private final Literal lit = new PlainLiteralImpl("That's me (and you)"); + + private Graph sameAsStatements = new SimpleGraph(); + { + sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); + } + + private Graph dataGraph = new SimpleGraph(); + { + dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); + dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); + dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); + } + + @Test + public void simple() { + assertEquals(3, dataGraph.size()); + Smusher.sameAsSmush(dataGraph, sameAsStatements); + assertEquals(3, dataGraph.size()); + assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); + //exactly one statement with literal + Iterator litStmts = dataGraph.filter(null, null, lit); + assertTrue(litStmts.hasNext()); + Triple litStmt = litStmts.next(); + assertFalse(litStmts.hasNext()); + Iterator knowsStmts = dataGraph.filter(null, FOAF.knows, null); + assertTrue(knowsStmts.hasNext()); + Triple knowStmt = knowsStmts.next(); + assertEquals(knowStmt.getSubject(), knowStmt.getObject()); + assertEquals(litStmt.getSubject(), knowStmt.getObject()); + assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java new file mode 100644 index 0000000000..7387eae1a1 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/TestGraphNode.java @@ -0,0 +1,278 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.RDFTerm; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.core.test.RandomGraph; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto, mir + */ +@RunWith(JUnitPlatform.class) +public class TestGraphNode { + + @Test + public void nodeContext() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(bNode2, property2, bNode1)); + g.add(new TripleImpl(property1, property1, bNode2)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + assertEquals(4, n.getNodeContext().size()); + n.deleteNodeContext(); + assertEquals(1, g.size()); + assertFalse(n.getObjects(property2).hasNext()); + } + + @Test + public void addNode() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + assertEquals(1, g.size()); + } + + @Test + public void testGetSubjectAndObjectNodes() { + RandomGraph graph = new RandomGraph(500, 20, new SimpleGraph()); + for (int j = 0; j < 200; j++) { + Triple randomTriple = graph.getRandomTriple(); + GraphNode node = new GraphNode(randomTriple.getSubject(), graph); + Iterator properties = node.getProperties(); + while (properties.hasNext()) { + IRI property = properties.next(); + Set objects = createSet(node.getObjects(property)); + Iterator objectNodes = node.getObjectNodes(property); + while (objectNodes.hasNext()) { + GraphNode graphNode = objectNodes.next(); + assertTrue(objects.contains(graphNode.getNode())); + } + } + } + + for (int j = 0; j < 200; j++) { + Triple randomTriple = graph.getRandomTriple(); + GraphNode node = new GraphNode(randomTriple.getObject(), graph); + Iterator properties = node.getProperties(); + while (properties.hasNext()) { + IRI property = properties.next(); + Set subjects = createSet(node.getSubjects(property)); + Iterator subjectNodes = node.getSubjectNodes(property); + while (subjectNodes.hasNext()) { + GraphNode graphNode = subjectNodes.next(); + assertTrue(subjects.contains(graphNode.getNode())); + } + } + } + } + + @Test + public void getAvailableProperties(){ + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + IRI property3 = new IRI("http://example.org/property3"); + IRI property4 = new IRI("http://example.org/property4"); + ArrayList props = new ArrayList(); + props.add(property1); + props.add(property2); + props.add(property3); + props.add(property4); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + n.addProperty(property2, bNode2); + n.addProperty(property3, bNode2); + n.addProperty(property4, bNode2); + Iterator properties = n.getProperties(); + int i = 0; + while(properties.hasNext()){ + i++; + IRI prop = properties.next(); + assertTrue(props.contains(prop)); + props.remove(prop); + } + assertEquals(i, 4); + assertEquals(props.size(), 0); + + } + + @Test + public void deleteAll() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + //the two properties two be deleted + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); + //this 3 properties should stay + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + n.deleteProperties(property1); + assertEquals(3, g.size()); + } + + @Test + public void deleteSingleProperty() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + //the properties two be deleted + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("literal"))); + //this 4 properties should stay + g.add(new TripleImpl(bNode1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode1, property2, property1)); + g.add(new TripleImpl(property1, property1, new PlainLiteralImpl("bla bla"))); + g.add(new TripleImpl(bNode2, property1, new PlainLiteralImpl("bla bla"))); + GraphNode n = new GraphNode(bNode1, g); + n.deleteProperty(property1, new PlainLiteralImpl("literal")); + assertEquals(4, g.size()); + } + + @Test + public void replaceWith() { + Graph initialGraph = new SimpleGraph(); + BlankNode bNode1 = new BlankNode(); + BlankNode bNode2 = new BlankNode(); + BlankNode newBnode = new BlankNode(); + IRI property1 = new IRI("http://example.org/property1"); + IRI property2 = new IRI("http://example.org/property2"); + IRI newIRI = new IRI("http://example.org/newName"); + Literal literal1 = new PlainLiteralImpl("literal"); + Literal literal2 = new PlainLiteralImpl("bla bla"); + + Triple triple1 = new TripleImpl(bNode1, property1, literal1); + Triple triple2 = new TripleImpl(bNode1, property2, property1); + Triple triple3 = new TripleImpl(bNode2, property2, bNode1); + Triple triple4 = new TripleImpl(property1, property1, bNode2); + Triple triple5 = new TripleImpl(property1, property1, literal2); + initialGraph.add(triple1); + initialGraph.add(triple2); + initialGraph.add(triple3); + initialGraph.add(triple4); + initialGraph.add(triple5); + GraphNode node = new GraphNode(property1, + new SimpleGraph(initialGraph.iterator())); + + node.replaceWith(newIRI, true); + assertEquals(5, node.getGraph().size()); + Triple expectedTriple1 = new TripleImpl(bNode1, newIRI, literal1); + Triple expectedTriple2 = new TripleImpl(bNode1, property2, newIRI); + Triple expectedTriple3 = new TripleImpl(newIRI, newIRI, bNode2); + Triple expectedTriple4 = new TripleImpl(newIRI, newIRI, literal2); + + assertTrue(node.getGraph().contains(expectedTriple1)); + assertTrue(node.getGraph().contains(expectedTriple2)); + assertTrue(node.getGraph().contains(expectedTriple3)); + assertTrue(node.getGraph().contains(expectedTriple4)); + + assertFalse(node.getGraph().contains(triple1)); + assertFalse(node.getGraph().contains(triple2)); + assertFalse(node.getGraph().contains(triple4)); + assertFalse(node.getGraph().contains(triple5)); + + node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newBnode); + Triple expectedTriple5 = new TripleImpl(bNode1, property2, newBnode); + Triple expectedTriple6 = new TripleImpl(newBnode, property1, bNode2); + Triple expectedTriple7 = new TripleImpl(newBnode, property1, literal2); + + assertTrue(node.getGraph().contains(triple1)); + assertTrue(node.getGraph().contains(expectedTriple5)); + assertTrue(node.getGraph().contains(expectedTriple6)); + assertTrue(node.getGraph().contains(expectedTriple7)); + + node = new GraphNode(literal1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newBnode); + Triple expectedTriple8 = new TripleImpl(bNode1, property1, newBnode); + assertTrue(node.getGraph().contains(expectedTriple8)); + + node = new GraphNode(property1, new SimpleGraph(initialGraph.iterator())); + node.replaceWith(newIRI); + Triple expectedTriple9 = new TripleImpl(bNode1, property2, newIRI); + Triple expectedTriple10 = new TripleImpl(newIRI, property1, bNode2); + Triple expectedTriple11 = new TripleImpl(newIRI, property1, literal2); + assertTrue(node.getGraph().contains(triple1)); + assertTrue(node.getGraph().contains(expectedTriple9)); + assertTrue(node.getGraph().contains(expectedTriple10)); + assertTrue(node.getGraph().contains(expectedTriple11)); + } + + @Test + public void equality() { + Graph g = new SimpleGraph(); + BlankNode bNode1 = new BlankNode() {}; + BlankNode bNode2 = new BlankNode() {}; + IRI property1 = new IRI("http://example.org/property1"); + GraphNode n = new GraphNode(bNode1, g); + n.addProperty(property1, bNode2); + assertTrue(n.equals(new GraphNode(bNode1, g))); + assertFalse(n.equals(new GraphNode(bNode2, g))); + GraphNode n2 = null; + assertFalse(n.equals(n2)); + } + + private Set createSet(Iterator resources) { + Set set = new HashSet(); + while (resources.hasNext()) { + RDFTerm resource = resources.next(); + set.add(resource); + } + return set; + } + +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java new file mode 100644 index 0000000000..17b0eb0fd0 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/UnionGraphTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Iterator; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author hasan + */ +@RunWith(JUnitPlatform.class) +public class UnionGraphTest { + + private final IRI uriRef1 = + new IRI("http://example.org/ontology#res1"); + private final IRI uriRef2 = + new IRI("http://example.org/ontology#res2"); + private final IRI uriRef3 = + new IRI("http://example.org/ontology#res3"); + private final IRI uriRef4 = + new IRI("http://example.org/ontology#res4"); + + @Test + public void readAccess() { + Graph graph = new SimpleGraph(); + Graph graph2 = new SimpleGraph(); + BlankNode bnode = new BlankNode() { + }; + graph.add(new TripleImpl(uriRef1, uriRef2, uriRef1)); + graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); + Graph unionGraph = new UnionGraph(graph, graph2); + Iterator unionTriples = unionGraph.iterator(); + assertTrue(unionTriples.hasNext()); + unionTriples.next(); + assertTrue(unionTriples.hasNext()); + unionTriples.next(); + assertFalse(unionTriples.hasNext()); + assertEquals(2, unionGraph.size()); + } + + @Test + public void writeAccess() { + Graph graph = new SimpleGraph(); + Graph graph2 = new SimpleGraph(); + BlankNode bnode = new BlankNode() { + }; + graph2.add(new TripleImpl(bnode, uriRef1, uriRef3)); + Graph unionGraph = new UnionGraph(graph, graph2); + assertEquals(1, unionGraph.size()); + unionGraph.add(new TripleImpl(uriRef4, uriRef1, uriRef3)); + assertEquals(1, graph.size()); + assertEquals(2, unionGraph.size()); + assertEquals(1, graph2.size()); + } +} diff --git a/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java new file mode 100644 index 0000000000..ad58987046 --- /dev/null +++ b/src/test/resources/oracle/commits/clerezza-d77dbe2085ffa89b2a933637c5432d113b7432b8/rdf/utils/src/test/java/org/apache/clerezza/rdf/utils/smushing/SameAsSmushTest.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.clerezza.rdf.utils.smushing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Iterator; +import java.util.Set; + +import org.apache.clerezza.commons.rdf.BlankNode; +import org.apache.clerezza.commons.rdf.Literal; +import org.apache.clerezza.commons.rdf.Graph; +import org.apache.clerezza.commons.rdf.Triple; +import org.apache.clerezza.commons.rdf.IRI; +import org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl; +import org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph; +import org.apache.clerezza.commons.rdf.impl.utils.TripleImpl; +import org.apache.clerezza.rdf.ontologies.FOAF; +import org.apache.clerezza.rdf.ontologies.OWL; +import org.apache.clerezza.rdf.ontologies.RDF; +import org.apache.clerezza.rdf.ontologies.RDFS; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +/** + * + * @author reto + */ +@RunWith(JUnitPlatform.class) +public class SameAsSmushTest { + + private final IRI uriA = new IRI("http://example.org/A"); + private final IRI uriB = new IRI("http://example.org/B"); + private final IRI uriC = new IRI("http://example.org/C"); + + private final Literal lit = new PlainLiteralImpl("That's me (and you)"); + + private Graph sameAsStatements = new SimpleGraph(); + { + sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB)); + } + + private Graph dataGraph = new SimpleGraph(); + { + dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB)); + dataGraph.add(new TripleImpl(uriB, RDFS.label, lit)); + dataGraph.add(new TripleImpl(uriA, RDFS.label, lit)); + } + + @Test + public void simple() { + SameAsSmusher smusher = new SameAsSmusher() { + + @Override + protected IRI getPreferedIRI(Set uriRefs) { + if (!uriRefs.contains(uriA)) throw new RuntimeException("not the set we excpect"); + if (!uriRefs.contains(uriB)) throw new RuntimeException("not the set we excpect"); + return uriC; + } + + }; + assertEquals(3, dataGraph.size()); + smusher.smush(dataGraph, sameAsStatements, true); + assertEquals(4, dataGraph.size()); + assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext()); + //exactly one statement with literal + Iterator litStmts = dataGraph.filter(null, null, lit); + assertTrue(litStmts.hasNext()); + Triple litStmt = litStmts.next(); + assertFalse(litStmts.hasNext()); + Iterator knowsStmts = dataGraph.filter(null, FOAF.knows, null); + assertTrue(knowsStmts.hasNext()); + Triple knowStmt = knowsStmts.next(); + assertEquals(knowStmt.getSubject(), knowStmt.getObject()); + assertEquals(litStmt.getSubject(), knowStmt.getObject()); + assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject()); + assertEquals(knowStmt.getSubject(), uriC); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/AssertionsTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/AssertionsTest.java new file mode 100644 index 0000000000..af41275d99 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/AssertionsTest.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import org.junit.Test; + +/** + */ +public class AssertionsTest { + + @Test + public void testNotNull() throws Exception { + Assertions.notNull(new Object(), "object"); + } + + @Test(expected = IllegalArgumentException.class) + public void testNotNullNull() throws Exception { + Assertions.notNull(null, "object"); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFileParserTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFileParserTest.java new file mode 100644 index 0000000000..92ede5bb21 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFileParserTest.java @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FilenameFilter; +import java.io.IOException; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * Parse tests using test files + */ +@RunWith(Parameterized.class) +public class CSVFileParserTest { + + private static final File BASE = new File("src/test/resources/CSVFileParser"); + + private final BufferedReader testData; + + private final String testName; + + public CSVFileParserTest(final File file) throws FileNotFoundException { + this.testName = file.getName(); + this.testData = new BufferedReader(new FileReader(file)); + } + + private String readTestData() throws IOException { + String line; + do { + line = testData.readLine(); + } while (line != null && line.startsWith("#")); + return line; + } + + @Parameters + public static Collection generateData() { + final List list = new ArrayList<>(); + + final FilenameFilter fileNameFilter = (dir, name) -> name.startsWith("test") && name.endsWith(".txt"); + final File[] files = BASE.listFiles(fileNameFilter); + if (files != null) { + for (final File f : files) { + list.add(new Object[] { f }); + } + } + return list; + } + + @Test + public void testCSVFile() throws Exception { + String line = readTestData(); + assertNotNull("file must contain config line", line); + final String[] split = line.split(" "); + assertTrue(testName + " require 1 param", split.length >= 1); + // first line starts with csv data file name + CSVFormat format = CSVFormat.newFormat(',').withQuote('"'); + boolean checkComments = false; + for (int i = 1; i < split.length; i++) { + final String option = split[i]; + final String[] option_parts = option.split("=", 2); + if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); + } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); + } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { + format = format.withCommentMarker(option_parts[1].charAt(0)); + } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { + checkComments = true; + } else { + fail(testName + " unexpected option: " + option); + } + } + line = readTestData(); // get string version of format + assertEquals(testName + " Expected format ", line, format.toString()); + + // Now parse the file and compare against the expected results + // We use a buffered reader internally so no need to create one here. + try (final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), Charset.defaultCharset(), format)) { + for (final CSVRecord record : parser) { + String parsed = Arrays.toString(record.values()); + if (checkComments) { + final String comment = record.getComment().replace("\n", "\\n"); + if (comment != null) { + parsed += "#" + comment; + } + } + final int count = record.size(); + assertEquals(testName, readTestData(), count + ":" + parsed); + } + } + } + + @Test + public void testCSVUrl() throws Exception { + String line = readTestData(); + assertNotNull("file must contain config line", line); + final String[] split = line.split(" "); + assertTrue(testName + " require 1 param", split.length >= 1); + // first line starts with csv data file name + CSVFormat format = CSVFormat.newFormat(',').withQuote('"'); + boolean checkComments = false; + for (int i = 1; i < split.length; i++) { + final String option = split[i]; + final String[] option_parts = option.split("=", 2); + if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); + } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); + } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { + format = format.withCommentMarker(option_parts[1].charAt(0)); + } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { + checkComments = true; + } else { + fail(testName + " unexpected option: " + option); + } + } + line = readTestData(); // get string version of format + assertEquals(testName + " Expected format ", line, format.toString()); + + // Now parse the file and compare against the expected results + final URL resource = ClassLoader.getSystemResource("CSVFileParser/" + split[0]); + try (final CSVParser parser = CSVParser.parse(resource, Charset.forName("UTF-8"), format)) { + for (final CSVRecord record : parser) { + String parsed = Arrays.toString(record.values()); + if (checkComments) { + final String comment = record.getComment().replace("\n", "\\n"); + if (comment != null) { + parsed += "#" + comment; + } + } + final int count = record.size(); + assertEquals(testName, readTestData(), count + ":" + parsed); + } + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java new file mode 100644 index 0000000000..bf19cf4fb7 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests {@link CSVFormat.Predefined}. + */ +public class CSVFormatPredefinedTest { + + private void test(final CSVFormat format, final String enumName) { + Assert.assertEquals(format, CSVFormat.Predefined.valueOf(enumName).getFormat()); + Assert.assertEquals(format, CSVFormat.valueOf(enumName)); + } + + @Test + public void testDefault() { + test(CSVFormat.DEFAULT, "Default"); + } + + @Test + public void testExcel() { + test(CSVFormat.EXCEL, "Excel"); + } + + @Test + public void testMySQL() { + test(CSVFormat.MYSQL, "MySQL"); + } + + @Test + public void testOracle() { + test(CSVFormat.ORACLE, "Oracle"); + } + + @Test + public void testPostgreSqlCsv() { + test(CSVFormat.POSTGRESQL_CSV, "PostgreSQLCsv"); + } + + @Test + public void testMongoDbCsv() { + test(CSVFormat.MONGODB_CSV, "MongoDBCsv"); + } + + @Test + public void testMongoDbTsv() { + test(CSVFormat.MONGODB_TSV, "MongoDBTsv"); + } + + @Test + public void testPostgreSqlText() { + test(CSVFormat.POSTGRESQL_TEXT, "PostgreSQLText"); + } + + @Test + public void testRFC4180() { + test(CSVFormat.RFC4180, "RFC4180"); + } + + @Test + public void testTDF() { + test(CSVFormat.TDF, "TDF"); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatTest.java new file mode 100644 index 0000000000..865572ee87 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVFormatTest.java @@ -0,0 +1,1176 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static junit.framework.TestCase.assertNull; +import static org.apache.commons.csv.CSVFormat.RFC4180; +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests {@link CSVFormat}. + */ +public class CSVFormatTest { + + public enum EmptyEnum { + // empty enum. + } + + public enum Header { + Name, Email, Phone + } + + private static void assertNotEquals(final Object right, final Object left) { + assertFalse(right.equals(left)); + assertFalse(left.equals(right)); + } + + private static CSVFormat copy(final CSVFormat format) { + return format.withDelimiter(format.getDelimiter()); + } + + private void assertNotEquals(String name, String type, Object left, Object right) { + if (left.equals(right) || right.equals(left)) { + fail("Objects must not compare equal for " + name + "(" + type + ")"); + } + if (left.hashCode() == right.hashCode()) { + fail("Hash code should not be equal for " + name + "(" + type + ")"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testDelimiterSameAsCommentStartThrowsException() { + CSVFormat.DEFAULT.withDelimiter('!').withCommentMarker('!'); + } + + @Test(expected = IllegalArgumentException.class) + public void testDelimiterSameAsEscapeThrowsException() { + CSVFormat.DEFAULT.withDelimiter('!').withEscape('!'); + } + + @Test + public void testDuplicateHeaderElements() { + final String[] header = { "A", "A" }; + final CSVFormat format = CSVFormat.DEFAULT.withHeader(header); + assertEquals(2, format.getHeader().length); + assertArrayEquals(header, format.getHeader()); + } + + @Test(expected = IllegalArgumentException.class) + public void testDuplicateHeaderElementsFalse() { + CSVFormat.DEFAULT.withAllowDuplicateHeaderNames(false).withHeader("A", "A"); + } + + public void testDuplicateHeaderElementsTrue() { + CSVFormat.DEFAULT.withAllowDuplicateHeaderNames(true).withHeader("A", "A"); + } + + @Test + public void testEquals() { + final CSVFormat right = CSVFormat.DEFAULT; + final CSVFormat left = copy(right); + + assertFalse(right.equals(null)); + assertFalse(right.equals("A String Instance")); + + assertEquals(right, right); + assertEquals(right, left); + assertEquals(left, right); + + assertEquals(right.hashCode(), right.hashCode()); + assertEquals(right.hashCode(), left.hashCode()); + } + + @Test + public void testEqualsCommentStart() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withCommentMarker('#') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withCommentMarker('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsDelimiter() { + final CSVFormat right = CSVFormat.newFormat('!'); + final CSVFormat left = CSVFormat.newFormat('?'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsEscape() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withCommentMarker('#') + .withEscape('+') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withEscape('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsHash() throws Exception { + Method[] methods = CSVFormat.class.getDeclaredMethods(); + for (Method method : methods) { + if (Modifier.isPublic(method.getModifiers())) { + final String name = method.getName(); + if (name.startsWith("with")) { + for (Class cls : method.getParameterTypes()) { + final String type = cls.getCanonicalName(); + if ("boolean".equals(type)) { + final Object defTrue = method.invoke(CSVFormat.DEFAULT, new Object[] {Boolean.TRUE}); + final Object defFalse = method.invoke(CSVFormat.DEFAULT, new Object[] {Boolean.FALSE}); + assertNotEquals(name, type ,defTrue, defFalse); + } else if ("char".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {'a'}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {'b'}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.Character".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {null}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new Character('d')}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.String".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {null}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {"e"}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.String[]".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {new String[] {null, null}}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new String[] {"f", "g"}}); + assertNotEquals(name, type, a, b); + } else if ("org.apache.commons.csv.QuoteMode".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {QuoteMode.MINIMAL}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {QuoteMode.ALL}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.Object[]".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {new Object[] {null, null}}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new Object[] {new Object(), new Object()}}); + assertNotEquals(name, type, a, b); + } else if ("withHeader".equals(name)){ // covered above by String[] + // ignored + } else { + fail("Unhandled method: "+name + "(" + type + ")"); + } + } + } + } + } + } + + @Test + public void testEqualsHeader() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withHeader("One", "Two", "Three") + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withHeader("Three", "Two", "One"); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsIgnoreEmptyLines() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withIgnoreEmptyLines(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsIgnoreSurroundingSpaces() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withCommentMarker('#') + .withEscape('+') + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withIgnoreSurroundingSpaces(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsLeftNoQuoteRightQuote() { + final CSVFormat left = CSVFormat.newFormat(',').withQuote(null); + final CSVFormat right = left.withQuote('#'); + + assertNotEquals(left, right); + } + + @Test + public void testEqualsNoQuotes() { + final CSVFormat left = CSVFormat.newFormat(',').withQuote(null); + final CSVFormat right = left.withQuote(null); + + assertEquals(left, right); + } + + @Test + public void testEqualsNullString() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL) + .withNullString("null"); + final CSVFormat left = right + .withNullString("---"); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsOne() { + + final CSVFormat csvFormatOne = CSVFormat.INFORMIX_UNLOAD; + final CSVFormat csvFormatTwo = CSVFormat.MYSQL; + + + assertEquals('\\', (char)csvFormatOne.getEscapeCharacter()); + assertNull(csvFormatOne.getQuoteMode()); + + assertTrue(csvFormatOne.getIgnoreEmptyLines()); + assertFalse(csvFormatOne.getSkipHeaderRecord()); + + assertFalse(csvFormatOne.getIgnoreHeaderCase()); + assertNull(csvFormatOne.getCommentMarker()); + + assertFalse(csvFormatOne.isCommentMarkerSet()); + assertTrue(csvFormatOne.isQuoteCharacterSet()); + + assertEquals('|', csvFormatOne.getDelimiter()); + assertFalse(csvFormatOne.getAllowMissingColumnNames()); + + assertTrue(csvFormatOne.isEscapeCharacterSet()); + assertEquals("\n", csvFormatOne.getRecordSeparator()); + + assertEquals('\"', (char)csvFormatOne.getQuoteCharacter()); + assertFalse(csvFormatOne.getTrailingDelimiter()); + + assertFalse(csvFormatOne.getTrim()); + assertFalse(csvFormatOne.isNullStringSet()); + + assertNull(csvFormatOne.getNullString()); + assertFalse(csvFormatOne.getIgnoreSurroundingSpaces()); + + + assertTrue(csvFormatTwo.isEscapeCharacterSet()); + assertNull(csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormatTwo.getQuoteMode()); + + assertEquals('\t', csvFormatTwo.getDelimiter()); + assertEquals("\n", csvFormatTwo.getRecordSeparator()); + + assertFalse(csvFormatTwo.isQuoteCharacterSet()); + assertTrue(csvFormatTwo.isNullStringSet()); + + assertEquals('\\', (char)csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertFalse(csvFormatTwo.getIgnoreEmptyLines()); + + assertEquals("\\N", csvFormatTwo.getNullString()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormatTwo.getTrailingDelimiter()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormatTwo, csvFormatOne); + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + assertEquals('\\', (char)csvFormatOne.getEscapeCharacter()); + assertNull(csvFormatOne.getQuoteMode()); + + assertTrue(csvFormatOne.getIgnoreEmptyLines()); + assertFalse(csvFormatOne.getSkipHeaderRecord()); + + assertFalse(csvFormatOne.getIgnoreHeaderCase()); + assertNull(csvFormatOne.getCommentMarker()); + + assertFalse(csvFormatOne.isCommentMarkerSet()); + assertTrue(csvFormatOne.isQuoteCharacterSet()); + + assertEquals('|', csvFormatOne.getDelimiter()); + assertFalse(csvFormatOne.getAllowMissingColumnNames()); + + assertTrue(csvFormatOne.isEscapeCharacterSet()); + assertEquals("\n", csvFormatOne.getRecordSeparator()); + + assertEquals('\"', (char)csvFormatOne.getQuoteCharacter()); + assertFalse(csvFormatOne.getTrailingDelimiter()); + + assertFalse(csvFormatOne.getTrim()); + assertFalse(csvFormatOne.isNullStringSet()); + + assertNull(csvFormatOne.getNullString()); + assertFalse(csvFormatOne.getIgnoreSurroundingSpaces()); + + assertTrue(csvFormatTwo.isEscapeCharacterSet()); + assertNull(csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormatTwo.getQuoteMode()); + + assertEquals('\t', csvFormatTwo.getDelimiter()); + assertEquals("\n", csvFormatTwo.getRecordSeparator()); + + assertFalse(csvFormatTwo.isQuoteCharacterSet()); + assertTrue(csvFormatTwo.isNullStringSet()); + + assertEquals('\\', (char)csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertFalse(csvFormatTwo.getIgnoreEmptyLines()); + + assertEquals("\\N", csvFormatTwo.getNullString()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormatTwo.getTrailingDelimiter()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormatOne, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormatOne); + + assertFalse(csvFormatOne.equals(csvFormatTwo)); + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + } + + @Test + public void testEqualsQuoteChar() { + final CSVFormat right = CSVFormat.newFormat('\'').withQuote('"'); + final CSVFormat left = right.withQuote('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsQuotePolicy() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withQuoteMode(QuoteMode.MINIMAL); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsRecordSeparator() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withRecordSeparator(LF); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsSkipHeaderRecord() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL) + .withNullString("null") + .withSkipHeaderRecord(); + final CSVFormat left = right + .withSkipHeaderRecord(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsWithNull() { + + final CSVFormat csvFormat = CSVFormat.POSTGRESQL_TEXT; + + assertEquals('\\', (char)csvFormat.getEscapeCharacter()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertFalse(csvFormat.getTrim()); + + assertTrue(csvFormat.isQuoteCharacterSet()); + assertEquals("\\N", csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormat.isEscapeCharacterSet()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormat.getQuoteMode()); + + assertEquals('\t', csvFormat.getDelimiter()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertEquals("\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertTrue(csvFormat.isNullStringSet()); + + assertEquals('\\', (char)csvFormat.getEscapeCharacter()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertFalse(csvFormat.getTrim()); + + assertTrue(csvFormat.isQuoteCharacterSet()); + assertEquals("\\N", csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormat.isEscapeCharacterSet()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormat.getQuoteMode()); + + assertEquals('\t', csvFormat.getDelimiter()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertEquals("\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertTrue(csvFormat.isNullStringSet()); + + assertFalse(csvFormat.equals( null)); + + } + + @Test(expected = IllegalArgumentException.class) + public void testEscapeSameAsCommentStartThrowsException() { + CSVFormat.DEFAULT.withEscape('!').withCommentMarker('!'); + } + + @Test(expected = IllegalArgumentException.class) + public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType() { + // Cannot assume that callers won't use different Character objects + CSVFormat.DEFAULT.withEscape(new Character('!')).withCommentMarker(new Character('!')); + } + + @Test + public void testFormat() { + final CSVFormat format = CSVFormat.DEFAULT; + + assertEquals("", format.format()); + assertEquals("a,b,c", format.format("a", "b", "c")); + assertEquals("\"x,y\",z", format.format("x,y", "z")); + } + + @Test //I assume this to be a defect. + public void testFormatThrowsNullPointerException() { + + final CSVFormat csvFormat = CSVFormat.MYSQL; + + try { + csvFormat.format((Object[]) null); + fail("Expecting exception: NullPointerException"); + } catch(final NullPointerException e) { + assertEquals(CSVFormat.class.getName(), e.getStackTrace()[0].getClassName()); + } + + } + + @Test + public void testGetHeader() throws Exception { + final String[] header = new String[]{"one", "two", "three"}; + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); + // getHeader() makes a copy of the header array. + final String[] headerCopy = formatWithHeader.getHeader(); + headerCopy[0] = "A"; + headerCopy[1] = "B"; + headerCopy[2] = "C"; + assertFalse(Arrays.equals(formatWithHeader.getHeader(), headerCopy)); + assertNotSame(formatWithHeader.getHeader(), headerCopy); + } + + @Test + public void testHashCodeAndWithIgnoreHeaderCase() { + + final CSVFormat csvFormat = CSVFormat.INFORMIX_UNLOAD_CSV; + final CSVFormat csvFormatTwo = csvFormat.withIgnoreHeaderCase(); + csvFormatTwo.hashCode(); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormatTwo.getIgnoreHeaderCase()); // now different + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertFalse(csvFormatTwo.getTrim()); + + } + + @Test + public void testJiraCsv236() { + CSVFormat.DEFAULT.withAllowDuplicateHeaderNames().withHeader("CC","VV","VV"); + } + + @Test + public void testNewFormat() { + + final CSVFormat csvFormat = CSVFormat.newFormat('X'); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertFalse(csvFormat.isEscapeCharacterSet()); + + assertNull(csvFormat.getRecordSeparator()); + assertNull(csvFormat.getQuoteMode()); + + assertNull(csvFormat.getCommentMarker()); + assertFalse(csvFormat.getIgnoreHeaderCase()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertEquals('X', csvFormat.getDelimiter()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.isQuoteCharacterSet()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertNull(csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertFalse(csvFormat.isEscapeCharacterSet()); + + assertNull(csvFormat.getRecordSeparator()); + assertNull(csvFormat.getQuoteMode()); + + assertNull(csvFormat.getCommentMarker()); + assertFalse(csvFormat.getIgnoreHeaderCase()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertEquals('X', csvFormat.getDelimiter()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.isQuoteCharacterSet()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertNull(csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + } + + @Test + public void testNullRecordSeparatorCsv106() { + final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord().withHeader("H1", "H2"); + final String formatStr = format.format("A", "B"); + assertNotNull(formatStr); + assertFalse(formatStr.endsWith("null")); + } + + @Test(expected = IllegalArgumentException.class) + public void testQuoteCharSameAsCommentStartThrowsException() { + CSVFormat.DEFAULT.withQuote('!').withCommentMarker('!'); + } + + @Test(expected = IllegalArgumentException.class) + public void testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() { + // Cannot assume that callers won't use different Character objects + CSVFormat.DEFAULT.withQuote(new Character('!')).withCommentMarker('!'); + } + + @Test(expected = IllegalArgumentException.class) + public void testQuoteCharSameAsDelimiterThrowsException() { + CSVFormat.DEFAULT.withQuote('!').withDelimiter('!'); + } + + @Test(expected = IllegalArgumentException.class) + public void testQuotePolicyNoneWithoutEscapeThrowsException() { + CSVFormat.newFormat('!').withQuoteMode(QuoteMode.NONE); + } + + @Test + public void testRFC4180() { + assertEquals(null, RFC4180.getCommentMarker()); + assertEquals(',', RFC4180.getDelimiter()); + assertEquals(null, RFC4180.getEscapeCharacter()); + assertFalse(RFC4180.getIgnoreEmptyLines()); + assertEquals(Character.valueOf('"'), RFC4180.getQuoteCharacter()); + assertEquals(null, RFC4180.getQuoteMode()); + assertEquals("\r\n", RFC4180.getRecordSeparator()); + } + + @SuppressWarnings("boxing") // no need to worry about boxing here + @Test + public void testSerialization() throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + + try (final ObjectOutputStream oos = new ObjectOutputStream(out)) { + oos.writeObject(CSVFormat.DEFAULT); + oos.flush(); + } + + final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); + final CSVFormat format = (CSVFormat) in.readObject(); + + assertNotNull(format); + assertEquals("delimiter", CSVFormat.DEFAULT.getDelimiter(), format.getDelimiter()); + assertEquals("encapsulator", CSVFormat.DEFAULT.getQuoteCharacter(), format.getQuoteCharacter()); + assertEquals("comment start", CSVFormat.DEFAULT.getCommentMarker(), format.getCommentMarker()); + assertEquals("record separator", CSVFormat.DEFAULT.getRecordSeparator(), format.getRecordSeparator()); + assertEquals("escape", CSVFormat.DEFAULT.getEscapeCharacter(), format.getEscapeCharacter()); + assertEquals("trim", CSVFormat.DEFAULT.getIgnoreSurroundingSpaces(), format.getIgnoreSurroundingSpaces()); + assertEquals("empty lines", CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines()); + } + + @Test + public void testToString() { + + final String string = CSVFormat.INFORMIX_UNLOAD.toString(); + + assertEquals("Delimiter=<|> Escape=<\\> QuoteChar=<\"> RecordSeparator=<\n> EmptyLines:ignored SkipHeaderRecord:false", string); + + } + + @Test + public void testToStringAndWithCommentMarkerTakingCharacter() { + + final CSVFormat.Predefined csvFormat_Predefined = CSVFormat.Predefined.Default; + final CSVFormat csvFormat = csvFormat_Predefined.getFormat(); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + final Character character = Character.valueOf('n'); + + final CSVFormat csvFormatTwo = csvFormat.withCommentMarker(character); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + assertNull(csvFormatTwo.getNullString()); + + assertEquals(',', csvFormatTwo.getDelimiter()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertTrue(csvFormatTwo.isCommentMarkerSet()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertNull(csvFormatTwo.getEscapeCharacter()); + + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertEquals('n', (char)csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormatTwo.equals(csvFormat)); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + assertNull(csvFormatTwo.getNullString()); + + assertEquals(',', csvFormatTwo.getDelimiter()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertTrue(csvFormatTwo.isCommentMarkerSet()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertNull(csvFormatTwo.getEscapeCharacter()); + + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertEquals('n', (char)csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormat.equals(csvFormatTwo)); + + assertFalse(csvFormatTwo.equals(csvFormat)); + assertEquals("Delimiter=<,> QuoteChar=<\"> CommentStart= " + + "RecordSeparator=<\r\n> EmptyLines:ignored SkipHeaderRecord:false" + , csvFormatTwo.toString()); + + } + + @Test + public void testWithCommentStart() throws Exception { + final CSVFormat formatWithCommentStart = CSVFormat.DEFAULT.withCommentMarker('#'); + assertEquals( Character.valueOf('#'), formatWithCommentStart.getCommentMarker()); + } + + @Test(expected = IllegalArgumentException.class) + public void testWithCommentStartCRThrowsException() { + CSVFormat.DEFAULT.withCommentMarker(CR); + } + + @Test + public void testWithDelimiter() throws Exception { + final CSVFormat formatWithDelimiter = CSVFormat.DEFAULT.withDelimiter('!'); + assertEquals('!', formatWithDelimiter.getDelimiter()); + } + + @Test(expected = IllegalArgumentException.class) + public void testWithDelimiterLFThrowsException() { + CSVFormat.DEFAULT.withDelimiter(LF); + } + + @Test + public void testWithEmptyEnum() throws Exception { + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(EmptyEnum.class); + Assert.assertTrue(formatWithHeader.getHeader().length == 0); + } + + @Test + public void testWithEscape() throws Exception { + final CSVFormat formatWithEscape = CSVFormat.DEFAULT.withEscape('&'); + assertEquals(Character.valueOf('&'), formatWithEscape.getEscapeCharacter()); + } + + @Test(expected = IllegalArgumentException.class) + public void testWithEscapeCRThrowsExceptions() { + CSVFormat.DEFAULT.withEscape(CR); + } + + @Test + public void testWithFirstRecordAsHeader() throws Exception { + final CSVFormat formatWithFirstRecordAsHeader = CSVFormat.DEFAULT.withFirstRecordAsHeader(); + assertTrue(formatWithFirstRecordAsHeader.getSkipHeaderRecord()); + assertTrue(formatWithFirstRecordAsHeader.getHeader().length == 0); + } + + @Test + public void testWithHeader() throws Exception { + final String[] header = new String[]{"one", "two", "three"}; + // withHeader() makes a copy of the header array. + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); + assertArrayEquals(header, formatWithHeader.getHeader()); + assertNotSame(header, formatWithHeader.getHeader()); + } + + + @Test + public void testWithHeaderComments() { + + final CSVFormat csvFormat = CSVFormat.DEFAULT; + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + final Object[] objectArray = new Object[8]; + final CSVFormat csvFormatTwo = csvFormat.withHeaderComments(objectArray); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertNull(csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getTrim()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertNull(csvFormatTwo.getNullString()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertEquals(',', csvFormatTwo.getDelimiter()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + + final String string = csvFormatTwo.format(objectArray); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertNull(csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getTrim()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertNull(csvFormatTwo.getNullString()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertEquals(',', csvFormatTwo.getDelimiter()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertNotNull(string); + assertFalse(csvFormat.equals(csvFormatTwo)); // CSV-244 - should not be equal + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + assertEquals(",,,,,,,", string); + + } + + + @Test + public void testWithHeaderEnum() throws Exception { + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(Header.class); + assertArrayEquals(new String[]{ "Name", "Email", "Phone" }, formatWithHeader.getHeader()); + } + + + @Test + public void testWithIgnoreEmptyLines() throws Exception { + assertFalse(CSVFormat.DEFAULT.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); + assertTrue(CSVFormat.DEFAULT.withIgnoreEmptyLines().getIgnoreEmptyLines()); + } + + + @Test + public void testWithIgnoreSurround() throws Exception { + assertFalse(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); + assertTrue(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces().getIgnoreSurroundingSpaces()); + } + + + @Test + public void testWithNullString() throws Exception { + final CSVFormat formatWithNullString = CSVFormat.DEFAULT.withNullString("null"); + assertEquals("null", formatWithNullString.getNullString()); + } + + + @Test + public void testWithQuoteChar() throws Exception { + final CSVFormat formatWithQuoteChar = CSVFormat.DEFAULT.withQuote('"'); + assertEquals(Character.valueOf('"'), formatWithQuoteChar.getQuoteCharacter()); + } + + + @Test(expected = IllegalArgumentException.class) + public void testWithQuoteLFThrowsException() { + CSVFormat.DEFAULT.withQuote(LF); + } + + @Test + public void testWithQuotePolicy() throws Exception { + final CSVFormat formatWithQuotePolicy = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); + assertEquals(QuoteMode.ALL, formatWithQuotePolicy.getQuoteMode()); + } + + @Test + public void testWithRecordSeparatorCR() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(CR); + assertEquals(String.valueOf(CR), formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithRecordSeparatorCRLF() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(CRLF); + assertEquals(CRLF, formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithRecordSeparatorLF() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(LF); + assertEquals(String.valueOf(LF), formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithSystemRecordSeparator() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withSystemRecordSeparator(); + assertEquals(System.getProperty("line.separator"), formatWithRecordSeparator.getRecordSeparator()); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVParserTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVParserTest.java new file mode 100644 index 0000000000..531989397e --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVParserTest.java @@ -0,0 +1,1289 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedReader; +import java.io.PipedWriter; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.io.input.BOMInputStream; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: The 'setter/getter' section, the lexer section and finally the + * parser section. In case a test fails, you should follow a top-down approach for fixing a potential bug (its likely + * that the parser itself fails if the lexer has problems...). + */ +public class CSVParserTest { + + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + private static final String UTF_8_NAME = UTF_8.name(); + + private static final String CSV_INPUT = "a,b,c,d\n" + " a , b , 1 2 \n" + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String CSV_INPUT_1 = "a,b,c,d"; + + private static final String CSV_INPUT_2 = "a,b,1 2"; + + private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, + { "foo\n,,\n\",,\n\"", "d", "e" } }; + + private BOMInputStream createBOMInputStream(final String resource) throws IOException { + final URL url = ClassLoader.getSystemClassLoader().getResource(resource); + return new BOMInputStream(url.openStream()); + } + + private void parseFully(final CSVParser parser) { + for (final CSVRecord csvRecord : parser) { + Assert.assertNotNull(csvRecord); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { { "one", "two", "three" }, // 0 + { "", "" }, // 1 + { "'", "'" }, // 2 + { "'", "'" }, // 3 + { "'", "'" }, // 4 + { ",", "," }, // 5 + { "/", "/" }, // 6 + { "/", "/" }, // 7 + { " 8 ", " \"quoted \"\" /\" / string\" " }, { "9", " \n " }, }; + + final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(CRLF).withEscape('/') + .withIgnoreEmptyLines(); + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { { " ", " ", " " }, // 1 + { " \t ", " ", " " }, // 2 + { " / ", " , ", " ," }, // 3 + }; + + final CSVFormat format = CSVFormat.newFormat(',').withRecordSeparator(CRLF).withEscape('/') + .withIgnoreEmptyLines(); + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; + final String[][] res = { { "one", "two", "three" }, { "on\\\"e", "two" }, { "on\"e", "two" }, + { "one", "tw\"o" }, { "one", "t\\,wo" }, // backslash in quotes only escapes a delimiter (",") + { "one", "two", "th,ree" }, { "a\\\\" }, // backslash in quotes only escapes a delimiter (",") + { "a\\", "b" }, // a backslash must be returnd + { "a\\\\,b" } // backslash in quotes only escapes a delimiter (",") + }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + @Ignore("CSV-107") + public void testBOM() throws IOException { + final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + try (final CSVParser parser = CSVParser.parse(url, Charset.forName(UTF_8_NAME), CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_ParserWithInputStream() throws IOException { + try (final BOMInputStream inputStream = createBOMInputStream("CSVFileParser/bom.csv"); + final CSVParser parser = CSVParser.parse(inputStream, UTF_8, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_ParserWithReader() throws IOException { + try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); + final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_parseWithReader() throws IOException { + try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); + final CSVParser parser = CSVParser.parse(reader, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final Iterator records; + try (final CSVParser parser = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in)) { + records = parser.iterator(); + assertTrue(records.hasNext()); + } + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCSV57() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { { "a", "b#" }, { "\n", " ", "#" }, { "#", "" }, { "# Final comment" } }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentMarkerSet()); + final String[][] res_comments = { { "a", "b#" }, { "\n", " ", "#" }, }; + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + format = CSVFormat.DEFAULT.withCommentMarker('#'); + } + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testDuplicateHeadersNotAllowed() throws Exception { + CSVParser.parse("a,b,a\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader(new String[] {}).withAllowDuplicateHeaderNames(false)); + } + + @Test + public void testDuplicateHeadersAllowedByDefault() throws Exception { + CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[] {})); + } + + @Test + public void testEmptyFileHeaderParsing() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT.withFirstRecordAsHeader())) { + assertNull(parser.nextRecord()); + assertTrue(parser.getHeaderNames().isEmpty()); + } + } + + @Test + public void testEmptyFile() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { + assertNull(parser.nextRecord()); + } + } + + @Test + public void testEmptyLineBehaviorCSV() throws Exception { + final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" } // CSV format ignores empty lines + }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEmptyLineBehaviorExcel() throws Exception { + final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; + final String[][] res = { { "hello", "" }, // CSV format ignores empty lines + { "world", "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEndOfFileBehaviorExcel() throws Exception { + final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "world", "" } }; + + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { { "value1", "value2", "value3", "value4" }, { "a", "b", "c", "d" }, + { " x", "", "", "" }, { "" }, { "\"hello\"", " \"world\"", "abc\ndef", "" } }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { { "foo", "baar" }, { "" }, { "hello", "" }, { "" }, { "world", "" } }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + /** + * Tests an exported Excel worksheet with a header row and rows that have more columns than the headers + * @throws Exception + */ + @Test + public void testExcelHeaderCountLessThanData() throws Exception { + final String code = "A,B,C,,\r\na,b,c,d,e\r\n"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser.getRecords()) { + Assert.assertEquals("a", record.get("A")); + Assert.assertEquals("b", record.get("B")); + Assert.assertEquals("c", record.get("C")); + } + } + } + + @Test + public void testFirstEndOfLineCr() throws IOException { + final String data = "foo\rbaar,\rhello,world\r,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\r", parser.getFirstEndOfLine()); + } + } + + @Test + public void testFirstEndOfLineCrLf() throws IOException { + final String data = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\r\n", parser.getFirstEndOfLine()); + } + } + + @Test + public void testFirstEndOfLineLf() throws IOException { + final String data = "foo\nbaar,\nhello,world\n,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\n", parser.getFirstEndOfLine()); + } + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList<>(); + try (final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z")) { + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + assertEquals(3, records.size()); + assertArrayEquals(new String[] { "a", "b", "c" }, records.get(0).values()); + assertArrayEquals(new String[] { "1", "2", "3" }, records.get(1).values()); + assertArrayEquals(new String[] { "x", "y", "z" }, records.get(2).values()); + } + } + + @Test + public void testGetHeaderMap() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + } + + @Test + public void testGetHeaderNames() throws IOException { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final Map nameIndexMap = parser.getHeaderMap(); + final List headerNames = parser.getHeaderNames(); + Assert.assertNotNull(headerNames); + Assert.assertEquals(nameIndexMap.size(), headerNames.size()); + for (int i = 0; i < headerNames.size(); i++) { + final String name = headerNames.get(i); + Assert.assertEquals(i, nameIndexMap.get(name).intValue()); + } + } + } + + @Test + public void testGetHeaderNamesReadOnly() throws IOException { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final List headerNames = parser.getHeaderNames(); + Assert.assertNotNull(headerNames); + try { + headerNames.add("This is a read-only list."); + fail(); + } catch (final UnsupportedOperationException e) { + // Yes. + } + } + } + + @Test + public void testGetLine() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetOneLine() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT)) { + final CSVRecord record = parser.getRecords().get(0); + assertArrayEquals(RESULT[0], record.values()); + } + } + + /** + * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. + * + * @throws IOException + */ + @Test + public void testGetOneLineOneParser() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT; + try (final PipedWriter writer = new PipedWriter(); + final CSVParser parser = new CSVParser(new PipedReader(writer), format)) { + writer.append(CSV_INPUT_1); + writer.append(format.getRecordSeparator()); + final CSVRecord record1 = parser.nextRecord(); + assertArrayEquals(RESULT[0], record1.values()); + writer.append(CSV_INPUT_2); + writer.append(format.getRecordSeparator()); + final CSVRecord record2 = parser.nextRecord(); + assertArrayEquals(RESULT[1], record2.values()); + } + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordPositionWithCRLF() throws Exception { + this.validateRecordPosition(CRLF); + } + + @Test + public void testGetRecordPositionWithLF() throws Exception { + this.validateRecordPosition(String.valueOf(LF)); + } + + @Test + public void testGetRecords() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + } + + @Test + public void testGetRecordWithMultiLineValues() throws Exception { + try (final CSVParser parser = CSVParser.parse( + "\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF))) { + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderMissing() throws Exception { + final Reader in = new StringReader("a,,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderMissingWithNull() throws Exception { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + CSVFormat.DEFAULT.withHeader().withNullString("").withAllowMissingColumnNames().parse(in).iterator(); + } + + @Test + public void testHeadersMissing() throws Exception { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + CSVFormat.DEFAULT.withHeader().withAllowMissingColumnNames().parse(in).iterator(); + } + + @Test(expected = IllegalArgumentException.class) + public void testHeadersMissingException() throws Exception { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + } + + @Test + public void testIgnoreCaseHeaderMapping() throws Exception { + final Reader reader = new StringReader("1,2,3"); + final Iterator records = CSVFormat.DEFAULT.withHeader("One", "TWO", "three").withIgnoreHeaderCase() + .parse(reader).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("one")); + assertEquals("2", record.get("two")); + assertEquals("3", record.get("THREE")); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + // String code = "world\r\n\n"; + // String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + try (final CSVParser parser = new CSVParser(null, invalidFormat)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[] { "a", "b", "c" }, iterator.next().values()); + assertArrayEquals(new String[] { "1", "2", "3" }, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[] { "x", "y", "z" }, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testIteratorSequenceBreaking() throws IOException { + final String fiveRows = "1\n2\n3\n4\n5\n"; + + // Iterator hasNext() shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + final Iterator iter = parser.iterator(); + recordNumber = 0; + while (iter.hasNext()) { + final CSVRecord record = iter.next(); + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + iter.hasNext(); + while (iter.hasNext()) { + final CSVRecord record = iter.next(); + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + + // Consecutive enhanced for loops shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + + // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + parser.iterator().hasNext(); + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord().parse(in) + .iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test + @Ignore + public void testMongoDbCsv() throws Exception { + try (final CSVParser parser = CSVParser.parse("\"a a\",b,c" + LF + "d,e,f", CSVFormat.MONGODB_CSV)) { + final Iterator itr1 = parser.iterator(); + final Iterator itr2 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr2.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + } + + @Test + // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? + public void testMultipleIterators() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c" + CRLF + "d,e,f", CSVFormat.DEFAULT)) { + final Iterator itr1 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr1.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserNullReaderFormat() throws Exception { + try (final CSVParser parser = new CSVParser(null, CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserReaderNullFormat() throws Exception { + try (final CSVParser parser = new CSVParser(new StringReader(""), null)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test + public void testNoHeaderMap() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT)) { + Assert.assertNull(parser.getHeaderMap()); + } + } + + @Test + public void testParse() throws Exception { + final ClassLoader loader = ClassLoader.getSystemClassLoader(); + final URL url = loader.getResource("CSVFileParser/test.csv"); + final CSVFormat format = CSVFormat.DEFAULT.withHeader("A", "B", "C", "D"); + final Charset charset = StandardCharsets.UTF_8; + + try(final CSVParser parser = CSVParser.parse(new InputStreamReader(url.openStream(), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(new String(Files.readAllBytes(Paths.get(url.toURI())), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(new File(url.toURI()), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(url.openStream(), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(Paths.get(url.toURI()), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(url, charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = new CSVParser(new InputStreamReader(url.openStream(), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = new CSVParser(new InputStreamReader(url.openStream(), charset), format, /*characterOffset=*/0, /*recordNumber=*/1)) { + parseFully(parser); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseFileNullFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse(new File("CSVFileParser/test.csv"), Charset.defaultCharset(), null)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullFileFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullPathFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse((Path) null, Charset.defaultCharset(), CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullStringFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse((String) null, CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullUrlCharsetFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse((URL) null, Charset.defaultCharset(), CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParserUrlNullCharsetFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse(new URL("https://commons.apache.org"), null, CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseStringNullFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse("csv data", (CSVFormat) null)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testParseUrlCharsetNullFormat() throws Exception { + try (final CSVParser parser = CSVParser.parse(new URL("https://commons.apache.org"), Charset.defaultCharset(), null)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT)) { + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + } + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipHeaderOverrideDuplicateHeaders() throws Exception { + final Reader in = new StringReader("a,a,a\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + } + + @Test + public void testSkipSetAltHeaders() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + @Ignore + public void testStartWithEmptyLinesThenHeaders() throws Exception { + final String[] codes = { "\r\n\r\n\r\nhello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testTrailingDelimiter() throws Exception { + final Reader in = new StringReader("a,a,a,\n\"1\",\"2\",\"3\",\nx,y,z,"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() + .withTrailingDelimiter().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + Assert.assertEquals(3, record.size()); + } + + @Test + public void testTrim() throws Exception { + final Reader in = new StringReader("a,a,a\n\" 1 \",\" 2 \",\" 3 \"\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() + .withTrim().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + Assert.assertEquals(3, record.size()); + } + + @Test + public void testRepeatedHeadersAreReturnedInCSVRecordHeaderNames() throws IOException { + final Reader in = new StringReader("header1,header2,header1\n1,2,3\n4,5,6"); + final Iterator records = CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals(Arrays.asList("header1", "header2", "header1"), record.getParser().getHeaderNames()); + } + + @Test + public void testCSV235() throws IOException { + final String dqString = "\"aaa\",\"b\"\"bb\",\"ccc\""; // "aaa","b""bb","ccc" + final Iterator records = CSVFormat.RFC4180.parse(new StringReader(dqString)).iterator(); + final CSVRecord record = records.next(); + assertFalse(records.hasNext()); + Assert.assertEquals(3, record.size()); + assertEquals("aaa", record.get(0)); + assertEquals("b\"bb", record.get(1)); + assertEquals("ccc", record.get(2)); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", + CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", + CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + } + + private void validateRecordPosition(final String lineSeparator) throws IOException { + final String nl = lineSeparator; // used as linebreak in values for better distinction + + final String code = "a,b,c" + lineSeparator + "1,2,3" + lineSeparator + + // to see if recordPosition correctly points to the enclosing quote + "'A" + nl + "A','B" + nl + "B',CC" + lineSeparator + + // unicode test... not very relevant while operating on strings instead of bytes, but for + // completeness... + "\u00c4,\u00d6,\u00dc" + lineSeparator + "EOF,EOF,EOF"; + + final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(lineSeparator); + CSVParser parser = CSVParser.parse(code, format); + + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(code.indexOf('a'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(code.indexOf('1'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + final long positionRecord3 = record.getCharacterPosition(); + assertEquals(3, record.getRecordNumber()); + assertEquals(code.indexOf("'A"), record.getCharacterPosition()); + assertEquals("A" + lineSeparator + "A", record.get(0)); + assertEquals("B" + lineSeparator + "B", record.get(1)); + assertEquals("CC", record.get(2)); + + assertNotNull(record = parser.nextRecord()); + assertEquals(4, record.getRecordNumber()); + assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(5, record.getRecordNumber()); + assertEquals(code.indexOf("EOF"), record.getCharacterPosition()); + + parser.close(); + + // now try to read starting at record 3 + parser = new CSVParser(new StringReader(code.substring((int) positionRecord3)), format, positionRecord3, 3); + + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(code.indexOf("'A"), record.getCharacterPosition()); + assertEquals("A" + lineSeparator + "A", record.get(0)); + assertEquals("B" + lineSeparator + "B", record.get(1)); + assertEquals("CC", record.get(2)); + + assertNotNull(record = parser.nextRecord()); + assertEquals(4, record.getRecordNumber()); + assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); + assertEquals("\u00c4", record.get(0)); + + parser.close(); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVPrinterTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVPrinterTest.java new file mode 100644 index 0000000000..59a5030c8a --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVPrinterTest.java @@ -0,0 +1,1537 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.CharArrayWriter; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.sql.BatchUpdateException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.Vector; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.output.NullOutputStream; +import org.apache.commons.lang3.StringUtils; +import org.h2.tools.SimpleResultSet; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * + */ +public class CSVPrinterTest { + + private static final char EURO_CH = '\u20AC'; + private static final char DQUOTE_CHAR = '"'; + private static final char BACKSLASH_CH = '\\'; + private static final char QUOTE_CH = '\''; + private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; + + private static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + private String longText2; + + private void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = generateLines(nLines, nCol); + + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + final String[][] expected = lines.clone(); + for (int i = 0; i < expected.length; i++) { + expected[i] = expectNulls(expected[i], format); + } + Utils.compare("Printer output :" + printable(result), expected, parseResult); + } + } + + private void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + /** + * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values + * because the parser will convert these strings to null. + */ + private T[] expectNulls(final T[] original, final CSVFormat csvFormat) { + final T[] fixed = original.clone(); + for (int i = 0; i < fixed.length; i++) { + if (Objects.equals(csvFormat.getNullString(), fixed[i])) { + fixed[i] = null; + } + } + return fixed; + } + + private Connection geH2Connection() throws SQLException, ClassNotFoundException { + Class.forName("org.h2.Driver"); + return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + } + + private String[][] generateLines(final int nLines, final int nCol) { + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + return lines; + } + + private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) + throws IOException { + CSVFormat format = baseFormat; + // Use withHeaderComments first to test CSV-145 + format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); + format = format.withCommentMarker('#'); + format = format.withHeader("Col1", "Col2"); + final CSVPrinter csvPrinter = format.print(sw); + csvPrinter.printRecord("A", "B"); + csvPrinter.printRecord("C", "D"); + csvPrinter.close(); + return csvPrinter; + } + + private String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = DQUOTE_CHAR; + break; + case 7: + ch = '\''; + break; + case 8: + ch = BACKSLASH_CH; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + private void setUpTable(final Connection connection) throws SQLException { + try (final Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255), TEXT CLOB)"); + statement.execute("insert into TEST values(1, 'r1', 'long text 1')"); + longText2 = StringUtils.repeat('a', IOUtils.DEFAULT_BUFFER_SIZE - 4); + longText2 += "\"\r\n\"a\""; + longText2 += StringUtils.repeat('a', IOUtils.DEFAULT_BUFFER_SIZE - 1); + statement.execute("insert into TEST values(2, 'r2', '" + longText2 + "')"); + longText2 = longText2.replace("\"","\"\""); + } + } + + @Test + public void testCloseBackwardCompatibility() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + }} + + @Test + public void testCloseWithCsvFormatAutoFlushOff() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(false); + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + } + } + + @Test + public void testCloseWithCsvFormatAutoFlushOn() throws IOException { + // System.out.println("start method"); + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(true); + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, times(1)).flush(); + verify(writer, times(1)).close(); + }} + + @Test + public void testCloseWithFlushOff() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + @SuppressWarnings("resource") + final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); + csvPrinter.close(false); + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + } + } + + @Test + public void testCloseWithFlushOn() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + @SuppressWarnings("resource") + final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); + csvPrinter.close(true); + verify(writer, times(1)).flush(); + } + } + + @Test + public void testCSV135() throws IOException { + List l = new LinkedList(); + l.add("\"\""); // "" + l.add("\\\\"); // \\ + l.add("\\\"\\"); // \"\ + tryFormat(l, null, null, "\"\",\\\\,\\\"\\"); // "",\\,\"\ (unchanged) + tryFormat(l, '"', null, "\"\"\"\"\"\",\\\\,\"\\\"\"\\\""); // """""",\\,"\""\" (quoted, and embedded DQ doubled) + tryFormat(l, null, '\\', "\"\",\\\\\\\\,\\\\\"\\\\"); // "",\\\\,\\"\\ (escapes escaped, not quoted) + tryFormat(l, '"', '\\', "\"\\\"\\\"\",\"\\\\\\\\\",\"\\\\\\\"\\\\\""); // "\"\"","\\\\","\\\"\\" (quoted, and embedded DQ & escape escaped) + tryFormat(l, '"', '"', "\"\"\"\"\"\",\\\\,\"\\\"\"\\\""); // """""",\\,"\""\" (quoted, embedded DQ escaped) + } + + @Test + public void testDelimeterQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("'a,b,c',xyz", sw.toString()); + } + } + + @Test + public void testDelimeterQuoteNone() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + } + } + + @Test + public void testDelimiterEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + } + } + + @Test + public void testDelimiterPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a,b,c,xyz", sw.toString()); + } + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printComment("This is a comment"); + assertEquals("", sw.toString()); + } + } + + @Test + public void testDontQuoteEuroFirstChar() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { + printer.printRecord(EURO_CH, "Deux"); + assertEquals(EURO_CH + ",Deux" + recordSeparator, sw.toString()); + } + } + + @Test + public void testEolEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a!rb!nc,x\fy\bz", sw.toString()); + } + } + + @Test + public void testEolPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a\rb\nc,x\fy\bz", sw.toString()); + } + } + + @Test + public void testEolQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a\rb\nc"); + printer.print("x\by\fz"); + assertEquals("'a\rb\nc',x\by\fz", sw.toString()); + } + } + + @Test + public void testEscapeBackslash1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\"); + } + assertEquals("\\", sw.toString()); + } + + @Test + public void testEscapeBackslash2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\r"); + } + assertEquals("'\\\r'", sw.toString()); + } + + @Test + public void testEscapeBackslash3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("X\\\r"); + } + assertEquals("'X\\\r'", sw.toString()); + } + + @Test + public void testEscapeBackslash4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeBackslash5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeNull1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\"); + } + assertEquals("\\", sw.toString()); + } + + @Test + public void testEscapeNull2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\r"); + } + assertEquals("\"\\\r\"", sw.toString()); + } + + @Test + public void testEscapeNull3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("X\\\r"); + } + assertEquals("\"X\\\r\"", sw.toString()); + } + + @Test + public void testEscapeNull4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeNull5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords( + (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords( + Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testHeader() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testHeaderCommentExcel() throws IOException { + final StringWriter sw = new StringWriter(); + final Date now = new Date(); + final CSVFormat format = CSVFormat.EXCEL; + try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { + assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", + sw.toString()); + } + } + + @Test + public void testHeaderCommentTdf() throws IOException { + final StringWriter sw = new StringWriter(); + final Date now = new Date(); + final CSVFormat format = CSVFormat.TDF; + try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { + assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", + sw.toString()); + } + } + + @Test + public void testHeaderNotSet() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), invalidFormat)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + try (final Connection connection = geH2Connection()) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecords(stmt.executeQuery("select ID, NAME, TEXT from TEST")); + } + } + assertEquals("1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + longText2 + "\"" + recordSeparator, + sw.toString()); + } + + @Test + public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + try (final Connection connection = geH2Connection();) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final ResultSet resultSet = stmt.executeQuery("select ID, NAME, TEXT from TEST"); + final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { + printer.printRecords(resultSet); + } + } + assertEquals("ID,NAME,TEXT" + recordSeparator + "1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + longText2 + + "\"" + recordSeparator, sw.toString()); + } + + @Test + public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + try (final Connection connection = geH2Connection()) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final ResultSet resultSet = stmt.executeQuery("select ID, NAME, TEXT from TEST"); + final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { + printer.printRecords(resultSet); + assertEquals("ID,NAME,TEXT" + recordSeparator + "1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + + longText2 + "\"" + recordSeparator, sw.toString()); + } + } + } + + @Test + @Ignore + public void testJira135_part1() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\""); + printer.printRecord(list); + } + final String expected = "\"\\\"\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Ignore + public void testJira135_part2() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\n"); + printer.printRecord(list); + } + final String expected = "\"\\n\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Ignore + public void testJira135_part3() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\\"); + printer.printRecord(list); + } + final String expected = "\"\\\\\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Ignore + public void testJira135All() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\""); + list.add("\n"); + list.add("\\"); + printer.printRecord(list); + } + final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + public void testMongoDbCsvBasic() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvCommaInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a,b", "c"); + assertEquals("\"a,b\",c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvDoubleQuoteInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a \"c\" b", "d"); + assertEquals("\"a \"\"c\"\" b\",d" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvTabInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a\tb", "c"); + assertEquals("a\tb,c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvBasic() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a", "b"); + assertEquals("a\tb" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvCommaInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a,b", "c"); + assertEquals("a,b\tc" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvTabInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a\tb", "c"); + assertEquals("\"a\tb\"\tc" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, + sw.toString()); + } + } + + @Test + public void testMySqlNullOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\"\tNULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.MYSQL.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + public void testMySqlNullStringDefault() { + assertEquals("\\N", CSVFormat.MYSQL.getNullString()); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCsvPrinterAppendableNullFormat() throws Exception { + try (final CSVPrinter printer = new CSVPrinter(new StringWriter(), null)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCsvPrinterNullAppendableFormat() throws Exception { + try (final CSVPrinter printer = new CSVPrinter(null, CSVFormat.DEFAULT)) { + Assert.fail("This test should have thrown an exception."); + } + } + + @Test + public void testParseCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + printer.printRecord("a", null, "b"); + } + final String csvString = sw.toString(); + assertEquals("a,NULL,b" + recordSeparator, csvString); + try (final CSVParser iterable = format.parse(new StringReader(csvString))) { + final Iterator iterator = iterable.iterator(); + final CSVRecord record = iterator.next(); + assertEquals("a", record.get(0)); + assertEquals(null, record.get(1)); + assertEquals("b", record.get(2)); + assertFalse(iterator.hasNext()); + } + } + + @Test + public void testPlainEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + } + } + + @Test + public void testPlainPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + } + } + + @Test + public void testPlainQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("abc"); + assertEquals("abc", sw.toString()); + } + } + + @Test + @Ignore + public void testPostgreSqlCsvNullOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.POSTGRESQL_CSV.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\",NULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + @Ignore + public void testPostgreSqlCsvTextOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.POSTGRESQL_TEXT.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\"\tNULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + public void testPostgreSqlNullStringDefaultCsv() { + assertEquals("", CSVFormat.POSTGRESQL_CSV.getNullString()); + } + + @Test + public void testPostgreSqlNullStringDefaultText() { + assertEquals("\\N", CSVFormat.POSTGRESQL_TEXT.getNullString()); + } + + @Test + public void testPrint() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { + printer.printRecord("a", null, "b"); + assertEquals("a,NULL,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintOnePositiveInteger() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { + printer.print(Integer.MAX_VALUE); + assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); + } + } + + /** + * Test to target the use of {@link IOUtils#copy(java.io.Reader, Appendable)} which directly + * buffers the value from the Reader to the Appendable. + * + *

Requires the format to have no quote or escape character, value to be a + * {@link java.io.Reader Reader} and the output MUST NOT be a + * {@link java.io.Writer Writer} but some other Appendable.

+ * + * @throws IOException Not expected to happen + */ + @Test + public void testPrintReaderWithoutQuoteToAppendable() throws IOException { + final StringBuilder sb = new StringBuilder(); + final String content = "testValue"; + try (final CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT.withQuote(null))) { + final StringReader value = new StringReader(content); + printer.print(value); + } + assertEquals(content, sb.toString()); + } + + /** + * Test to target the use of {@link IOUtils#copyLarge(java.io.Reader, Writer)} which directly + * buffers the value from the Reader to the Writer. + * + *

Requires the format to have no quote or escape character, value to be a + * {@link java.io.Reader Reader} and the output MUST be a + * {@link java.io.Writer Writer}.

+ * + * @throws IOException Not expected to happen + */ + @Test + public void testPrintReaderWithoutQuoteToWriter() throws IOException { + final StringWriter sw = new StringWriter(); + final String content = "testValue"; + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + final StringReader value = new StringReader(content); + printer.print(value); + } + assertEquals(content, sw.toString()); + } + + @Test + public void testPrintRecordsWithEmptyVector() throws IOException { + final PrintStream out = System.out; + try { + System.setOut(new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM)); + try (CSVPrinter csvPrinter = CSVFormat.POSTGRESQL_TEXT.printer()) { + final Vector vector = new Vector<>(); + final int expectedCapacity = 23; + vector.setSize(expectedCapacity); + csvPrinter.printRecords(vector); + assertEquals(expectedCapacity, vector.capacity()); + } + } finally { + System.setOut(out); + } + } + + @Test + public void testPrintRecordsWithObjectArray() throws IOException { + final CharArrayWriter charArrayWriter = new CharArrayWriter(0); + try (CSVPrinter csvPrinter = CSVFormat.INFORMIX_UNLOAD.print(charArrayWriter)) { + final HashSet hashSet = new HashSet<>(); + final Object[] objectArray = new Object[6]; + objectArray[3] = hashSet; + csvPrinter.printRecords(objectArray); + } + assertEquals(6, charArrayWriter.size()); + assertEquals("\n\n\n\n\n\n", charArrayWriter.toString()); + } + + @Test + public void testPrintRecordsWithResultSetOneRow() throws IOException, SQLException { + try (CSVPrinter csvPrinter = CSVFormat.MYSQL.printer()) { + try (ResultSet resultSet = new SimpleResultSet()) { + csvPrinter.printRecords(resultSet); + assertEquals(0, resultSet.getRow()); + } + } + } + + @Test + public void testPrintToFileWithCharsetUtf16Be() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); + } + + @Test + public void testPrintToFileWithDefaultCharset() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); + } + + @Test + public void testPrintToPathWithDefaultCharset() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testQuoteCommaFirstChar() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { + printer.printRecord(","); + assertEquals("\",\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + } + } + + @Test + public void testRandomDefault() throws Exception { + doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomExcel() throws Exception { + doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Ignore + public void testRandomMongoDbCsv() throws Exception { + doRandom(CSVFormat.MONGODB_CSV, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomMySql() throws Exception { + doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Ignore + public void testRandomOracle() throws Exception { + doRandom(CSVFormat.ORACLE, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Ignore + public void testRandomPostgreSqlCsv() throws Exception { + doRandom(CSVFormat.POSTGRESQL_CSV, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Ignore + public void testRandomPostgreSqlText() throws Exception { + doRandom(CSVFormat.POSTGRESQL_TEXT, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomRfc4180() throws Exception { + doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomTdf() throws Exception { + doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); + } + + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { + printer.printComment("This is a comment"); + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + } + } + + @Test + public void testSingleQuoteQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a'b'c"); + printer.print("xyz"); + assertEquals("'a''b''c',xyz", sw.toString()); + } + } + + @Test + public void testSkipHeaderRecordFalse() throws IOException { + // functionally identical to testHeader, used to test CSV-153 + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testSkipHeaderRecordTrue() throws IOException { + // functionally identical to testHeaderNotSet, used to test CSV-153 + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testTrailingDelimiterOnTwoColumns() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { + printer.printRecord("A", "B"); + assertEquals("A,B,\r\n", sw.toString()); + } + } + + @Test + public void testTrimOffOneColumn() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { + printer.print(" A "); + assertEquals("\" A \"", sw.toString()); + } + } + + @Test + public void testTrimOnOneColumn() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { + printer.print(" A "); + assertEquals("A", sw.toString()); + } + } + + @Test + public void testTrimOnTwoColumns() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { + printer.print(" A "); + printer.print(" B "); + assertEquals("A,B", sw.toString()); + } + } + + private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { + return CSVParser.parse(expected, format).getRecords().get(0).values(); + } + + private void tryFormat(List l, Character quote, Character escape, String expected) throws IOException { + CSVFormat format = CSVFormat.DEFAULT.withQuote(quote).withEscape(escape).withRecordSeparator(null); + Appendable out = new StringBuilder(); + CSVPrinter printer = new CSVPrinter(out, format); + printer.printRecord(l); + printer.close(); + assertEquals(expected, out.toString()); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVRecordTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVRecordTest.java new file mode 100644 index 0000000000..a3d69f61f8 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/CSVRecordTest.java @@ -0,0 +1,215 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class CSVRecordTest { + + private enum EnumFixture { + UNKNOWN_COLUMN + } + + private String[] values; + private CSVRecord record, recordWithHeader; + private Map headerMap; + + @Before + public void setUp() throws Exception { + values = new String[] { "A", "B", "C" }; + final String rowData = StringUtils.join(values, ','); + try (final CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(rowData))) { + record = parser.iterator().next(); + } + final String[] headers = { "first", "second", "third" }; + try (final CSVParser parser = CSVFormat.DEFAULT.withHeader(headers).parse(new StringReader(rowData))) { + recordWithHeader = parser.iterator().next(); + headerMap = parser.getHeaderMap(); + } + } + + @Test + public void testGetInt() { + assertEquals(values[0], record.get(0)); + assertEquals(values[1], record.get(1)); + assertEquals(values[2], record.get(2)); + } + + @Test + public void testGetString() { + assertEquals(values[0], recordWithHeader.get("first")); + assertEquals(values[1], recordWithHeader.get("second")); + assertEquals(values[2], recordWithHeader.get("third")); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetStringInconsistentRecord() { + headerMap.put("fourth", Integer.valueOf(4)); + recordWithHeader.get("fourth"); + } + + @Test(expected = IllegalStateException.class) + public void testGetStringNoHeader() { + record.get("first"); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetUnmappedEnum() { + assertNull(recordWithHeader.get(EnumFixture.UNKNOWN_COLUMN)); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetUnmappedName() { + assertNull(recordWithHeader.get("fourth")); + } + + @Test(expected = ArrayIndexOutOfBoundsException.class) + public void testGetUnmappedNegativeInt() { + assertNull(recordWithHeader.get(Integer.MIN_VALUE)); + } + + @Test(expected = ArrayIndexOutOfBoundsException.class) + public void testGetUnmappedPositiveInt() { + assertNull(recordWithHeader.get(Integer.MAX_VALUE)); + } + + @Test + public void testIsConsistent() { + assertTrue(record.isConsistent()); + assertTrue(recordWithHeader.isConsistent()); + final Map map = recordWithHeader.getParser().getHeaderMap(); + map.put("fourth", Integer.valueOf(4)); + // We are working on a copy of the map, so the record should still be OK. + assertTrue(recordWithHeader.isConsistent()); + } + + @Test + public void testIsInconsistent() throws IOException { + final String[] headers = { "first", "second", "third" }; + final String rowData = StringUtils.join(values, ','); + try (final CSVParser parser = CSVFormat.DEFAULT.withHeader(headers).parse(new StringReader(rowData))) { + final Map map = parser.getHeaderMapRaw(); + final CSVRecord record1 = parser.iterator().next(); + map.put("fourth", Integer.valueOf(4)); + assertFalse(record1.isConsistent()); + } + } + + @Test + public void testIsMapped() { + assertFalse(record.isMapped("first")); + assertTrue(recordWithHeader.isMapped("first")); + assertFalse(recordWithHeader.isMapped("fourth")); + } + + @Test + public void testIsSet() { + assertFalse(record.isSet("first")); + assertTrue(recordWithHeader.isSet("first")); + assertFalse(recordWithHeader.isSet("fourth")); + } + + @Test + public void testIterator() { + int i = 0; + for (final String value : record) { + assertEquals(values[i], value); + i++; + } + } + + @Test + public void testPutInMap() { + final Map map = new ConcurrentHashMap<>(); + this.recordWithHeader.putIn(map); + this.validateMap(map, false); + // Test that we can compile with assigment to the same map as the param. + final TreeMap map2 = recordWithHeader.putIn(new TreeMap()); + this.validateMap(map2, false); + } + + @Test + public void testRemoveAndAddColumns() throws IOException { + // do: + try (final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT)) { + final Map map = recordWithHeader.toMap(); + map.remove("OldColumn"); + map.put("ZColumn", "NewValue"); + // check: + final ArrayList list = new ArrayList<>(map.values()); + Collections.sort(list); + printer.printRecord(list); + Assert.assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); + } + } + + @Test + public void testToMap() { + final Map map = this.recordWithHeader.toMap(); + this.validateMap(map, true); + } + + @Test + public void testToMapWithShortRecord() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b", CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final CSVRecord shortRec = parser.iterator().next(); + shortRec.toMap(); + } + } + + @Test + public void testToMapWithNoHeader() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b", CSVFormat.newFormat(','))) { + final CSVRecord shortRec = parser.iterator().next(); + final Map map = shortRec.toMap(); + assertNotNull("Map is not null.", map); + assertTrue("Map is empty.", map.isEmpty()); + } + } + + private void validateMap(final Map map, final boolean allowsNulls) { + assertTrue(map.containsKey("first")); + assertTrue(map.containsKey("second")); + assertTrue(map.containsKey("third")); + assertFalse(map.containsKey("fourth")); + if (allowsNulls) { + assertFalse(map.containsKey(null)); + } + assertEquals("A", map.get("first")); + assertEquals("B", map.get("second")); + assertEquals("C", map.get("third")); + assertEquals(null, map.get("fourth")); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java new file mode 100644 index 0000000000..d17b483c1f --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.StringReader; + +import org.junit.Test; + +/** + * + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("")) { + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + } + + @Test + public void testReadLookahead1() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("1\n2\r3\n")) { + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + try (final ExtendedBufferedReader br = createBufferedReader("abcdefg")) { + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + } + + @Test + public void testReadLine() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("")) { + assertNull(br.readLine()); + } + try (final ExtendedBufferedReader br = createBufferedReader("\n")) { + assertEquals("", br.readLine()); + assertNull(br.readLine()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\n\nhello")) { + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo", br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("", br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello", br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\n\nhello")) { + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo", br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("", br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello", br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\rbaar\r\nfoo")) { + assertEquals("foo", br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar", br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo", br.readLine()); + assertNull(br.readLine()); + } + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF = "\n"; + final String CR = "\r"; + final String CRLF = CR + LF; + final String LFCR = LF + CR;// easier to read the string below + final String test = "a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f " + CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + } + + private ExtendedBufferedReader createBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/LexerTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/LexerTest.java new file mode 100644 index 0000000000..d6023d6283 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/LexerTest.java @@ -0,0 +1,391 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.BACKSPACE; +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.FF; +import static org.apache.commons.csv.Constants.LF; +import static org.apache.commons.csv.Constants.TAB; +import static org.apache.commons.csv.Token.Type.COMMENT; +import static org.apache.commons.csv.Token.Type.EOF; +import static org.apache.commons.csv.Token.Type.EORECORD; +import static org.apache.commons.csv.Token.Type.TOKEN; +import static org.apache.commons.csv.TokenMatchers.hasContent; +import static org.apache.commons.csv.TokenMatchers.matches; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.StringReader; + +import org.junit.Before; +import org.junit.Test; + +/** + * + */ +public class LexerTest { + + private CSVFormat formatWithEscaping; + + @Before + public void setUp() { + formatWithEscaping = CSVFormat.DEFAULT.withEscape('\\'); + } + + @SuppressWarnings("resource") + private Lexer createLexer(final String input, final CSVFormat format) { + return new Lexer(format, new ExtendedBufferedReader(new StringReader(input))); + } + + @Test + public void testSurroundingSpacesAreDeleted() throws IOException { + final String code = "noSpaces, leadingSpaces,trailingSpaces , surroundingSpaces , ,,"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "noSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testSurroundingTabsAreDeleted() throws IOException { + final String code = "noTabs,\tleadingTab,trailingTab\t,\tsurroundingTabs\t,\t\t,,"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "noTabs")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingTab")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingTab")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingTabs")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "first,line,\n" + "\n" + "\n" + "second,line\n" + "\n" + "\n" + "third line \n" + "\n" + + "\n" + "last, line \n" + "\n" + "\n" + "\n"; + final CSVFormat format = CSVFormat.DEFAULT.withIgnoreEmptyLines(); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "third line ")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "last")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, " line ")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testComments() throws IOException { + final String code = "first,line,\n" + "second,line,tokenWith#no-comment\n" + "# comment line \n" + + "third,line,#no-comment\n" + "# penultimate comment\n" + "# Final comment\n"; + final CSVFormat format = CSVFormat.DEFAULT.withCommentMarker('#'); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "tokenWith#no-comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "comment line")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "third")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testCommentsAndEmptyLines() throws IOException { + final String code = "1,2,3,\n" + // 1 + "\n" + // 1b + "\n" + // 1c + "a,b x,c#no-comment\n" + // 2 + "#foo\n" + // 3 + "\n" + // 4 + "\n" + // 4b + "d,e,#no-comment\n" + // 5 + "\n" + // 5b + "\n" + // 5c + "# penultimate comment\n" + // 6 + "\n" + // 6b + "\n" + // 6c + "# Final comment\n"; // 7 + final CSVFormat format = CSVFormat.DEFAULT.withCommentMarker('#').withIgnoreEmptyLines(false); + assertFalse("Should not ignore empty lines", format.getIgnoreEmptyLines()); + + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "1")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "2")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "3")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1c + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "b x")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "c#no-comment")); // 2 + assertThat(parser.nextToken(new Token()), matches(COMMENT, "foo")); // 3 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4b + assertThat(parser.nextToken(new Token()), matches(TOKEN, "d")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "e")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); // 5 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5c + assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); // 6 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6c + assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); // 7 + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + // simple token with escaping not enabled + @Test + public void testBackslashWithoutEscaping() throws IOException { + /* + * file: a,\,,b \,, + */ + final String code = "a,\\,,b\\\n\\,,"; + final CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isEscapeCharacterSet()); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + // an unquoted single backslash is not an escape char + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); + // an unquoted single backslash is not an escape char + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + // simple token with escaping enabled + @Test + public void testBackslashWithEscaping() throws IOException { + /* + * file: a,\,,b \,, + */ + final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; + final CSVFormat format = formatWithEscaping.withIgnoreEmptyLines(false); + assertTrue(format.isEscapeCharacterSet()); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\nc")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); + assertThat(parser.nextToken(new Token()), matches(EOF, "e")); + } + } + + // encapsulator tokenizer (single line) + @Test + public void testNextToken4() throws IOException { + /* + * file: a,"foo",b a, " foo",b a,"foo " ,b // whitespace after closing encapsulator a, " foo " ,b + */ + final String code = "a,\"foo\",b\na, \" foo\",b\na,\"foo \" ,b\na, \" foo \" ,b"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo ")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo ")); + // assertTokenEquals(EORECORD, "b", parser.nextToken(new Token())); + assertThat(parser.nextToken(new Token()), matches(EOF, "b")); + } + } + + // encapsulator tokenizer (multi line, delimiter in string) + @Test + public void testNextToken5() throws IOException { + final String code = "a,\"foo\n\",b\n\"foo\n baar ,,,\"\n\"\n\t \n\""; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo\n")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "foo\n baar ,,,")); + assertThat(parser.nextToken(new Token()), matches(EOF, "\n\t \n")); + } + } + + // change delimiters, comment, encapsulater + @Test + public void testNextToken6() throws IOException { + /* + * file: a;'b and \' more ' !comment;;;; ;; + */ + final String code = "a;'b and '' more\n'\n!comment;;;;\n;;"; + final CSVFormat format = CSVFormat.DEFAULT.withQuote('\'').withCommentMarker('!').withDelimiter(';'); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b and ' more\n")); + } + } + + // From CSV-1 + @Test + public void testDelimiterIsWhitespace() throws IOException { + final String code = "one\ttwo\t\tfour \t five\t six"; + try (final Lexer parser = createLexer(code, CSVFormat.TDF)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); + assertThat(parser.nextToken(new Token()), matches(EOF, "six")); + } + } + + @Test + public void testEscapedCR() throws Exception { + try (final Lexer lexer = createLexer("character\\" + CR + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test + public void testCR() throws Exception { + try (final Lexer lexer = createLexer("character" + CR + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character")); + assertThat(lexer.nextToken(new Token()), hasContent("NotEscaped")); + } + } + + @Test + public void testEscapedLF() throws Exception { + try (final Lexer lexer = createLexer("character\\" + LF + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + LF + "Escaped")); + } + } + + @Test + public void testLF() throws Exception { + try (final Lexer lexer = createLexer("character" + LF + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character")); + assertThat(lexer.nextToken(new Token()), hasContent("NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect TAB to be unescaped? + public void testEscapedTab() throws Exception { + try (final Lexer lexer = createLexer("character\\" + TAB + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "Escaped")); + } + + } + + @Test + public void testTab() throws Exception { + try (final Lexer lexer = createLexer("character" + TAB + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect BACKSPACE to be unescaped? + public void testEscapedBackspace() throws Exception { + try (final Lexer lexer = createLexer("character\\" + BACKSPACE + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "Escaped")); + } + } + + @Test + public void testBackspace() throws Exception { + try (final Lexer lexer = createLexer("character" + BACKSPACE + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect FF to be unescaped? + public void testEscapedFF() throws Exception { + try (final Lexer lexer = createLexer("character\\" + FF + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "Escaped")); + } + } + + @Test + public void testFF() throws Exception { + try (final Lexer lexer = createLexer("character" + FF + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "NotEscaped")); + } + } + + @Test + public void testEscapedMySqlNullValue() throws Exception { + // MySQL uses \N to symbolize null values. We have to restore this + try (final Lexer lexer = createLexer("character\\NEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character\\NEscaped")); + } + } + + @Test + public void testEscapedCharacter() throws Exception { + try (final Lexer lexer = createLexer("character\\aEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character\\aEscaped")); + } + } + + @Test + public void testEscapedControlCharacter() throws Exception { + // we are explicitly using an escape different from \ here + try (final Lexer lexer = createLexer("character!rEscaped", CSVFormat.DEFAULT.withEscape('!'))) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test + public void testEscapedControlCharacter2() throws Exception { + try (final Lexer lexer = createLexer("character\\rEscaped", CSVFormat.DEFAULT.withEscape('\\'))) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test(expected = IOException.class) + public void testEscapingAtEOF() throws Exception { + final String code = "escaping at EOF is evil\\"; + try (final Lexer lexer = createLexer(code, formatWithEscaping)) { + lexer.nextToken(new Token()); + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/TokenMatchersTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/TokenMatchersTest.java new file mode 100644 index 0000000000..5a4826b8bc --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/TokenMatchersTest.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import static org.apache.commons.csv.TokenMatchers.hasContent; +import static org.apache.commons.csv.TokenMatchers.hasType; +import static org.apache.commons.csv.TokenMatchers.isReady; +import static org.apache.commons.csv.TokenMatchers.matches; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class TokenMatchersTest { + + private Token token; + + @Before + public void setUp() { + token = new Token(); + token.type = Token.Type.TOKEN; + token.isReady = true; + token.content.append("content"); + } + + @Test + public void testHasType() { + assertFalse(hasType(Token.Type.COMMENT).matches(token)); + assertFalse(hasType(Token.Type.EOF).matches(token)); + assertFalse(hasType(Token.Type.EORECORD).matches(token)); + assertTrue(hasType(Token.Type.TOKEN).matches(token)); + } + + @Test + public void testHasContent() { + assertFalse(hasContent("This is not the token's content").matches(token)); + assertTrue(hasContent("content").matches(token)); + } + + @Test + public void testIsReady() { + assertTrue(isReady().matches(token)); + token.isReady = false; + assertFalse(isReady().matches(token)); + } + + @Test + public void testMatches() { + assertTrue(matches(Token.Type.TOKEN, "content").matches(token)); + assertFalse(matches(Token.Type.EOF, "content").matches(token)); + assertFalse(matches(Token.Type.TOKEN, "not the content").matches(token)); + assertFalse(matches(Token.Type.EORECORD, "not the content").matches(token)); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/Utils.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/Utils.java new file mode 100644 index 0000000000..dcf2cc1893 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/Utils.java @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.commons.csv; + +import java.util.List; + +import org.junit.Assert; + +/** + * Utility methods for test cases + */ +final class Utils { + + private Utils() { + } + + /** + * Checks if the 2d array has the same contents as the list of records. + * + * @param message the message to be displayed + * @param expected the 2d array of expected results + * @param actual the List of {@link CSVRecord} entries, each containing an array of values + */ + public static void compare(final String message, final String[][] expected, final List actual) { + Assert.assertEquals(message+" - outer array size", expected.length, actual.size()); + for (int i = 0; i < expected.length; i++) { + Assert.assertArrayEquals(message + " (entry " + i + ")", expected[i], actual.get(i).values()); + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java new file mode 100644 index 0000000000..07e8f94b1e --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.junit.Test; + +public class JiraCsv164Test { + + @Test + public void testJiraCsv154_withCommentMarker() throws IOException { + final String comment = "This is a header comment"; + final CSVFormat format = CSVFormat.EXCEL.withHeader("H1", "H2").withCommentMarker('#') + .withHeaderComments(comment); + final StringBuilder out = new StringBuilder(); + try (final CSVPrinter printer = format.print(out)) { + printer.print("A"); + printer.print("B"); + } + final String s = out.toString(); + assertTrue(s, s.contains(comment)); + } + + @Test + public void testJiraCsv154_withHeaderComments() throws IOException { + final String comment = "This is a header comment"; + final CSVFormat format = CSVFormat.EXCEL.withHeader("H1", "H2").withHeaderComments(comment) + .withCommentMarker('#'); + final StringBuilder out = new StringBuilder(); + try (final CSVPrinter printer = format.print(out)) { + printer.print("A"); + printer.print("B"); + } + final String s = out.toString(); + assertTrue(s, s.contains(comment)); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java new file mode 100644 index 0000000000..d4c41aaf58 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.csv.QuoteMode; +import org.junit.Assert; +import org.junit.Test; + +public class JiraCsv167Test { + + @Test + public void parse() throws IOException { + int totcomment = 0; + int totrecs = 0; + try (final BufferedReader br = new BufferedReader(getTestInput())) { + String s = null; + boolean lastWasComment = false; + while ((s = br.readLine()) != null) { + if (s.startsWith("#")) { + if (!lastWasComment) { // comments are merged + totcomment++; + } + lastWasComment = true; + } else { + totrecs++; + lastWasComment = false; + } + } + } + CSVFormat format = CSVFormat.DEFAULT; + // + format = format.withAllowMissingColumnNames(false); + format = format.withCommentMarker('#'); + format = format.withDelimiter(','); + format = format.withEscape('\\'); + format = format.withHeader("author", "title", "publishDate"); + format = format.withHeaderComments("headerComment"); + format = format.withNullString("NULL"); + format = format.withIgnoreEmptyLines(true); + format = format.withIgnoreSurroundingSpaces(true); + format = format.withQuote('"'); + format = format.withQuoteMode(QuoteMode.ALL); + format = format.withRecordSeparator('\n'); + format = format.withSkipHeaderRecord(false); + // + int comments = 0; + int records = 0; + try (final CSVParser parser = format.parse(getTestInput())) { + for (final CSVRecord csvRecord : parser) { + records++; + if (csvRecord.hasComment()) { + comments++; + } + } + } + // Comment lines are concatenated, in this example 4 lines become 2 comments. + Assert.assertEquals(totcomment, comments); + Assert.assertEquals(totrecs, records); // records includes the header + } + + private Reader getTestInput() { + final InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("csv-167/sample1.csv"); + return new InputStreamReader(is); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java new file mode 100644 index 0000000000..a5722f9253 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.junit.Assert; +import org.junit.Test; + +public class JiraCsv198Test { + + private static final CSVFormat CSV_FORMAT = CSVFormat.EXCEL.withDelimiter('^').withFirstRecordAsHeader(); + + @Test + public void test() throws UnsupportedEncodingException, IOException { + final InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); + Assert.assertNotNull(pointsOfReference); + try (@SuppressWarnings("resource") + CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8"))) { + for (final CSVRecord record : parser) { + final String locationType = record.get("location_type"); + Assert.assertNotNull(locationType); + } + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java new file mode 100644 index 0000000000..847f05e3d1 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.QuoteMode; +import org.junit.Assert; +import org.junit.Test; + +/** + * JIRA: withNullString value is printed without quotes when QuoteMode.ALL is specified + */ +public class JiraCsv203Test { + + @Test + public void testQuoteModeAll() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("\"N/A\",\"Hello\",\"N/A\",\"World\"\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeAllNonNull() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL_NON_NULL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("N/A,\"Hello\",N/A,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithoutQuoteMode() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("N/A,Hello,N/A,World\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeMinimal() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.MINIMAL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("N/A,Hello,N/A,World\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeNonNumeric() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.NON_NUMERIC); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("N/A,\"Hello\",N/A,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithoutNullString() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + //.withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals(",\"Hello\",,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithEmptyValues() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { "", "Hello", "", "World" }); + //printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + Assert.assertEquals("\"\",\"Hello\",\"\",\"World\"\r\n", buffer.toString()); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java new file mode 100644 index 0000000000..7c2d0526d9 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.csv.QuoteMode; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Tests https://issues.apache.org/jira/browse/CSV-213 + * + * This is normal behavior with the current architecture: The iterator() API presents an object that is backed by data + * in the CSVParser as the parser is streaming over the file. The CSVParser is like a forward-only stream. When you + * create a new Iterator you are only created a new view on the same position in the parser's stream. For the behavior + * you want, you need to open a new CSVParser. + */ +@Ignore +public class JiraCsv213Test { + + private void createEndChannel(final File csvFile) { + // @formatter:off + final CSVFormat csvFormat = + CSVFormat.DEFAULT + .withDelimiter(';') + .withFirstRecordAsHeader() + .withRecordSeparator('\n') + .withQuoteMode(QuoteMode.ALL); + // @formatter:on + try (CSVParser parser = csvFormat + .parse(new InputStreamReader(new FileInputStream(csvFile), StandardCharsets.UTF_8))) { + if (parser.iterator().hasNext()) { + System.out.println(parser.getCurrentLineNumber()); + System.out.println(parser.getRecordNumber()); + // get only first record we don't need other's + final CSVRecord firstRecord = parser.iterator().next(); // this fails + + return; + } + } catch (final IOException e) { + throw new IllegalStateException("Error while adding end channel to csv", e); + } + + return; + } + + @Test + public void test() { + createEndChannel(new File("src/test/resources/CSV-213/999751170.patch.csv")); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java new file mode 100644 index 0000000000..a11966c2cf --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv.issues; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.List; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.Assert; +import org.junit.Test; + +public class JiraCvs249Test { + + @Test + public void testJiraCsv249() throws IOException { + + final CSVFormat csvFormat = CSVFormat.DEFAULT.withEscape('\\'); + + final StringWriter stringWriter = new StringWriter(); + + try (CSVPrinter printer = new CSVPrinter(stringWriter, csvFormat)) { + printer.printRecord("foo \\", "bar"); + } + final StringReader stringReader = new StringReader(stringWriter.toString()); + List records; + try (CSVParser parser = new CSVParser(stringReader, csvFormat)) { + records = parser.getRecords(); + } + + records.forEach(record -> { + Assert.assertEquals("foo \\", record.get(0)); + Assert.assertEquals("bar", record.get(1)); + }); + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java new file mode 100644 index 0000000000..887cc8eaec --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv.perf; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.util.zip.GZIPInputStream; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.io.IOUtils; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Tests performance. + * + * To run this test, use: mvn test -Dtest=PeformanceTest + */ +@SuppressWarnings("boxing") // test code +public class PerformanceTest { + + private final int max = 10; + + private static final File BIG_FILE = new File(System.getProperty("java.io.tmpdir"), "worldcitiespop.txt"); + + @BeforeClass + public static void setUpClass() throws FileNotFoundException, IOException { + if (BIG_FILE.exists()) { + System.out.println(String.format("Found test fixture %s: %,d bytes.", BIG_FILE, BIG_FILE.length())); + return; + } + System.out.println("Decompressing test fixture " + BIG_FILE + "..."); + try (final InputStream input = new GZIPInputStream( + new FileInputStream("src/test/resources/perf/worldcitiespop.txt.gz")); + final OutputStream output = new FileOutputStream(BIG_FILE)) { + IOUtils.copy(input, output); + System.out.println(String.format("Decompressed test fixture %s: %,d bytes.", BIG_FILE, BIG_FILE.length())); + } + } + + private BufferedReader createBufferedReader() throws IOException { + return new BufferedReader(new FileReader(BIG_FILE)); + } + + private long parse(final Reader in, final boolean traverseColumns) throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false); + long recordCount = 0; + for (final CSVRecord record : format.parse(in)) { + recordCount++; + if (traverseColumns) { + for (@SuppressWarnings("unused") final String value : record) { + // do nothing for now + } + } + } + return recordCount; + } + + private void println(final String s) { + System.out.println(s); + } + + private long readAll(final BufferedReader in) throws IOException { + long count = 0; + while (in.readLine() != null) { + count++; + } + return count; + } + + public long testParseBigFile(final boolean traverseColumns) throws Exception { + final long startMillis = System.currentTimeMillis(); + final long count = this.parse(this.createBufferedReader(), traverseColumns); + final long totalMillis = System.currentTimeMillis() - startMillis; + this.println(String.format("File parsed in %,d milliseconds with Commons CSV: %,d lines.", totalMillis, count)); + return totalMillis; + } + + @Test + public void testParseBigFileRepeat() throws Exception { + long bestTime = Long.MAX_VALUE; + for (int i = 0; i < this.max; i++) { + bestTime = Math.min(this.testParseBigFile(false), bestTime); + } + this.println(String.format("Best time out of %,d is %,d milliseconds.", this.max, bestTime)); + } + + @Test + public void testReadBigFile() throws Exception { + long bestTime = Long.MAX_VALUE; + for (int i = 0; i < this.max; i++) { + final long startMillis; + long count; + try (final BufferedReader in = this.createBufferedReader()) { + startMillis = System.currentTimeMillis(); + count = 0; + count = this.readAll(in); + } + final long totalMillis = System.currentTimeMillis() - startMillis; + bestTime = Math.min(totalMillis, bestTime); + this.println(String.format("File read in %,d milliseconds: %,d lines.", totalMillis, count)); + } + this.println(String.format("Best time out of %,d is %,d milliseconds.", this.max, bestTime)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.json b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.json new file mode 100644 index 0000000000..8492b22183 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea.json @@ -0,0 +1 @@ +{"parentCommitId":"6aa17567501c94e2ed65dc0c2f2ff3c01e534bd5","currentCommitId":"e2f0a4d8a83a41eaa984086636a3712c682307ea","filesBefore":["src/test/java/org/apache/commons/csv/AssertionsTest.java","src/test/java/org/apache/commons/csv/CSVFileParserTest.java","src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java","src/test/java/org/apache/commons/csv/CSVFormatTest.java","src/test/java/org/apache/commons/csv/CSVParserTest.java","src/test/java/org/apache/commons/csv/CSVPrinterTest.java","src/test/java/org/apache/commons/csv/CSVRecordTest.java","src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java","src/test/java/org/apache/commons/csv/LexerTest.java","src/test/java/org/apache/commons/csv/TokenMatchersTest.java","src/test/java/org/apache/commons/csv/Utils.java","src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java","src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java","src/test/java/org/apache/commons/csv/perf/PerformanceTest.java"],"filesCurrent":["src/test/java/org/apache/commons/csv/AssertionsTest.java","src/test/java/org/apache/commons/csv/CSVFileParserTest.java","src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java","src/test/java/org/apache/commons/csv/CSVFormatTest.java","src/test/java/org/apache/commons/csv/CSVParserTest.java","src/test/java/org/apache/commons/csv/CSVPrinterTest.java","src/test/java/org/apache/commons/csv/CSVRecordTest.java","src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java","src/test/java/org/apache/commons/csv/LexerTest.java","src/test/java/org/apache/commons/csv/TokenMatchersTest.java","src/test/java/org/apache/commons/csv/Utils.java","src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java","src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java","src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java","src/test/java/org/apache/commons/csv/perf/PerformanceTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["src/test/java","src/test/java/org/apache/commons/csv/issues","src/test/java/org/apache/commons/csv","src/test","src","src/test/java/org/apache/commons/csv/perf","src/test/java/org","src/test/java/org/apache/commons","src/test/java/org/apache"],"repositoryDirectoriesCurrent":["src/test/java","src/test/java/org/apache/commons/csv/issues","src/test/java/org/apache/commons/csv","src/test","src","src/test/java/org/apache/commons/csv/perf","src/test/java/org","src/test/java/org/apache/commons","src/test/java/org/apache"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/AssertionsTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/AssertionsTest.java new file mode 100644 index 0000000000..9d956a29f6 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/AssertionsTest.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +/** + */ +public class AssertionsTest { + + @Test + public void testNotNull() throws Exception { + Assertions.notNull(new Object(), "object"); + } + + @Test + public void testNotNullNull() { + assertThrows(IllegalArgumentException.class, () -> Assertions.notNull(null, "object")); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFileParserTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFileParserTest.java new file mode 100644 index 0000000000..52813a3142 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFileParserTest.java @@ -0,0 +1,155 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FilenameFilter; +import java.io.IOException; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Parse tests using test files + */ +public class CSVFileParserTest { + + private static final File BASE = new File("src/test/resources/CSVFileParser"); + + private String readTestData(BufferedReader reader) throws IOException { + String line; + do { + line = reader.readLine(); + } while (line != null && line.startsWith("#")); + return line; + } + + public static Stream generateData() { + final FilenameFilter fileNameFilter = (dir, name) -> name.startsWith("test") && name.endsWith(".txt"); + final File[] files = BASE.listFiles(fileNameFilter); + if (files != null) { + return Arrays.stream(files); + } + return Stream.empty(); + } + + @ParameterizedTest + @MethodSource("generateData") + public void testCSVFile(File testFile) throws Exception { + try (FileReader fr = new FileReader(testFile); BufferedReader testData = new BufferedReader(fr)) { + String line = readTestData(testData); + assertNotNull("file must contain config line", line); + final String[] split = line.split(" "); + assertTrue(split.length >= 1, testFile.getName() + " require 1 param"); + // first line starts with csv data file name + CSVFormat format = CSVFormat.newFormat(',').withQuote('"'); + boolean checkComments = false; + for (int i = 1; i < split.length; i++) { + final String option = split[i]; + final String[] option_parts = option.split("=", 2); + if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); + } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); + } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { + format = format.withCommentMarker(option_parts[1].charAt(0)); + } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { + checkComments = true; + } else { + fail(testFile.getName() + " unexpected option: " + option); + } + } + line = readTestData(testData); // get string version of format + assertEquals(line, format.toString(), testFile.getName() + " Expected format "); + + // Now parse the file and compare against the expected results + // We use a buffered reader internally so no need to create one here. + try (final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), Charset.defaultCharset(), format)) { + for (final CSVRecord record : parser) { + String parsed = Arrays.toString(record.values()); + if (checkComments) { + final String comment = record.getComment().replace("\n", "\\n"); + if (comment != null) { + parsed += "#" + comment; + } + } + final int count = record.size(); + assertEquals(readTestData(testData), count + ":" + parsed, testFile.getName()); + } + } + } + } + + @ParameterizedTest + @MethodSource("generateData") + public void testCSVUrl(File testFile) throws Exception { + try (FileReader fr = new FileReader(testFile); BufferedReader testData = new BufferedReader(fr)) { + String line = readTestData(testData); + assertNotNull("file must contain config line", line); + final String[] split = line.split(" "); + assertTrue(split.length >= 1, testFile.getName() + " require 1 param"); + // first line starts with csv data file name + CSVFormat format = CSVFormat.newFormat(',').withQuote('"'); + boolean checkComments = false; + for (int i = 1; i < split.length; i++) { + final String option = split[i]; + final String[] option_parts = option.split("=", 2); + if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); + } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { + format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); + } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { + format = format.withCommentMarker(option_parts[1].charAt(0)); + } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { + checkComments = true; + } else { + fail(testFile.getName() + " unexpected option: " + option); + } + } + line = readTestData(testData); // get string version of format + assertEquals(line, format.toString(), testFile.getName() + " Expected format "); + + // Now parse the file and compare against the expected results + final URL resource = ClassLoader.getSystemResource("CSVFileParser/" + split[0]); + try (final CSVParser parser = CSVParser.parse(resource, Charset.forName("UTF-8"), format)) { + for (final CSVRecord record : parser) { + String parsed = Arrays.toString(record.values()); + if (checkComments) { + final String comment = record.getComment().replace("\n", "\\n"); + if (comment != null) { + parsed += "#" + comment; + } + } + final int count = record.size(); + assertEquals(readTestData(testData), count + ":" + parsed, testFile.getName()); + } + } + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java new file mode 100644 index 0000000000..a3e6ecd049 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatPredefinedTest.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** + * Tests {@link CSVFormat.Predefined}. + */ +public class CSVFormatPredefinedTest { + + private void test(final CSVFormat format, final String enumName) { + assertEquals(format, CSVFormat.Predefined.valueOf(enumName).getFormat()); + assertEquals(format, CSVFormat.valueOf(enumName)); + } + + @Test + public void testDefault() { + test(CSVFormat.DEFAULT, "Default"); + } + + @Test + public void testExcel() { + test(CSVFormat.EXCEL, "Excel"); + } + + @Test + public void testMySQL() { + test(CSVFormat.MYSQL, "MySQL"); + } + + @Test + public void testOracle() { + test(CSVFormat.ORACLE, "Oracle"); + } + + @Test + public void testPostgreSqlCsv() { + test(CSVFormat.POSTGRESQL_CSV, "PostgreSQLCsv"); + } + + @Test + public void testMongoDbCsv() { + test(CSVFormat.MONGODB_CSV, "MongoDBCsv"); + } + + @Test + public void testMongoDbTsv() { + test(CSVFormat.MONGODB_TSV, "MongoDBTsv"); + } + + @Test + public void testPostgreSqlText() { + test(CSVFormat.POSTGRESQL_TEXT, "PostgreSQLText"); + } + + @Test + public void testRFC4180() { + test(CSVFormat.RFC4180, "RFC4180"); + } + + @Test + public void testTDF() { + test(CSVFormat.TDF, "TDF"); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatTest.java new file mode 100644 index 0000000000..1c95fd6656 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVFormatTest.java @@ -0,0 +1,1183 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.CSVFormat.RFC4180; +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +/** + * Tests {@link CSVFormat}. + */ +public class CSVFormatTest { + + public enum EmptyEnum { + // empty enum. + } + + public enum Header { + Name, Email, Phone + } + + private static void assertNotEquals(final Object right, final Object left) { + assertFalse(right.equals(left)); + assertFalse(left.equals(right)); + } + + private static CSVFormat copy(final CSVFormat format) { + return format.withDelimiter(format.getDelimiter()); + } + + private void assertNotEquals(String name, String type, Object left, Object right) { + if (left.equals(right) || right.equals(left)) { + fail("Objects must not compare equal for " + name + "(" + type + ")"); + } + if (left.hashCode() == right.hashCode()) { + fail("Hash code should not be equal for " + name + "(" + type + ")"); + } + } + + @Test + public void testDelimiterSameAsCommentStartThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withDelimiter('!').withCommentMarker('!')); + } + + @Test + public void testDelimiterSameAsEscapeThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withDelimiter('!').withEscape('!')); + } + + @Test + public void testDuplicateHeaderElements() { + final String[] header = { "A", "A" }; + final CSVFormat format = CSVFormat.DEFAULT.withHeader(header); + assertEquals(2, format.getHeader().length); + assertArrayEquals(header, format.getHeader()); + } + + @Test + public void testDuplicateHeaderElementsFalse() { + assertThrows( + IllegalArgumentException.class, + () -> CSVFormat.DEFAULT.withAllowDuplicateHeaderNames(false).withHeader("A", "A")); + } + + public void testDuplicateHeaderElementsTrue() { + CSVFormat.DEFAULT.withAllowDuplicateHeaderNames(true).withHeader("A", "A"); + } + + @Test + public void testEquals() { + final CSVFormat right = CSVFormat.DEFAULT; + final CSVFormat left = copy(right); + + assertFalse(right.equals(null)); + assertFalse(right.equals("A String Instance")); + + assertEquals(right, right); + assertEquals(right, left); + assertEquals(left, right); + + assertEquals(right.hashCode(), right.hashCode()); + assertEquals(right.hashCode(), left.hashCode()); + } + + @Test + public void testEqualsCommentStart() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withCommentMarker('#') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withCommentMarker('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsDelimiter() { + final CSVFormat right = CSVFormat.newFormat('!'); + final CSVFormat left = CSVFormat.newFormat('?'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsEscape() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withCommentMarker('#') + .withEscape('+') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withEscape('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsHash() throws Exception { + Method[] methods = CSVFormat.class.getDeclaredMethods(); + for (Method method : methods) { + if (Modifier.isPublic(method.getModifiers())) { + final String name = method.getName(); + if (name.startsWith("with")) { + for (Class cls : method.getParameterTypes()) { + final String type = cls.getCanonicalName(); + if ("boolean".equals(type)) { + final Object defTrue = method.invoke(CSVFormat.DEFAULT, new Object[] {Boolean.TRUE}); + final Object defFalse = method.invoke(CSVFormat.DEFAULT, new Object[] {Boolean.FALSE}); + assertNotEquals(name, type ,defTrue, defFalse); + } else if ("char".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {'a'}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {'b'}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.Character".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {null}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new Character('d')}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.String".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {null}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {"e"}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.String[]".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {new String[] {null, null}}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new String[] {"f", "g"}}); + assertNotEquals(name, type, a, b); + } else if ("org.apache.commons.csv.QuoteMode".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {QuoteMode.MINIMAL}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {QuoteMode.ALL}); + assertNotEquals(name, type, a, b); + } else if ("java.lang.Object[]".equals(type)){ + final Object a = method.invoke(CSVFormat.DEFAULT, new Object[] {new Object[] {null, null}}); + final Object b = method.invoke(CSVFormat.DEFAULT, new Object[] {new Object[] {new Object(), new Object()}}); + assertNotEquals(name, type, a, b); + } else if ("withHeader".equals(name)){ // covered above by String[] + // ignored + } else { + fail("Unhandled method: "+name + "(" + type + ")"); + } + } + } + } + } + } + + @Test + public void testEqualsHeader() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withHeader("One", "Two", "Three") + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withHeader("Three", "Two", "One"); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsIgnoreEmptyLines() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withIgnoreEmptyLines(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsIgnoreSurroundingSpaces() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withCommentMarker('#') + .withEscape('+') + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withIgnoreSurroundingSpaces(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsLeftNoQuoteRightQuote() { + final CSVFormat left = CSVFormat.newFormat(',').withQuote(null); + final CSVFormat right = left.withQuote('#'); + + assertNotEquals(left, right); + } + + @Test + public void testEqualsNoQuotes() { + final CSVFormat left = CSVFormat.newFormat(',').withQuote(null); + final CSVFormat right = left.withQuote(null); + + assertEquals(left, right); + } + + @Test + public void testEqualsNullString() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL) + .withNullString("null"); + final CSVFormat left = right + .withNullString("---"); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsOne() { + + final CSVFormat csvFormatOne = CSVFormat.INFORMIX_UNLOAD; + final CSVFormat csvFormatTwo = CSVFormat.MYSQL; + + + assertEquals('\\', (char)csvFormatOne.getEscapeCharacter()); + assertNull(csvFormatOne.getQuoteMode()); + + assertTrue(csvFormatOne.getIgnoreEmptyLines()); + assertFalse(csvFormatOne.getSkipHeaderRecord()); + + assertFalse(csvFormatOne.getIgnoreHeaderCase()); + assertNull(csvFormatOne.getCommentMarker()); + + assertFalse(csvFormatOne.isCommentMarkerSet()); + assertTrue(csvFormatOne.isQuoteCharacterSet()); + + assertEquals('|', csvFormatOne.getDelimiter()); + assertFalse(csvFormatOne.getAllowMissingColumnNames()); + + assertTrue(csvFormatOne.isEscapeCharacterSet()); + assertEquals("\n", csvFormatOne.getRecordSeparator()); + + assertEquals('\"', (char)csvFormatOne.getQuoteCharacter()); + assertFalse(csvFormatOne.getTrailingDelimiter()); + + assertFalse(csvFormatOne.getTrim()); + assertFalse(csvFormatOne.isNullStringSet()); + + assertNull(csvFormatOne.getNullString()); + assertFalse(csvFormatOne.getIgnoreSurroundingSpaces()); + + + assertTrue(csvFormatTwo.isEscapeCharacterSet()); + assertNull(csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormatTwo.getQuoteMode()); + + assertEquals('\t', csvFormatTwo.getDelimiter()); + assertEquals("\n", csvFormatTwo.getRecordSeparator()); + + assertFalse(csvFormatTwo.isQuoteCharacterSet()); + assertTrue(csvFormatTwo.isNullStringSet()); + + assertEquals('\\', (char)csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertFalse(csvFormatTwo.getIgnoreEmptyLines()); + + assertEquals("\\N", csvFormatTwo.getNullString()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormatTwo.getTrailingDelimiter()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormatTwo, csvFormatOne); + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + assertEquals('\\', (char)csvFormatOne.getEscapeCharacter()); + assertNull(csvFormatOne.getQuoteMode()); + + assertTrue(csvFormatOne.getIgnoreEmptyLines()); + assertFalse(csvFormatOne.getSkipHeaderRecord()); + + assertFalse(csvFormatOne.getIgnoreHeaderCase()); + assertNull(csvFormatOne.getCommentMarker()); + + assertFalse(csvFormatOne.isCommentMarkerSet()); + assertTrue(csvFormatOne.isQuoteCharacterSet()); + + assertEquals('|', csvFormatOne.getDelimiter()); + assertFalse(csvFormatOne.getAllowMissingColumnNames()); + + assertTrue(csvFormatOne.isEscapeCharacterSet()); + assertEquals("\n", csvFormatOne.getRecordSeparator()); + + assertEquals('\"', (char)csvFormatOne.getQuoteCharacter()); + assertFalse(csvFormatOne.getTrailingDelimiter()); + + assertFalse(csvFormatOne.getTrim()); + assertFalse(csvFormatOne.isNullStringSet()); + + assertNull(csvFormatOne.getNullString()); + assertFalse(csvFormatOne.getIgnoreSurroundingSpaces()); + + assertTrue(csvFormatTwo.isEscapeCharacterSet()); + assertNull(csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormatTwo.getQuoteMode()); + + assertEquals('\t', csvFormatTwo.getDelimiter()); + assertEquals("\n", csvFormatTwo.getRecordSeparator()); + + assertFalse(csvFormatTwo.isQuoteCharacterSet()); + assertTrue(csvFormatTwo.isNullStringSet()); + + assertEquals('\\', (char)csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertFalse(csvFormatTwo.getIgnoreEmptyLines()); + + assertEquals("\\N", csvFormatTwo.getNullString()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormatTwo.getTrailingDelimiter()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormatOne, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormatOne); + + assertFalse(csvFormatOne.equals(csvFormatTwo)); + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + assertFalse(csvFormatTwo.equals(csvFormatOne)); + + } + + @Test + public void testEqualsQuoteChar() { + final CSVFormat right = CSVFormat.newFormat('\'').withQuote('"'); + final CSVFormat left = right.withQuote('!'); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsQuotePolicy() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withQuoteMode(QuoteMode.MINIMAL); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsRecordSeparator() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL); + final CSVFormat left = right + .withRecordSeparator(LF); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsSkipHeaderRecord() { + final CSVFormat right = CSVFormat.newFormat('\'') + .withRecordSeparator(CR) + .withCommentMarker('#') + .withEscape('+') + .withIgnoreEmptyLines() + .withIgnoreSurroundingSpaces() + .withQuote('"') + .withQuoteMode(QuoteMode.ALL) + .withNullString("null") + .withSkipHeaderRecord(); + final CSVFormat left = right + .withSkipHeaderRecord(false); + + assertNotEquals(right, left); + } + + @Test + public void testEqualsWithNull() { + + final CSVFormat csvFormat = CSVFormat.POSTGRESQL_TEXT; + + assertEquals('\\', (char)csvFormat.getEscapeCharacter()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertFalse(csvFormat.getTrim()); + + assertTrue(csvFormat.isQuoteCharacterSet()); + assertEquals("\\N", csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormat.isEscapeCharacterSet()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormat.getQuoteMode()); + + assertEquals('\t', csvFormat.getDelimiter()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertEquals("\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertTrue(csvFormat.isNullStringSet()); + + assertEquals('\\', (char)csvFormat.getEscapeCharacter()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertFalse(csvFormat.getTrim()); + + assertTrue(csvFormat.isQuoteCharacterSet()); + assertEquals("\\N", csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormat.isEscapeCharacterSet()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertEquals(QuoteMode.ALL_NON_NULL, csvFormat.getQuoteMode()); + + assertEquals('\t', csvFormat.getDelimiter()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertEquals("\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertTrue(csvFormat.isNullStringSet()); + + assertFalse(csvFormat.equals( null)); + + } + + @Test + public void testEscapeSameAsCommentStartThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withEscape('!').withCommentMarker('!')); + } + + @Test + public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType() { + // Cannot assume that callers won't use different Character objects + assertThrows( + IllegalArgumentException.class, + () -> CSVFormat.DEFAULT.withEscape(new Character('!')).withCommentMarker(new Character('!'))); + } + + @Test + public void testFormat() { + final CSVFormat format = CSVFormat.DEFAULT; + + assertEquals("", format.format()); + assertEquals("a,b,c", format.format("a", "b", "c")); + assertEquals("\"x,y\",z", format.format("x,y", "z")); + } + + @Test //I assume this to be a defect. + public void testFormatThrowsNullPointerException() { + + final CSVFormat csvFormat = CSVFormat.MYSQL; + + try { + csvFormat.format((Object[]) null); + fail("Expecting exception: NullPointerException"); + } catch(final NullPointerException e) { + assertEquals(CSVFormat.class.getName(), e.getStackTrace()[0].getClassName()); + } + + } + + @Test + public void testGetHeader() throws Exception { + final String[] header = new String[]{"one", "two", "three"}; + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); + // getHeader() makes a copy of the header array. + final String[] headerCopy = formatWithHeader.getHeader(); + headerCopy[0] = "A"; + headerCopy[1] = "B"; + headerCopy[2] = "C"; + assertFalse(Arrays.equals(formatWithHeader.getHeader(), headerCopy)); + assertNotSame(formatWithHeader.getHeader(), headerCopy); + } + + @Test + public void testHashCodeAndWithIgnoreHeaderCase() { + + final CSVFormat csvFormat = CSVFormat.INFORMIX_UNLOAD_CSV; + final CSVFormat csvFormatTwo = csvFormat.withIgnoreHeaderCase(); + csvFormatTwo.hashCode(); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertTrue(csvFormatTwo.getIgnoreHeaderCase()); // now different + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertFalse(csvFormatTwo.getTrim()); + + } + + @Test + public void testJiraCsv236() { + CSVFormat.DEFAULT.withAllowDuplicateHeaderNames().withHeader("CC","VV","VV"); + } + + @Test + public void testNewFormat() { + + final CSVFormat csvFormat = CSVFormat.newFormat('X'); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertFalse(csvFormat.isEscapeCharacterSet()); + + assertNull(csvFormat.getRecordSeparator()); + assertNull(csvFormat.getQuoteMode()); + + assertNull(csvFormat.getCommentMarker()); + assertFalse(csvFormat.getIgnoreHeaderCase()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertEquals('X', csvFormat.getDelimiter()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.isQuoteCharacterSet()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertNull(csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertFalse(csvFormat.isEscapeCharacterSet()); + + assertNull(csvFormat.getRecordSeparator()); + assertNull(csvFormat.getQuoteMode()); + + assertNull(csvFormat.getCommentMarker()); + assertFalse(csvFormat.getIgnoreHeaderCase()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertEquals('X', csvFormat.getDelimiter()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.isQuoteCharacterSet()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertNull(csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.getIgnoreEmptyLines()); + + } + + @Test + public void testNullRecordSeparatorCsv106() { + final CSVFormat format = CSVFormat.newFormat(';').withSkipHeaderRecord().withHeader("H1", "H2"); + final String formatStr = format.format("A", "B"); + assertNotNull(formatStr); + assertFalse(formatStr.endsWith("null")); + } + + @Test + public void testQuoteCharSameAsCommentStartThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withQuote('!').withCommentMarker('!')); + } + + @Test + public void testQuoteCharSameAsCommentStartThrowsExceptionForWrapperType() { + // Cannot assume that callers won't use different Character objects + assertThrows( + IllegalArgumentException.class, + () -> CSVFormat.DEFAULT.withQuote(new Character('!')).withCommentMarker('!')); + } + + @Test + public void testQuoteCharSameAsDelimiterThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withQuote('!').withDelimiter('!')); + } + + @Test + public void testQuotePolicyNoneWithoutEscapeThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.newFormat('!').withQuoteMode(QuoteMode.NONE)); + } + + @Test + public void testRFC4180() { + assertEquals(null, RFC4180.getCommentMarker()); + assertEquals(',', RFC4180.getDelimiter()); + assertEquals(null, RFC4180.getEscapeCharacter()); + assertFalse(RFC4180.getIgnoreEmptyLines()); + assertEquals(Character.valueOf('"'), RFC4180.getQuoteCharacter()); + assertEquals(null, RFC4180.getQuoteMode()); + assertEquals("\r\n", RFC4180.getRecordSeparator()); + } + + @SuppressWarnings("boxing") // no need to worry about boxing here + @Test + public void testSerialization() throws Exception { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + + try (final ObjectOutputStream oos = new ObjectOutputStream(out)) { + oos.writeObject(CSVFormat.DEFAULT); + oos.flush(); + } + + final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); + final CSVFormat format = (CSVFormat) in.readObject(); + + assertNotNull(format); + assertEquals(CSVFormat.DEFAULT.getDelimiter(), format.getDelimiter(), "delimiter"); + assertEquals(CSVFormat.DEFAULT.getQuoteCharacter(), format.getQuoteCharacter(), "encapsulator"); + assertEquals(CSVFormat.DEFAULT.getCommentMarker(), format.getCommentMarker(), "comment start"); + assertEquals(CSVFormat.DEFAULT.getRecordSeparator(), format.getRecordSeparator(), "record separator"); + assertEquals(CSVFormat.DEFAULT.getEscapeCharacter(), format.getEscapeCharacter(), "escape"); + assertEquals(CSVFormat.DEFAULT.getIgnoreSurroundingSpaces(), format.getIgnoreSurroundingSpaces(), "trim"); + assertEquals(CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines(), "empty lines"); + } + + @Test + public void testToString() { + + final String string = CSVFormat.INFORMIX_UNLOAD.toString(); + + assertEquals("Delimiter=<|> Escape=<\\> QuoteChar=<\"> RecordSeparator=<\n> EmptyLines:ignored SkipHeaderRecord:false", string); + + } + + @Test + public void testToStringAndWithCommentMarkerTakingCharacter() { + + final CSVFormat.Predefined csvFormat_Predefined = CSVFormat.Predefined.Default; + final CSVFormat csvFormat = csvFormat_Predefined.getFormat(); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + final Character character = Character.valueOf('n'); + + final CSVFormat csvFormatTwo = csvFormat.withCommentMarker(character); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + assertNull(csvFormatTwo.getNullString()); + + assertEquals(',', csvFormatTwo.getDelimiter()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertTrue(csvFormatTwo.isCommentMarkerSet()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertNull(csvFormatTwo.getEscapeCharacter()); + + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertEquals('n', (char)csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormatTwo.equals(csvFormat)); + + assertNull(csvFormat.getEscapeCharacter()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getTrim()); + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + + assertFalse(csvFormat.getTrailingDelimiter()); + assertEquals(',', csvFormat.getDelimiter()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertEquals("\r\n", csvFormat.getRecordSeparator()); + + assertFalse(csvFormat.isCommentMarkerSet()); + assertNull(csvFormat.getCommentMarker()); + + assertFalse(csvFormat.isNullStringSet()); + assertFalse(csvFormat.getAllowMissingColumnNames()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertFalse(csvFormat.getSkipHeaderRecord()); + + assertNull(csvFormat.getNullString()); + assertNull(csvFormat.getQuoteMode()); + + assertTrue(csvFormat.getIgnoreEmptyLines()); + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + assertNull(csvFormatTwo.getNullString()); + + assertEquals(',', csvFormatTwo.getDelimiter()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertTrue(csvFormatTwo.isCommentMarkerSet()); + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + + assertFalse(csvFormatTwo.getTrim()); + assertNull(csvFormatTwo.getEscapeCharacter()); + + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertEquals('n', (char)csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormat.equals(csvFormatTwo)); + + assertFalse(csvFormatTwo.equals(csvFormat)); + assertEquals("Delimiter=<,> QuoteChar=<\"> CommentStart= " + + "RecordSeparator=<\r\n> EmptyLines:ignored SkipHeaderRecord:false" + , csvFormatTwo.toString()); + + } + + @Test + public void testWithCommentStart() throws Exception { + final CSVFormat formatWithCommentStart = CSVFormat.DEFAULT.withCommentMarker('#'); + assertEquals( Character.valueOf('#'), formatWithCommentStart.getCommentMarker()); + } + + @Test + public void testWithCommentStartCRThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withCommentMarker(CR)); + } + + @Test + public void testWithDelimiter() throws Exception { + final CSVFormat formatWithDelimiter = CSVFormat.DEFAULT.withDelimiter('!'); + assertEquals('!', formatWithDelimiter.getDelimiter()); + } + + @Test + public void testWithDelimiterLFThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withDelimiter(LF)); + } + + @Test + public void testWithEmptyEnum() throws Exception { + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(EmptyEnum.class); + assertTrue(formatWithHeader.getHeader().length == 0); + } + + @Test + public void testWithEscape() throws Exception { + final CSVFormat formatWithEscape = CSVFormat.DEFAULT.withEscape('&'); + assertEquals(Character.valueOf('&'), formatWithEscape.getEscapeCharacter()); + } + + @Test + public void testWithEscapeCRThrowsExceptions() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withEscape(CR)); + } + + @Test + public void testWithFirstRecordAsHeader() throws Exception { + final CSVFormat formatWithFirstRecordAsHeader = CSVFormat.DEFAULT.withFirstRecordAsHeader(); + assertTrue(formatWithFirstRecordAsHeader.getSkipHeaderRecord()); + assertTrue(formatWithFirstRecordAsHeader.getHeader().length == 0); + } + + @Test + public void testWithHeader() throws Exception { + final String[] header = new String[]{"one", "two", "three"}; + // withHeader() makes a copy of the header array. + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header); + assertArrayEquals(header, formatWithHeader.getHeader()); + assertNotSame(header, formatWithHeader.getHeader()); + } + + + @Test + public void testWithHeaderComments() { + + final CSVFormat csvFormat = CSVFormat.DEFAULT; + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + final Object[] objectArray = new Object[8]; + final CSVFormat csvFormatTwo = csvFormat.withHeaderComments(objectArray); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertNull(csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getTrim()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertNull(csvFormatTwo.getNullString()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertEquals(',', csvFormatTwo.getDelimiter()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + + final String string = csvFormatTwo.format(objectArray); + + assertEquals('\"', (char)csvFormat.getQuoteCharacter()); + assertFalse(csvFormat.isCommentMarkerSet()); + + assertFalse(csvFormat.isEscapeCharacterSet()); + assertTrue(csvFormat.isQuoteCharacterSet()); + + assertFalse(csvFormat.getSkipHeaderRecord()); + assertNull(csvFormat.getQuoteMode()); + + assertEquals(',', csvFormat.getDelimiter()); + assertTrue(csvFormat.getIgnoreEmptyLines()); + + assertFalse(csvFormat.getIgnoreHeaderCase()); + assertNull(csvFormat.getCommentMarker()); + + assertEquals("\r\n", csvFormat.getRecordSeparator()); + assertFalse(csvFormat.getTrailingDelimiter()); + + assertFalse(csvFormat.getAllowMissingColumnNames()); + assertFalse(csvFormat.getTrim()); + + assertFalse(csvFormat.isNullStringSet()); + assertNull(csvFormat.getNullString()); + + assertFalse(csvFormat.getIgnoreSurroundingSpaces()); + assertNull(csvFormat.getEscapeCharacter()); + + assertFalse(csvFormatTwo.getIgnoreHeaderCase()); + assertNull(csvFormatTwo.getQuoteMode()); + + assertTrue(csvFormatTwo.getIgnoreEmptyLines()); + assertFalse(csvFormatTwo.getIgnoreSurroundingSpaces()); + + assertNull(csvFormatTwo.getEscapeCharacter()); + assertFalse(csvFormatTwo.getTrim()); + + assertFalse(csvFormatTwo.isEscapeCharacterSet()); + assertTrue(csvFormatTwo.isQuoteCharacterSet()); + + assertFalse(csvFormatTwo.getSkipHeaderRecord()); + assertEquals('\"', (char)csvFormatTwo.getQuoteCharacter()); + + assertFalse(csvFormatTwo.getAllowMissingColumnNames()); + assertNull(csvFormatTwo.getNullString()); + + assertFalse(csvFormatTwo.isNullStringSet()); + assertFalse(csvFormatTwo.getTrailingDelimiter()); + + assertEquals("\r\n", csvFormatTwo.getRecordSeparator()); + assertEquals(',', csvFormatTwo.getDelimiter()); + + assertNull(csvFormatTwo.getCommentMarker()); + assertFalse(csvFormatTwo.isCommentMarkerSet()); + + assertNotSame(csvFormat, csvFormatTwo); + assertNotSame(csvFormatTwo, csvFormat); + + assertNotNull(string); + assertFalse(csvFormat.equals(csvFormatTwo)); // CSV-244 - should not be equal + + assertFalse(csvFormatTwo.equals(csvFormat)); // CSV-244 - should not be equal + assertEquals(",,,,,,,", string); + + } + + + @Test + public void testWithHeaderEnum() throws Exception { + final CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(Header.class); + assertArrayEquals(new String[]{ "Name", "Email", "Phone" }, formatWithHeader.getHeader()); + } + + + @Test + public void testWithIgnoreEmptyLines() throws Exception { + assertFalse(CSVFormat.DEFAULT.withIgnoreEmptyLines(false).getIgnoreEmptyLines()); + assertTrue(CSVFormat.DEFAULT.withIgnoreEmptyLines().getIgnoreEmptyLines()); + } + + + @Test + public void testWithIgnoreSurround() throws Exception { + assertFalse(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false).getIgnoreSurroundingSpaces()); + assertTrue(CSVFormat.DEFAULT.withIgnoreSurroundingSpaces().getIgnoreSurroundingSpaces()); + } + + + @Test + public void testWithNullString() throws Exception { + final CSVFormat formatWithNullString = CSVFormat.DEFAULT.withNullString("null"); + assertEquals("null", formatWithNullString.getNullString()); + } + + + @Test + public void testWithQuoteChar() throws Exception { + final CSVFormat formatWithQuoteChar = CSVFormat.DEFAULT.withQuote('"'); + assertEquals(Character.valueOf('"'), formatWithQuoteChar.getQuoteCharacter()); + } + + + @Test + public void testWithQuoteLFThrowsException() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withQuote(LF)); + } + + @Test + public void testWithQuotePolicy() throws Exception { + final CSVFormat formatWithQuotePolicy = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); + assertEquals(QuoteMode.ALL, formatWithQuotePolicy.getQuoteMode()); + } + + @Test + public void testWithRecordSeparatorCR() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(CR); + assertEquals(String.valueOf(CR), formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithRecordSeparatorCRLF() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(CRLF); + assertEquals(CRLF, formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithRecordSeparatorLF() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withRecordSeparator(LF); + assertEquals(String.valueOf(LF), formatWithRecordSeparator.getRecordSeparator()); + } + + @Test + public void testWithSystemRecordSeparator() throws Exception { + final CSVFormat formatWithRecordSeparator = CSVFormat.DEFAULT.withSystemRecordSeparator(); + assertEquals(System.getProperty("line.separator"), formatWithRecordSeparator.getRecordSeparator()); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVParserTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVParserTest.java new file mode 100644 index 0000000000..d23a870775 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVParserTest.java @@ -0,0 +1,1280 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PipedReader; +import java.io.PipedWriter; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.io.input.BOMInputStream; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: The 'setter/getter' section, the lexer section and finally the + * parser section. In case a test fails, you should follow a top-down approach for fixing a potential bug (its likely + * that the parser itself fails if the lexer has problems...). + */ +public class CSVParserTest { + + private static final Charset UTF_8 = StandardCharsets.UTF_8; + + private static final String UTF_8_NAME = UTF_8.name(); + + private static final String CSV_INPUT = "a,b,c,d\n" + " a , b , 1 2 \n" + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String CSV_INPUT_1 = "a,b,c,d"; + + private static final String CSV_INPUT_2 = "a,b,1 2"; + + private static final String[][] RESULT = { { "a", "b", "c", "d" }, { "a", "b", "1 2" }, { "foo baar", "b", "" }, + { "foo\n,,\n\",,\n\"", "d", "e" } }; + + private BOMInputStream createBOMInputStream(final String resource) throws IOException { + final URL url = ClassLoader.getSystemClassLoader().getResource(resource); + return new BOMInputStream(url.openStream()); + } + + private void parseFully(final CSVParser parser) { + for (final CSVRecord csvRecord : parser) { + assertNotNull(csvRecord); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { { "one", "two", "three" }, // 0 + { "", "" }, // 1 + { "'", "'" }, // 2 + { "'", "'" }, // 3 + { "'", "'" }, // 4 + { ",", "," }, // 5 + { "/", "/" }, // 6 + { "/", "/" }, // 7 + { " 8 ", " \"quoted \"\" /\" / string\" " }, { "9", " \n " }, }; + + final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(CRLF).withEscape('/') + .withIgnoreEmptyLines(); + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { { " ", " ", " " }, // 1 + { " \t ", " ", " " }, // 2 + { " / ", " , ", " ," }, // 3 + }; + + final CSVFormat format = CSVFormat.newFormat(',').withRecordSeparator(CRLF).withEscape('/') + .withIgnoreEmptyLines(); + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + } + + @Test + @Disabled + public void testBackslashEscapingOld() throws IOException { + final String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; + final String[][] res = { { "one", "two", "three" }, { "on\\\"e", "two" }, { "on\"e", "two" }, + { "one", "tw\"o" }, { "one", "t\\,wo" }, // backslash in quotes only escapes a delimiter (",") + { "one", "two", "th,ree" }, { "a\\\\" }, // backslash in quotes only escapes a delimiter (",") + { "a\\", "b" }, // a backslash must be returnd + { "a\\\\,b" } // backslash in quotes only escapes a delimiter (",") + }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + @Disabled("CSV-107") + public void testBOM() throws IOException { + final URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + try (final CSVParser parser = CSVParser.parse(url, Charset.forName(UTF_8_NAME), CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_ParserWithInputStream() throws IOException { + try (final BOMInputStream inputStream = createBOMInputStream("CSVFileParser/bom.csv"); + final CSVParser parser = CSVParser.parse(inputStream, UTF_8, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_ParserWithReader() throws IOException { + try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); + final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testBOMInputStream_parseWithReader() throws IOException { + try (final Reader reader = new InputStreamReader(createBOMInputStream("CSVFileParser/bom.csv"), UTF_8_NAME); + final CSVParser parser = CSVParser.parse(reader, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser) { + final String string = record.get("Date"); + assertNotNull(string); + // System.out.println("date: " + record.get("Date")); + } + } + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final Iterator records; + try (final CSVParser parser = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in)) { + records = parser.iterator(); + assertTrue(records.hasNext()); + } + assertFalse(records.hasNext()); + assertThrows(NoSuchElementException.class, records::next); + } + + @Test + public void testCSV57() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { { "a", "b#" }, { "\n", " ", "#" }, { "#", "" }, { "# Final comment" } }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentMarkerSet()); + final String[][] res_comments = { { "a", "b#" }, { "\n", " ", "#" }, }; + + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + format = CSVFormat.DEFAULT.withCommentMarker('#'); + } + try (final CSVParser parser = CSVParser.parse(code, format)) { + final List records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + } + + @Test + public void testDuplicateHeadersNotAllowed() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse("a,b,a\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader(new String[] {}).withAllowDuplicateHeaderNames(false))); + } + + @Test + public void testDuplicateHeadersAllowedByDefault() throws Exception { + CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[] {})); + } + + @Test + public void testEmptyFileHeaderParsing() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT.withFirstRecordAsHeader())) { + assertNull(parser.nextRecord()); + assertTrue(parser.getHeaderNames().isEmpty()); + } + } + + @Test + public void testEmptyFile() throws Exception { + try (final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT)) { + assertNull(parser.nextRecord()); + } + } + + @Test + public void testEmptyLineBehaviorCSV() throws Exception { + final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" } // CSV format ignores empty lines + }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEmptyLineBehaviorExcel() throws Exception { + final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; + final String[][] res = { { "hello", "" }, // CSV format ignores empty lines + { "world", "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testEndOfFileBehaviorExcel() throws Exception { + final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "world", "" } }; + + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { { "value1", "value2", "value3", "value4" }, { "a", "b", "c", "d" }, + { " x", "", "", "" }, { "" }, { "\"hello\"", " \"world\"", "abc\ndef", "" } }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { { "foo", "baar" }, { "" }, { "hello", "" }, { "" }, { "world", "" } }; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + /** + * Tests an exported Excel worksheet with a header row and rows that have more columns than the headers + * @throws Exception + */ + @Test + public void testExcelHeaderCountLessThanData() throws Exception { + final String code = "A,B,C,,\r\na,b,c,d,e\r\n"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL.withHeader())) { + for (final CSVRecord record : parser.getRecords()) { + assertEquals("a", record.get("A")); + assertEquals("b", record.get("B")); + assertEquals("c", record.get("C")); + } + } + } + + @Test + public void testFirstEndOfLineCr() throws IOException { + final String data = "foo\rbaar,\rhello,world\r,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\r", parser.getFirstEndOfLine()); + } + } + + @Test + public void testFirstEndOfLineCrLf() throws IOException { + final String data = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\r\n", parser.getFirstEndOfLine()); + } + } + + @Test + public void testFirstEndOfLineLf() throws IOException { + final String data = "foo\nbaar,\nhello,world\n,kanu"; + try (final CSVParser parser = CSVParser.parse(data, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + assertEquals("\n", parser.getFirstEndOfLine()); + } + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList<>(); + try (final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z")) { + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + assertEquals(3, records.size()); + assertArrayEquals(new String[] { "a", "b", "c" }, records.get(0).values()); + assertArrayEquals(new String[] { "1", "2", "3" }, records.get(1).values()); + assertArrayEquals(new String[] { "x", "y", "z" }, records.get(2).values()); + } + } + + @Test + public void testGetHeaderMap() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + assertEquals("A", columnNames.next()); + assertEquals("B", columnNames.next()); + assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + } + + @Test + public void testGetHeaderNames() throws IOException { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final Map nameIndexMap = parser.getHeaderMap(); + final List headerNames = parser.getHeaderNames(); + assertNotNull(headerNames); + assertEquals(nameIndexMap.size(), headerNames.size()); + for (int i = 0; i < headerNames.size(); i++) { + final String name = headerNames.get(i); + assertEquals(i, nameIndexMap.get(name).intValue()); + } + } + } + + @Test + public void testGetHeaderNamesReadOnly() throws IOException { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", + CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final List headerNames = parser.getHeaderNames(); + assertNotNull(headerNames); + try { + headerNames.add("This is a read-only list."); + fail(); + } catch (final UnsupportedOperationException e) { + // Yes. + } + } + } + + @Test + public void testGetLine() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetOneLine() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT_1, CSVFormat.DEFAULT)) { + final CSVRecord record = parser.getRecords().get(0); + assertArrayEquals(RESULT[0], record.values()); + } + } + + /** + * Tests reusing a parser to process new string records one at a time as they are being discovered. See [CSV-110]. + * + * @throws IOException + */ + @Test + public void testGetOneLineOneParser() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT; + try (final PipedWriter writer = new PipedWriter(); + final CSVParser parser = new CSVParser(new PipedReader(writer), format)) { + writer.append(CSV_INPUT_1); + writer.append(format.getRecordSeparator()); + final CSVRecord record1 = parser.nextRecord(); + assertArrayEquals(RESULT[0], record1.values()); + writer.append(CSV_INPUT_2); + writer.append(format.getRecordSeparator()); + final CSVRecord record2 = parser.nextRecord(); + assertArrayEquals(RESULT[1], record2.values()); + } + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordPositionWithCRLF() throws Exception { + this.validateRecordPosition(CRLF); + } + + @Test + public void testGetRecordPositionWithLF() throws Exception { + this.validateRecordPosition(String.valueOf(LF)); + } + + @Test + public void testGetRecords() throws IOException { + try (final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + } + + @Test + public void testGetRecordWithMultiLineValues() throws Exception { + try (final CSVParser parser = CSVParser.parse( + "\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF))) { + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentMarker('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderMissing() throws Exception { + final Reader in = new StringReader("a,,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderMissingWithNull() throws Exception { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + CSVFormat.DEFAULT.withHeader().withNullString("").withAllowMissingColumnNames().parse(in).iterator(); + } + + @Test + public void testHeadersMissing() throws Exception { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + CSVFormat.DEFAULT.withHeader().withAllowMissingColumnNames().parse(in).iterator(); + } + + @Test + public void testHeadersMissingException() { + final Reader in = new StringReader("a,,c,,d\n1,2,3,4\nx,y,z,zz"); + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withHeader().parse(in).iterator()); + } + + @Test + public void testIgnoreCaseHeaderMapping() throws Exception { + final Reader reader = new StringReader("1,2,3"); + final Iterator records = CSVFormat.DEFAULT.withHeader("One", "TWO", "three").withIgnoreHeaderCase() + .parse(reader).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("one")); + assertEquals("2", record.get("two")); + assertEquals("3", record.get("THREE")); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + // String code = "world\r\n\n"; + // String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + } + + @Test + public void testInvalidFormat() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withDelimiter(CR)); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[] { "a", "b", "c" }, iterator.next().values()); + assertArrayEquals(new String[] { "1", "2", "3" }, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[] { "x", "y", "z" }, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testIteratorSequenceBreaking() throws IOException { + final String fiveRows = "1\n2\n3\n4\n5\n"; + + // Iterator hasNext() shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + final Iterator iter = parser.iterator(); + recordNumber = 0; + while (iter.hasNext()) { + final CSVRecord record = iter.next(); + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + iter.hasNext(); + while (iter.hasNext()) { + final CSVRecord record = iter.next(); + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + + // Consecutive enhanced for loops shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + + // Consecutive enhanced for loops with hasNext() peeking shouldn't break sequence + try (CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(fiveRows))) { + int recordNumber = 0; + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + if (recordNumber >= 2) { + break; + } + } + parser.iterator().hasNext(); + for (final CSVRecord record : parser) { + recordNumber++; + assertEquals(String.valueOf(recordNumber), record.get(0)); + } + } + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT)) { + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord().parse(in) + .iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test + @Disabled + public void testMongoDbCsv() throws Exception { + try (final CSVParser parser = CSVParser.parse("\"a a\",b,c" + LF + "d,e,f", CSVFormat.MONGODB_CSV)) { + final Iterator itr1 = parser.iterator(); + final Iterator itr2 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr2.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + } + + @Test + // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? + public void testMultipleIterators() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c" + CRLF + "d,e,f", CSVFormat.DEFAULT)) { + final Iterator itr1 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr1.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + } + + @Test + public void testNewCSVParserNullReaderFormat() { + assertThrows(IllegalArgumentException.class, () -> new CSVParser(null, CSVFormat.DEFAULT)); + } + + @Test + public void testNewCSVParserReaderNullFormat() { + assertThrows(IllegalArgumentException.class, () -> new CSVParser(new StringReader(""), null)); + } + + @Test + public void testNoHeaderMap() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT)) { + assertNull(parser.getHeaderMap()); + } + } + + @Test + public void testParse() throws Exception { + final ClassLoader loader = ClassLoader.getSystemClassLoader(); + final URL url = loader.getResource("CSVFileParser/test.csv"); + final CSVFormat format = CSVFormat.DEFAULT.withHeader("A", "B", "C", "D"); + final Charset charset = StandardCharsets.UTF_8; + + try(final CSVParser parser = CSVParser.parse(new InputStreamReader(url.openStream(), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(new String(Files.readAllBytes(Paths.get(url.toURI())), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(new File(url.toURI()), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(url.openStream(), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(Paths.get(url.toURI()), charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = CSVParser.parse(url, charset, format)) { + parseFully(parser); + } + try(final CSVParser parser = new CSVParser(new InputStreamReader(url.openStream(), charset), format)) { + parseFully(parser); + } + try(final CSVParser parser = new CSVParser(new InputStreamReader(url.openStream(), charset), format, /*characterOffset=*/0, /*recordNumber=*/1)) { + parseFully(parser); + } + } + + @Test + public void testParseFileNullFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse(new File("CSVFileParser/test.csv"), Charset.defaultCharset(), null)); + } + + @Test + public void testParseNullFileFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse((File) null, Charset.defaultCharset(), CSVFormat.DEFAULT)); + } + + @Test + public void testParseNullPathFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse((Path) null, Charset.defaultCharset(), CSVFormat.DEFAULT)); + } + + @Test + public void testParseNullStringFormat() { + assertThrows(IllegalArgumentException.class, () -> CSVParser.parse((String) null, CSVFormat.DEFAULT)); + } + + @Test + public void testParseNullUrlCharsetFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse((URL) null, Charset.defaultCharset(), CSVFormat.DEFAULT)); + } + + @Test + public void testParserUrlNullCharsetFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse(new URL("https://commons.apache.org"), null, CSVFormat.DEFAULT)); + } + + @Test + public void testParseStringNullFormat() { + assertThrows(IllegalArgumentException.class, () -> CSVParser.parse("csv data", (CSVFormat) null)); + } + + @Test + public void testParseUrlCharsetNullFormat() { + assertThrows( + IllegalArgumentException.class, + () -> CSVParser.parse(new URL("https://commons.apache.org"), Charset.defaultCharset(), null)); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT)) { + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + } + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipHeaderOverrideDuplicateHeaders() throws Exception { + final Reader in = new StringReader("a,a,a\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + } + + @Test + public void testSkipSetAltHeaders() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord().parse(in) + .iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + @Disabled + public void testStartWithEmptyLinesThenHeaders() throws Exception { + final String[] codes = { "\r\n\r\n\r\nhello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" }; + final String[][] res = { { "hello", "" }, { "" }, // Excel format does not ignore empty lines + { "" } }; + for (final String code : codes) { + try (final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL)) { + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + } + + @Test + public void testTrailingDelimiter() throws Exception { + final Reader in = new StringReader("a,a,a,\n\"1\",\"2\",\"3\",\nx,y,z,"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() + .withTrailingDelimiter().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + assertEquals(3, record.size()); + } + + @Test + public void testTrim() throws Exception { + final Reader in = new StringReader("a,a,a\n\" 1 \",\" 2 \",\" 3 \"\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("X", "Y", "Z").withSkipHeaderRecord() + .withTrim().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("X")); + assertEquals("2", record.get("Y")); + assertEquals("3", record.get("Z")); + assertEquals(3, record.size()); + } + + @Test + public void testRepeatedHeadersAreReturnedInCSVRecordHeaderNames() throws IOException { + final Reader in = new StringReader("header1,header2,header1\n1,2,3\n4,5,6"); + final Iterator records = CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals(Arrays.asList("header1", "header2", "header1"), record.getParser().getHeaderNames()); + } + + @Test + public void testCSV235() throws IOException { + final String dqString = "\"aaa\",\"b\"\"bb\",\"ccc\""; // "aaa","b""bb","ccc" + final Iterator records = CSVFormat.RFC4180.parse(new StringReader(dqString)).iterator(); + final CSVRecord record = records.next(); + assertFalse(records.hasNext()); + assertEquals(3, record.size()); + assertEquals("aaa", record.get(0)); + assertEquals("b\"bb", record.get(1)); + assertEquals("ccc", record.get(2)); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", + CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + try (final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", + CSVFormat.DEFAULT.withRecordSeparator(lineSeparator))) { + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + } + + private void validateRecordPosition(final String lineSeparator) throws IOException { + final String nl = lineSeparator; // used as linebreak in values for better distinction + + final String code = "a,b,c" + lineSeparator + "1,2,3" + lineSeparator + + // to see if recordPosition correctly points to the enclosing quote + "'A" + nl + "A','B" + nl + "B',CC" + lineSeparator + + // unicode test... not very relevant while operating on strings instead of bytes, but for + // completeness... + "\u00c4,\u00d6,\u00dc" + lineSeparator + "EOF,EOF,EOF"; + + final CSVFormat format = CSVFormat.newFormat(',').withQuote('\'').withRecordSeparator(lineSeparator); + CSVParser parser = CSVParser.parse(code, format); + + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(code.indexOf('a'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(code.indexOf('1'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + final long positionRecord3 = record.getCharacterPosition(); + assertEquals(3, record.getRecordNumber()); + assertEquals(code.indexOf("'A"), record.getCharacterPosition()); + assertEquals("A" + lineSeparator + "A", record.get(0)); + assertEquals("B" + lineSeparator + "B", record.get(1)); + assertEquals("CC", record.get(2)); + + assertNotNull(record = parser.nextRecord()); + assertEquals(4, record.getRecordNumber()); + assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); + + assertNotNull(record = parser.nextRecord()); + assertEquals(5, record.getRecordNumber()); + assertEquals(code.indexOf("EOF"), record.getCharacterPosition()); + + parser.close(); + + // now try to read starting at record 3 + parser = new CSVParser(new StringReader(code.substring((int) positionRecord3)), format, positionRecord3, 3); + + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(code.indexOf("'A"), record.getCharacterPosition()); + assertEquals("A" + lineSeparator + "A", record.get(0)); + assertEquals("B" + lineSeparator + "B", record.get(1)); + assertEquals("CC", record.get(2)); + + assertNotNull(record = parser.nextRecord()); + assertEquals(4, record.getRecordNumber()); + assertEquals(code.indexOf('\u00c4'), record.getCharacterPosition()); + assertEquals("\u00c4", record.get(0)); + + parser.close(); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVPrinterTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVPrinterTest.java new file mode 100644 index 0000000000..b3bc91094b --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVPrinterTest.java @@ -0,0 +1,1530 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.CharArrayWriter; +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.sql.BatchUpdateException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Random; +import java.util.Vector; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.output.NullOutputStream; +import org.apache.commons.lang3.StringUtils; +import org.h2.tools.SimpleResultSet; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * + */ +public class CSVPrinterTest { + + private static final char EURO_CH = '\u20AC'; + private static final char DQUOTE_CHAR = '"'; + private static final char BACKSLASH_CH = '\\'; + private static final char QUOTE_CH = '\''; + private static final int ITERATIONS_FOR_RANDOM_TEST = 50000; + + private static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + private String longText2; + + private void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = generateLines(nLines, nCol); + + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + final String[][] expected = lines.clone(); + for (int i = 0; i < expected.length; i++) { + expected[i] = expectNulls(expected[i], format); + } + Utils.compare("Printer output :" + printable(result), expected, parseResult); + } + } + + private void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + /** + * Converts an input CSV array into expected output values WRT NULLs. NULL strings are converted to null values + * because the parser will convert these strings to null. + */ + private T[] expectNulls(final T[] original, final CSVFormat csvFormat) { + final T[] fixed = original.clone(); + for (int i = 0; i < fixed.length; i++) { + if (Objects.equals(csvFormat.getNullString(), fixed[i])) { + fixed[i] = null; + } + } + return fixed; + } + + private Connection geH2Connection() throws SQLException, ClassNotFoundException { + Class.forName("org.h2.Driver"); + return DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + } + + private String[][] generateLines(final int nLines, final int nCol) { + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + return lines; + } + + private CSVPrinter printWithHeaderComments(final StringWriter sw, final Date now, final CSVFormat baseFormat) + throws IOException { + CSVFormat format = baseFormat; + // Use withHeaderComments first to test CSV-145 + format = format.withHeaderComments("Generated by Apache Commons CSV 1.1", now); + format = format.withCommentMarker('#'); + format = format.withHeader("Col1", "Col2"); + final CSVPrinter csvPrinter = format.print(sw); + csvPrinter.printRecord("A", "B"); + csvPrinter.printRecord("C", "D"); + csvPrinter.close(); + return csvPrinter; + } + + private String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = DQUOTE_CHAR; + break; + case 7: + ch = '\''; + break; + case 8: + ch = BACKSLASH_CH; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + private void setUpTable(final Connection connection) throws SQLException { + try (final Statement statement = connection.createStatement()) { + statement.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255), TEXT CLOB)"); + statement.execute("insert into TEST values(1, 'r1', 'long text 1')"); + longText2 = StringUtils.repeat('a', IOUtils.DEFAULT_BUFFER_SIZE - 4); + longText2 += "\"\r\n\"a\""; + longText2 += StringUtils.repeat('a', IOUtils.DEFAULT_BUFFER_SIZE - 1); + statement.execute("insert into TEST values(2, 'r2', '" + longText2 + "')"); + longText2 = longText2.replace("\"","\"\""); + } + } + + @Test + public void testCloseBackwardCompatibility() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + }} + + @Test + public void testCloseWithCsvFormatAutoFlushOff() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(false); + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + } + } + + @Test + public void testCloseWithCsvFormatAutoFlushOn() throws IOException { + // System.out.println("start method"); + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT.withAutoFlush(true); + try (CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + // empty + } + verify(writer, times(1)).flush(); + verify(writer, times(1)).close(); + }} + + @Test + public void testCloseWithFlushOff() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + @SuppressWarnings("resource") + final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); + csvPrinter.close(false); + verify(writer, never()).flush(); + verify(writer, times(1)).close(); + } + } + + @Test + public void testCloseWithFlushOn() throws IOException { + try (final Writer writer = mock(Writer.class)) { + final CSVFormat csvFormat = CSVFormat.DEFAULT; + @SuppressWarnings("resource") + final CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat); + csvPrinter.close(true); + verify(writer, times(1)).flush(); + } + } + + @Test + public void testCSV135() throws IOException { + List l = new LinkedList(); + l.add("\"\""); // "" + l.add("\\\\"); // \\ + l.add("\\\"\\"); // \"\ + tryFormat(l, null, null, "\"\",\\\\,\\\"\\"); // "",\\,\"\ (unchanged) + tryFormat(l, '"', null, "\"\"\"\"\"\",\\\\,\"\\\"\"\\\""); // """""",\\,"\""\" (quoted, and embedded DQ doubled) + tryFormat(l, null, '\\', "\"\",\\\\\\\\,\\\\\"\\\\"); // "",\\\\,\\"\\ (escapes escaped, not quoted) + tryFormat(l, '"', '\\', "\"\\\"\\\"\",\"\\\\\\\\\",\"\\\\\\\"\\\\\""); // "\"\"","\\\\","\\\"\\" (quoted, and embedded DQ & escape escaped) + tryFormat(l, '"', '"', "\"\"\"\"\"\",\\\\,\"\\\"\"\\\""); // """""",\\,"\""\" (quoted, embedded DQ escaped) + } + + @Test + public void testDelimeterQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("'a,b,c',xyz", sw.toString()); + } + } + + @Test + public void testDelimeterQuoteNone() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuoteMode(QuoteMode.NONE); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + } + } + + @Test + public void testDelimiterEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuote(null))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + } + } + + @Test + public void testDelimiterPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a,b,c,xyz", sw.toString()); + } + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printComment("This is a comment"); + assertEquals("", sw.toString()); + } + } + + @Test + public void testDontQuoteEuroFirstChar() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { + printer.printRecord(EURO_CH, "Deux"); + assertEquals(EURO_CH + ",Deux" + recordSeparator, sw.toString()); + } + } + + @Test + public void testEolEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a!rb!nc,x\fy\bz", sw.toString()); + } + } + + @Test + public void testEolPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a\rb\nc,x\fy\bz", sw.toString()); + } + } + + @Test + public void testEolQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a\rb\nc"); + printer.print("x\by\fz"); + assertEquals("'a\rb\nc',x\by\fz", sw.toString()); + } + } + + @Test + public void testEscapeBackslash1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\"); + } + assertEquals("\\", sw.toString()); + } + + @Test + public void testEscapeBackslash2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\r"); + } + assertEquals("'\\\r'", sw.toString()); + } + + @Test + public void testEscapeBackslash3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("X\\\r"); + } + assertEquals("'X\\\r'", sw.toString()); + } + + @Test + public void testEscapeBackslash4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeBackslash5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(QUOTE_CH))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeNull1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\"); + } + assertEquals("\\", sw.toString()); + } + + @Test + public void testEscapeNull2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\r"); + } + assertEquals("\"\\\r\"", sw.toString()); + } + + @Test + public void testEscapeNull3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("X\\\r"); + } + assertEquals("\"X\\\r\"", sw.toString()); + } + + @Test + public void testEscapeNull4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testEscapeNull5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape(null))) { + printer.print("\\\\"); + } + assertEquals("\\\\", sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords((Object[]) new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords( + (Object[]) new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecords( + Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL)) { + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testHeader() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3"))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testHeaderCommentExcel() throws IOException { + final StringWriter sw = new StringWriter(); + final Date now = new Date(); + final CSVFormat format = CSVFormat.EXCEL; + try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { + assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1,Col2\r\nA,B\r\nC,D\r\n", + sw.toString()); + } + } + + @Test + public void testHeaderCommentTdf() throws IOException { + final StringWriter sw = new StringWriter(); + final Date now = new Date(); + final CSVFormat format = CSVFormat.TDF; + try (final CSVPrinter csvPrinter = printWithHeaderComments(sw, now, format)) { + assertEquals("# Generated by Apache Commons CSV 1.1\r\n# " + now + "\r\nCol1\tCol2\r\nA\tB\r\nC\tD\r\n", + sw.toString()); + } + } + + @Test + public void testHeaderNotSet() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testInvalidFormat() { + assertThrows(IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withDelimiter(CR)); + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + try (final Connection connection = geH2Connection()) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecords(stmt.executeQuery("select ID, NAME, TEXT from TEST")); + } + } + assertEquals("1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + longText2 + "\"" + recordSeparator, + sw.toString()); + } + + @Test + public void testJdbcPrinterWithResultSet() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + try (final Connection connection = geH2Connection();) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final ResultSet resultSet = stmt.executeQuery("select ID, NAME, TEXT from TEST"); + final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet).print(sw)) { + printer.printRecords(resultSet); + } + } + assertEquals("ID,NAME,TEXT" + recordSeparator + "1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + longText2 + + "\"" + recordSeparator, sw.toString()); + } + + @Test + public void testJdbcPrinterWithResultSetMetaData() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + try (final Connection connection = geH2Connection()) { + setUpTable(connection); + try (final Statement stmt = connection.createStatement(); + final ResultSet resultSet = stmt.executeQuery("select ID, NAME, TEXT from TEST"); + final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(resultSet.getMetaData()).print(sw)) { + printer.printRecords(resultSet); + assertEquals("ID,NAME,TEXT" + recordSeparator + "1,r1,\"long text 1\"" + recordSeparator + "2,r2,\"" + + longText2 + "\"" + recordSeparator, sw.toString()); + } + } + } + + @Test + @Disabled + public void testJira135_part1() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\""); + printer.printRecord(list); + } + final String expected = "\"\\\"\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Disabled + public void testJira135_part2() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\n"); + printer.printRecord(list); + } + final String expected = "\"\\n\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Disabled + public void testJira135_part3() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\\"); + printer.printRecord(list); + } + final String expected = "\"\\\\\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + @Disabled + public void testJira135All() throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator('\n').withQuote(DQUOTE_CHAR).withEscape(BACKSLASH_CH); + final StringWriter sw = new StringWriter(); + final List list = new LinkedList<>(); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + list.add("\""); + list.add("\n"); + list.add("\\"); + printer.printRecord(list); + } + final String expected = "\"\\\"\",\"\\n\",\"\\\"" + format.getRecordSeparator(); + assertEquals(expected, sw.toString()); + final String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(list.toArray(), format), record0); + } + + @Test + public void testMongoDbCsvBasic() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvCommaInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a,b", "c"); + assertEquals("\"a,b\",c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvDoubleQuoteInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a \"c\" b", "d"); + assertEquals("\"a \"\"c\"\" b\",d" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbCsvTabInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_CSV)) { + printer.printRecord("a\tb", "c"); + assertEquals("a\tb,c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvBasic() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a", "b"); + assertEquals("a\tb" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvCommaInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a,b", "c"); + assertEquals("a,b\tc" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMongoDbTsvTabInValue() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.MONGODB_TSV)) { + printer.printRecord("a\tb", "c"); + assertEquals("\"a\tb\"\tc" + recordSeparator, sw.toString()); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, + sw.toString()); + } + } + + @Test + public void testMySqlNullOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.MYSQL.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.NON_NUMERIC); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\"\tNULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.MYSQL.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.MYSQL.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.MYSQL; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + public void testMySqlNullStringDefault() { + assertEquals("\\N", CSVFormat.MYSQL.getNullString()); + } + + @Test + public void testNewCsvPrinterAppendableNullFormat() { + assertThrows(IllegalArgumentException.class, () -> new CSVPrinter(new StringWriter(), null)); + } + + @Test + public void testNewCsvPrinterNullAppendableFormat() { + assertThrows(IllegalArgumentException.class, () -> new CSVPrinter(null, CSVFormat.DEFAULT)); + } + + @Test + public void testParseCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); + try (final CSVPrinter printer = new CSVPrinter(sw, format)) { + printer.printRecord("a", null, "b"); + } + final String csvString = sw.toString(); + assertEquals("a,NULL,b" + recordSeparator, csvString); + try (final CSVParser iterable = format.parse(new StringReader(csvString))) { + final Iterator iterator = iterable.iterator(); + final CSVRecord record = iterator.next(); + assertEquals("a", record.get(0)); + assertEquals(null, record.get(1)); + assertEquals("b", record.get(2)); + assertFalse(iterator.hasNext()); + } + } + + @Test + public void testPlainEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null).withEscape('!'))) { + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + } + } + + @Test + public void testPlainPlain() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + } + } + + @Test + public void testPlainQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("abc"); + assertEquals("abc", sw.toString()); + } + } + + @Test + @Disabled + public void testPostgreSqlCsvNullOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.POSTGRESQL_CSV.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\",NULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_CSV.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.POSTGRESQL_CSV; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + @Disabled + public void testPostgreSqlCsvTextOutput() throws IOException { + Object[] s = new String[] { "NULL", null }; + CSVFormat format = CSVFormat.POSTGRESQL_TEXT.withQuote(DQUOTE_CHAR).withNullString("NULL").withQuoteMode(QuoteMode.ALL_NON_NULL); + StringWriter writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + String expected = "\"NULL\"\tNULL\n"; + assertEquals(expected, writer.toString()); + String[] record0 = toFirstRecordValues(expected, format); + assertArrayEquals(new Object[2], record0); + + s = new String[] { "\\N", null }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "A" }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\n", "A" }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("\\N"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\n\tA\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_TEXT.withNullString("NULL"); + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\tNULL\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "", null }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\t\\N\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\N", "", "\u000e,\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\N\t\t\u000e,\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "NULL", "\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "NULL\t\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + + s = new String[] { "\\\r" }; + format = CSVFormat.POSTGRESQL_TEXT; + writer = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(writer, format)) { + printer.printRecord(s); + } + expected = "\\\\\\r\n"; + assertEquals(expected, writer.toString()); + record0 = toFirstRecordValues(expected, format); + assertArrayEquals(expectNulls(s, format), record0); + } + + @Test + public void testPostgreSqlNullStringDefaultCsv() { + assertEquals("", CSVFormat.POSTGRESQL_CSV.getNullString()); + } + + @Test + public void testPostgreSqlNullStringDefaultText() { + assertEquals("\\N", CSVFormat.POSTGRESQL_TEXT.getNullString()); + } + + @Test + public void testPrint() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(sw)) { + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL"))) { + printer.printRecord("a", null, "b"); + assertEquals("a,NULL,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT)) { + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + } + } + + @Test + public void testPrintOnePositiveInteger() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.MINIMAL))) { + printer.print(Integer.MAX_VALUE); + assertEquals(String.valueOf(Integer.MAX_VALUE), sw.toString()); + } + } + + /** + * Test to target the use of {@link IOUtils#copy(java.io.Reader, Appendable)} which directly + * buffers the value from the Reader to the Appendable. + * + *

Requires the format to have no quote or escape character, value to be a + * {@link java.io.Reader Reader} and the output MUST NOT be a + * {@link java.io.Writer Writer} but some other Appendable.

+ * + * @throws IOException Not expected to happen + */ + @Test + public void testPrintReaderWithoutQuoteToAppendable() throws IOException { + final StringBuilder sb = new StringBuilder(); + final String content = "testValue"; + try (final CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT.withQuote(null))) { + final StringReader value = new StringReader(content); + printer.print(value); + } + assertEquals(content, sb.toString()); + } + + /** + * Test to target the use of {@link IOUtils#copyLarge(java.io.Reader, Writer)} which directly + * buffers the value from the Reader to the Writer. + * + *

Requires the format to have no quote or escape character, value to be a + * {@link java.io.Reader Reader} and the output MUST be a + * {@link java.io.Writer Writer}.

+ * + * @throws IOException Not expected to happen + */ + @Test + public void testPrintReaderWithoutQuoteToWriter() throws IOException { + final StringWriter sw = new StringWriter(); + final String content = "testValue"; + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote(null))) { + final StringReader value = new StringReader(content); + printer.print(value); + } + assertEquals(content, sw.toString()); + } + + @Test + public void testPrintRecordsWithEmptyVector() throws IOException { + final PrintStream out = System.out; + try { + System.setOut(new PrintStream(NullOutputStream.NULL_OUTPUT_STREAM)); + try (CSVPrinter csvPrinter = CSVFormat.POSTGRESQL_TEXT.printer()) { + final Vector vector = new Vector<>(); + final int expectedCapacity = 23; + vector.setSize(expectedCapacity); + csvPrinter.printRecords(vector); + assertEquals(expectedCapacity, vector.capacity()); + } + } finally { + System.setOut(out); + } + } + + @Test + public void testPrintRecordsWithObjectArray() throws IOException { + final CharArrayWriter charArrayWriter = new CharArrayWriter(0); + try (CSVPrinter csvPrinter = CSVFormat.INFORMIX_UNLOAD.print(charArrayWriter)) { + final HashSet hashSet = new HashSet<>(); + final Object[] objectArray = new Object[6]; + objectArray[3] = hashSet; + csvPrinter.printRecords(objectArray); + } + assertEquals(6, charArrayWriter.size()); + assertEquals("\n\n\n\n\n\n", charArrayWriter.toString()); + } + + @Test + public void testPrintRecordsWithResultSetOneRow() throws IOException, SQLException { + try (CSVPrinter csvPrinter = CSVFormat.MYSQL.printer()) { + try (ResultSet resultSet = new SimpleResultSet()) { + csvPrinter.printRecords(resultSet); + assertEquals(0, resultSet.getRow()); + } + } + } + + @Test + public void testPrintToFileWithCharsetUtf16Be() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, StandardCharsets.UTF_16BE)) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, StandardCharsets.UTF_16BE)); + } + + @Test + public void testPrintToFileWithDefaultCharset() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file, Charset.defaultCharset())) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); + } + + @Test + public void testPrintToPathWithDefaultCharset() throws IOException { + final File file = File.createTempFile(getClass().getName(), ".csv"); + try (final CSVPrinter printer = CSVFormat.DEFAULT.print(file.toPath(), Charset.defaultCharset())) { + printer.printRecord("a", "b\\c"); + } + assertEquals("a,b\\c" + recordSeparator, FileUtils.readFileToString(file, Charset.defaultCharset())); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL))) { + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testQuoteCommaFirstChar() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.RFC4180)) { + printer.printRecord(","); + assertEquals("\",\"" + recordSeparator, sw.toString()); + } + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NON_NUMERIC))) { + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + } + } + + @Test + public void testRandomDefault() throws Exception { + doRandom(CSVFormat.DEFAULT, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomExcel() throws Exception { + doRandom(CSVFormat.EXCEL, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Disabled + public void testRandomMongoDbCsv() throws Exception { + doRandom(CSVFormat.MONGODB_CSV, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomMySql() throws Exception { + doRandom(CSVFormat.MYSQL, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Disabled + public void testRandomOracle() throws Exception { + doRandom(CSVFormat.ORACLE, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Disabled + public void testRandomPostgreSqlCsv() throws Exception { + doRandom(CSVFormat.POSTGRESQL_CSV, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + @Disabled + public void testRandomPostgreSqlText() throws Exception { + doRandom(CSVFormat.POSTGRESQL_TEXT, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomRfc4180() throws Exception { + doRandom(CSVFormat.RFC4180, ITERATIONS_FOR_RANDOM_TEST); + } + + @Test + public void testRandomTdf() throws Exception { + doRandom(CSVFormat.TDF, ITERATIONS_FOR_RANDOM_TEST); + } + + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentMarker('#'))) { + printer.printComment("This is a comment"); + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + } + } + + @Test + public void testSingleQuoteQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuote('\''))) { + printer.print("a'b'c"); + printer.print("xyz"); + assertEquals("'a''b''c',xyz", sw.toString()); + } + } + + @Test + public void testSkipHeaderRecordFalse() throws IOException { + // functionally identical to testHeader, used to test CSV-153 + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(false))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("C1,C2,C3\r\na,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testSkipHeaderRecordTrue() throws IOException { + // functionally identical to testHeaderNotSet, used to test CSV-153 + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, + CSVFormat.DEFAULT.withQuote(null).withHeader("C1", "C2", "C3").withSkipHeaderRecord(true))) { + printer.printRecord("a", "b", "c"); + printer.printRecord("x", "y", "z"); + assertEquals("a,b,c\r\nx,y,z\r\n", sw.toString()); + } + } + + @Test + public void testTrailingDelimiterOnTwoColumns() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrailingDelimiter())) { + printer.printRecord("A", "B"); + assertEquals("A,B,\r\n", sw.toString()); + } + } + + @Test + public void testTrimOffOneColumn() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim(false))) { + printer.print(" A "); + assertEquals("\" A \"", sw.toString()); + } + } + + @Test + public void testTrimOnOneColumn() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { + printer.print(" A "); + assertEquals("A", sw.toString()); + } + } + + @Test + public void testTrimOnTwoColumns() throws IOException { + final StringWriter sw = new StringWriter(); + try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withTrim())) { + printer.print(" A "); + printer.print(" B "); + assertEquals("A,B", sw.toString()); + } + } + + private String[] toFirstRecordValues(final String expected, final CSVFormat format) throws IOException { + return CSVParser.parse(expected, format).getRecords().get(0).values(); + } + + private void tryFormat(List l, Character quote, Character escape, String expected) throws IOException { + CSVFormat format = CSVFormat.DEFAULT.withQuote(quote).withEscape(escape).withRecordSeparator(null); + Appendable out = new StringBuilder(); + CSVPrinter printer = new CSVPrinter(out, format); + printer.printRecord(l); + printer.close(); + assertEquals(expected, out.toString()); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVRecordTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVRecordTest.java new file mode 100644 index 0000000000..68310027de --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/CSVRecordTest.java @@ -0,0 +1,215 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class CSVRecordTest { + + private enum EnumFixture { + UNKNOWN_COLUMN + } + + private String[] values; + private CSVRecord record, recordWithHeader; + private Map headerMap; + + @BeforeEach + public void setUp() throws Exception { + values = new String[] { "A", "B", "C" }; + final String rowData = StringUtils.join(values, ','); + try (final CSVParser parser = CSVFormat.DEFAULT.parse(new StringReader(rowData))) { + record = parser.iterator().next(); + } + final String[] headers = { "first", "second", "third" }; + try (final CSVParser parser = CSVFormat.DEFAULT.withHeader(headers).parse(new StringReader(rowData))) { + recordWithHeader = parser.iterator().next(); + headerMap = parser.getHeaderMap(); + } + } + + @Test + public void testGetInt() { + assertEquals(values[0], record.get(0)); + assertEquals(values[1], record.get(1)); + assertEquals(values[2], record.get(2)); + } + + @Test + public void testGetString() { + assertEquals(values[0], recordWithHeader.get("first")); + assertEquals(values[1], recordWithHeader.get("second")); + assertEquals(values[2], recordWithHeader.get("third")); + } + + @Test + public void testGetStringInconsistentRecord() { + headerMap.put("fourth", Integer.valueOf(4)); + assertThrows(IllegalArgumentException.class, () -> recordWithHeader.get("fourth")); + } + + @Test + public void testGetStringNoHeader() { + assertThrows(IllegalStateException.class, () -> record.get("first")); + } + + @Test + public void testGetUnmappedEnum() { + assertThrows(IllegalArgumentException.class, () -> recordWithHeader.get(EnumFixture.UNKNOWN_COLUMN)); + } + + @Test + public void testGetUnmappedName() { + assertThrows(IllegalArgumentException.class, () -> assertNull(recordWithHeader.get("fourth"))); + } + + @Test + public void testGetUnmappedNegativeInt() { + assertThrows(ArrayIndexOutOfBoundsException.class, () -> recordWithHeader.get(Integer.MIN_VALUE)); + } + + @Test + public void testGetUnmappedPositiveInt() { + assertThrows(ArrayIndexOutOfBoundsException.class, () -> recordWithHeader.get(Integer.MAX_VALUE)); + } + + @Test + public void testIsConsistent() { + assertTrue(record.isConsistent()); + assertTrue(recordWithHeader.isConsistent()); + final Map map = recordWithHeader.getParser().getHeaderMap(); + map.put("fourth", Integer.valueOf(4)); + // We are working on a copy of the map, so the record should still be OK. + assertTrue(recordWithHeader.isConsistent()); + } + + @Test + public void testIsInconsistent() throws IOException { + final String[] headers = { "first", "second", "third" }; + final String rowData = StringUtils.join(values, ','); + try (final CSVParser parser = CSVFormat.DEFAULT.withHeader(headers).parse(new StringReader(rowData))) { + final Map map = parser.getHeaderMapRaw(); + final CSVRecord record1 = parser.iterator().next(); + map.put("fourth", Integer.valueOf(4)); + assertFalse(record1.isConsistent()); + } + } + + @Test + public void testIsMapped() { + assertFalse(record.isMapped("first")); + assertTrue(recordWithHeader.isMapped("first")); + assertFalse(recordWithHeader.isMapped("fourth")); + } + + @Test + public void testIsSet() { + assertFalse(record.isSet("first")); + assertTrue(recordWithHeader.isSet("first")); + assertFalse(recordWithHeader.isSet("fourth")); + } + + @Test + public void testIterator() { + int i = 0; + for (final String value : record) { + assertEquals(values[i], value); + i++; + } + } + + @Test + public void testPutInMap() { + final Map map = new ConcurrentHashMap<>(); + this.recordWithHeader.putIn(map); + this.validateMap(map, false); + // Test that we can compile with assigment to the same map as the param. + final TreeMap map2 = recordWithHeader.putIn(new TreeMap()); + this.validateMap(map2, false); + } + + @Test + public void testRemoveAndAddColumns() throws IOException { + // do: + try (final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT)) { + final Map map = recordWithHeader.toMap(); + map.remove("OldColumn"); + map.put("ZColumn", "NewValue"); + // check: + final ArrayList list = new ArrayList<>(map.values()); + Collections.sort(list); + printer.printRecord(list); + assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); + } + } + + @Test + public void testToMap() { + final Map map = this.recordWithHeader.toMap(); + this.validateMap(map, true); + } + + @Test + public void testToMapWithShortRecord() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b", CSVFormat.DEFAULT.withHeader("A", "B", "C"))) { + final CSVRecord shortRec = parser.iterator().next(); + shortRec.toMap(); + } + } + + @Test + public void testToMapWithNoHeader() throws Exception { + try (final CSVParser parser = CSVParser.parse("a,b", CSVFormat.newFormat(','))) { + final CSVRecord shortRec = parser.iterator().next(); + final Map map = shortRec.toMap(); + assertNotNull(map, "Map is not null."); + assertTrue(map.isEmpty(), "Map is empty."); + } + } + + private void validateMap(final Map map, final boolean allowsNulls) { + assertTrue(map.containsKey("first")); + assertTrue(map.containsKey("second")); + assertTrue(map.containsKey("third")); + assertFalse(map.containsKey("fourth")); + if (allowsNulls) { + assertFalse(map.containsKey(null)); + } + assertEquals("A", map.get("first")); + assertEquals("B", map.get("second")); + assertEquals("C", map.get("third")); + assertEquals(null, map.get("fourth")); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java new file mode 100644 index 0000000000..a570aec5e2 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java @@ -0,0 +1,210 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.StringReader; + +import org.junit.jupiter.api.Test; + +/** + * + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("")) { + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + } + + @Test + public void testReadLookahead1() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("1\n2\r3\n")) { + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + try (final ExtendedBufferedReader br = createBufferedReader("abcdefg")) { + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + } + + @Test + public void testReadLine() throws Exception { + try (final ExtendedBufferedReader br = createBufferedReader("")) { + assertNull(br.readLine()); + } + try (final ExtendedBufferedReader br = createBufferedReader("\n")) { + assertEquals("", br.readLine()); + assertNull(br.readLine()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\n\nhello")) { + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo", br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("", br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello", br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\n\nhello")) { + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo", br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("", br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello", br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader("foo\rbaar\r\nfoo")) { + assertEquals("foo", br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar", br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo", br.readLine()); + assertNull(br.readLine()); + } + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF = "\n"; + final String CR = "\r"; + final String CRLF = CR + LF; + final String LFCR = LF + CR;// easier to read the string below + final String test = "a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f " + CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + try (final ExtendedBufferedReader br = createBufferedReader(test)) { + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + } + + private ExtendedBufferedReader createBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/LexerTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/LexerTest.java new file mode 100644 index 0000000000..65d930b9c3 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/LexerTest.java @@ -0,0 +1,392 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.BACKSPACE; +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.FF; +import static org.apache.commons.csv.Constants.LF; +import static org.apache.commons.csv.Constants.TAB; +import static org.apache.commons.csv.Token.Type.COMMENT; +import static org.apache.commons.csv.Token.Type.EOF; +import static org.apache.commons.csv.Token.Type.EORECORD; +import static org.apache.commons.csv.Token.Type.TOKEN; +import static org.apache.commons.csv.TokenMatchers.hasContent; +import static org.apache.commons.csv.TokenMatchers.matches; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.StringReader; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * + */ +public class LexerTest { + + private CSVFormat formatWithEscaping; + + @BeforeEach + public void setUp() { + formatWithEscaping = CSVFormat.DEFAULT.withEscape('\\'); + } + + @SuppressWarnings("resource") + private Lexer createLexer(final String input, final CSVFormat format) { + return new Lexer(format, new ExtendedBufferedReader(new StringReader(input))); + } + + @Test + public void testSurroundingSpacesAreDeleted() throws IOException { + final String code = "noSpaces, leadingSpaces,trailingSpaces , surroundingSpaces , ,,"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "noSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingSpaces")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testSurroundingTabsAreDeleted() throws IOException { + final String code = "noTabs,\tleadingTab,trailingTab\t,\tsurroundingTabs\t,\t\t,,"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "noTabs")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "leadingTab")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "trailingTab")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "surroundingTabs")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "first,line,\n" + "\n" + "\n" + "second,line\n" + "\n" + "\n" + "third line \n" + "\n" + + "\n" + "last, line \n" + "\n" + "\n" + "\n"; + final CSVFormat format = CSVFormat.DEFAULT.withIgnoreEmptyLines(); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "third line ")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "last")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, " line ")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testComments() throws IOException { + final String code = "first,line,\n" + "second,line,tokenWith#no-comment\n" + "# comment line \n" + + "third,line,#no-comment\n" + "# penultimate comment\n" + "# Final comment\n"; + final CSVFormat format = CSVFormat.DEFAULT.withCommentMarker('#'); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "first")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "second")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "tokenWith#no-comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "comment line")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "third")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "line")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); + assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + @Test + public void testCommentsAndEmptyLines() throws IOException { + final String code = "1,2,3,\n" + // 1 + "\n" + // 1b + "\n" + // 1c + "a,b x,c#no-comment\n" + // 2 + "#foo\n" + // 3 + "\n" + // 4 + "\n" + // 4b + "d,e,#no-comment\n" + // 5 + "\n" + // 5b + "\n" + // 5c + "# penultimate comment\n" + // 6 + "\n" + // 6b + "\n" + // 6c + "# Final comment\n"; // 7 + final CSVFormat format = CSVFormat.DEFAULT.withCommentMarker('#').withIgnoreEmptyLines(false); + assertFalse(format.getIgnoreEmptyLines(), "Should not ignore empty lines"); + + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "1")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "2")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "3")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 1c + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "b x")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "c#no-comment")); // 2 + assertThat(parser.nextToken(new Token()), matches(COMMENT, "foo")); // 3 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 4b + assertThat(parser.nextToken(new Token()), matches(TOKEN, "d")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "e")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "#no-comment")); // 5 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 5c + assertThat(parser.nextToken(new Token()), matches(COMMENT, "penultimate comment")); // 6 + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6b + assertThat(parser.nextToken(new Token()), matches(EORECORD, "")); // 6c + assertThat(parser.nextToken(new Token()), matches(COMMENT, "Final comment")); // 7 + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + // simple token with escaping not enabled + @Test + public void testBackslashWithoutEscaping() throws IOException { + /* + * file: a,\,,b \,, + */ + final String code = "a,\\,,b\\\n\\,,"; + final CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isEscapeCharacterSet()); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + // an unquoted single backslash is not an escape char + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); + // an unquoted single backslash is not an escape char + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(EOF, "")); + } + } + + // simple token with escaping enabled + @Test + public void testBackslashWithEscaping() throws IOException { + /* + * file: a,\,,b \,, + */ + final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; + final CSVFormat format = formatWithEscaping.withIgnoreEmptyLines(false); + assertTrue(format.isEscapeCharacterSet()); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, ",")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "\nc")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); + assertThat(parser.nextToken(new Token()), matches(EOF, "e")); + } + } + + // encapsulator tokenizer (single line) + @Test + public void testNextToken4() throws IOException { + /* + * file: a,"foo",b a, " foo",b a,"foo " ,b // whitespace after closing encapsulator a, " foo " ,b + */ + final String code = "a,\"foo\",b\na, \" foo\",b\na,\"foo \" ,b\na, \" foo \" ,b"; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces())) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo ")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, " foo ")); + // assertTokenEquals(EORECORD, "b", parser.nextToken(new Token())); + assertThat(parser.nextToken(new Token()), matches(EOF, "b")); + } + } + + // encapsulator tokenizer (multi line, delimiter in string) + @Test + public void testNextToken5() throws IOException { + final String code = "a,\"foo\n\",b\n\"foo\n baar ,,,\"\n\"\n\t \n\""; + try (final Lexer parser = createLexer(code, CSVFormat.DEFAULT)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "foo\n")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "foo\n baar ,,,")); + assertThat(parser.nextToken(new Token()), matches(EOF, "\n\t \n")); + } + } + + // change delimiters, comment, encapsulater + @Test + public void testNextToken6() throws IOException { + /* + * file: a;'b and \' more ' !comment;;;; ;; + */ + final String code = "a;'b and '' more\n'\n!comment;;;;\n;;"; + final CSVFormat format = CSVFormat.DEFAULT.withQuote('\'').withCommentMarker('!').withDelimiter(';'); + try (final Lexer parser = createLexer(code, format)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); + assertThat(parser.nextToken(new Token()), matches(EORECORD, "b and ' more\n")); + } + } + + // From CSV-1 + @Test + public void testDelimiterIsWhitespace() throws IOException { + final String code = "one\ttwo\t\tfour \t five\t six"; + try (final Lexer parser = createLexer(code, CSVFormat.TDF)) { + assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); + assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); + assertThat(parser.nextToken(new Token()), matches(EOF, "six")); + } + } + + @Test + public void testEscapedCR() throws Exception { + try (final Lexer lexer = createLexer("character\\" + CR + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test + public void testCR() throws Exception { + try (final Lexer lexer = createLexer("character" + CR + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character")); + assertThat(lexer.nextToken(new Token()), hasContent("NotEscaped")); + } + } + + @Test + public void testEscapedLF() throws Exception { + try (final Lexer lexer = createLexer("character\\" + LF + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + LF + "Escaped")); + } + } + + @Test + public void testLF() throws Exception { + try (final Lexer lexer = createLexer("character" + LF + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character")); + assertThat(lexer.nextToken(new Token()), hasContent("NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect TAB to be unescaped? + public void testEscapedTab() throws Exception { + try (final Lexer lexer = createLexer("character\\" + TAB + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "Escaped")); + } + + } + + @Test + public void testTab() throws Exception { + try (final Lexer lexer = createLexer("character" + TAB + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + TAB + "NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect BACKSPACE to be unescaped? + public void testEscapedBackspace() throws Exception { + try (final Lexer lexer = createLexer("character\\" + BACKSPACE + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "Escaped")); + } + } + + @Test + public void testBackspace() throws Exception { + try (final Lexer lexer = createLexer("character" + BACKSPACE + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "NotEscaped")); + } + } + + @Test // TODO is this correct? Do we expect FF to be unescaped? + public void testEscapedFF() throws Exception { + try (final Lexer lexer = createLexer("character\\" + FF + "Escaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "Escaped")); + } + } + + @Test + public void testFF() throws Exception { + try (final Lexer lexer = createLexer("character" + FF + "NotEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + FF + "NotEscaped")); + } + } + + @Test + public void testEscapedMySqlNullValue() throws Exception { + // MySQL uses \N to symbolize null values. We have to restore this + try (final Lexer lexer = createLexer("character\\NEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character\\NEscaped")); + } + } + + @Test + public void testEscapedCharacter() throws Exception { + try (final Lexer lexer = createLexer("character\\aEscaped", formatWithEscaping)) { + assertThat(lexer.nextToken(new Token()), hasContent("character\\aEscaped")); + } + } + + @Test + public void testEscapedControlCharacter() throws Exception { + // we are explicitly using an escape different from \ here + try (final Lexer lexer = createLexer("character!rEscaped", CSVFormat.DEFAULT.withEscape('!'))) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test + public void testEscapedControlCharacter2() throws Exception { + try (final Lexer lexer = createLexer("character\\rEscaped", CSVFormat.DEFAULT.withEscape('\\'))) { + assertThat(lexer.nextToken(new Token()), hasContent("character" + CR + "Escaped")); + } + } + + @Test + public void testEscapingAtEOF() throws Exception { + final String code = "escaping at EOF is evil\\"; + try (final Lexer lexer = createLexer(code, formatWithEscaping)) { + assertThrows(IOException.class, () -> lexer.nextToken(new Token())); + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/TokenMatchersTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/TokenMatchersTest.java new file mode 100644 index 0000000000..5c59fe7761 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/TokenMatchersTest.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import static org.apache.commons.csv.TokenMatchers.hasContent; +import static org.apache.commons.csv.TokenMatchers.hasType; +import static org.apache.commons.csv.TokenMatchers.isReady; +import static org.apache.commons.csv.TokenMatchers.matches; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TokenMatchersTest { + + private Token token; + + @BeforeEach + public void setUp() { + token = new Token(); + token.type = Token.Type.TOKEN; + token.isReady = true; + token.content.append("content"); + } + + @Test + public void testHasType() { + assertFalse(hasType(Token.Type.COMMENT).matches(token)); + assertFalse(hasType(Token.Type.EOF).matches(token)); + assertFalse(hasType(Token.Type.EORECORD).matches(token)); + assertTrue(hasType(Token.Type.TOKEN).matches(token)); + } + + @Test + public void testHasContent() { + assertFalse(hasContent("This is not the token's content").matches(token)); + assertTrue(hasContent("content").matches(token)); + } + + @Test + public void testIsReady() { + assertTrue(isReady().matches(token)); + token.isReady = false; + assertFalse(isReady().matches(token)); + } + + @Test + public void testMatches() { + assertTrue(matches(Token.Type.TOKEN, "content").matches(token)); + assertFalse(matches(Token.Type.EOF, "content").matches(token)); + assertFalse(matches(Token.Type.TOKEN, "not the content").matches(token)); + assertFalse(matches(Token.Type.EORECORD, "not the content").matches(token)); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/Utils.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/Utils.java new file mode 100644 index 0000000000..2b4d310aa3 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/Utils.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.commons.csv; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +/** + * Utility methods for test cases + */ +final class Utils { + + private Utils() { + } + + /** + * Checks if the 2d array has the same contents as the list of records. + * + * @param message the message to be displayed + * @param expected the 2d array of expected results + * @param actual the List of {@link CSVRecord} entries, each containing an array of values + */ + public static void compare(final String message, final String[][] expected, final List actual) { + assertEquals(expected.length, actual.size(), message + " - outer array size"); + for (int i = 0; i < expected.length; i++) { + assertArrayEquals(expected[i], actual.get(i).values(), message + " (entry " + i + ")"); + } + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java new file mode 100644 index 0000000000..a689a61a63 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv164Test.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.junit.jupiter.api.Test; + +public class JiraCsv164Test { + + @Test + public void testJiraCsv154_withCommentMarker() throws IOException { + final String comment = "This is a header comment"; + final CSVFormat format = CSVFormat.EXCEL.withHeader("H1", "H2").withCommentMarker('#') + .withHeaderComments(comment); + final StringBuilder out = new StringBuilder(); + try (final CSVPrinter printer = format.print(out)) { + printer.print("A"); + printer.print("B"); + } + final String s = out.toString(); + assertTrue(s.contains(comment), s); + } + + @Test + public void testJiraCsv154_withHeaderComments() throws IOException { + final String comment = "This is a header comment"; + final CSVFormat format = CSVFormat.EXCEL.withHeader("H1", "H2").withHeaderComments(comment) + .withCommentMarker('#'); + final StringBuilder out = new StringBuilder(); + try (final CSVPrinter printer = format.print(out)) { + printer.print("A"); + printer.print("B"); + } + final String s = out.toString(); + assertTrue(s.contains(comment), s); + } + +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java new file mode 100644 index 0000000000..0e6e49fbe0 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv167Test.java @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.csv.QuoteMode; +import org.junit.jupiter.api.Test; + +public class JiraCsv167Test { + + @Test + public void parse() throws IOException { + int totcomment = 0; + int totrecs = 0; + try (final BufferedReader br = new BufferedReader(getTestInput())) { + String s = null; + boolean lastWasComment = false; + while ((s = br.readLine()) != null) { + if (s.startsWith("#")) { + if (!lastWasComment) { // comments are merged + totcomment++; + } + lastWasComment = true; + } else { + totrecs++; + lastWasComment = false; + } + } + } + CSVFormat format = CSVFormat.DEFAULT; + // + format = format.withAllowMissingColumnNames(false); + format = format.withCommentMarker('#'); + format = format.withDelimiter(','); + format = format.withEscape('\\'); + format = format.withHeader("author", "title", "publishDate"); + format = format.withHeaderComments("headerComment"); + format = format.withNullString("NULL"); + format = format.withIgnoreEmptyLines(true); + format = format.withIgnoreSurroundingSpaces(true); + format = format.withQuote('"'); + format = format.withQuoteMode(QuoteMode.ALL); + format = format.withRecordSeparator('\n'); + format = format.withSkipHeaderRecord(false); + // + int comments = 0; + int records = 0; + try (final CSVParser parser = format.parse(getTestInput())) { + for (final CSVRecord csvRecord : parser) { + records++; + if (csvRecord.hasComment()) { + comments++; + } + } + } + // Comment lines are concatenated, in this example 4 lines become 2 comments. + assertEquals(totcomment, comments); + assertEquals(totrecs, records); // records includes the header + } + + private Reader getTestInput() { + final InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("csv-167/sample1.csv"); + return new InputStreamReader(is); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java new file mode 100644 index 0000000000..f97c48d05a --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv198Test.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.junit.jupiter.api.Test; + +public class JiraCsv198Test { + + private static final CSVFormat CSV_FORMAT = CSVFormat.EXCEL.withDelimiter('^').withFirstRecordAsHeader(); + + @Test + public void test() throws UnsupportedEncodingException, IOException { + final InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); + assertNotNull(pointsOfReference); + try (@SuppressWarnings("resource") + CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8"))) { + for (final CSVRecord record : parser) { + final String locationType = record.get("location_type"); + assertNotNull(locationType); + } + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java new file mode 100644 index 0000000000..bb11625026 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv203Test.java @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.QuoteMode; +import org.junit.jupiter.api.Test; + +/** + * JIRA: withNullString value is printed without quotes when QuoteMode.ALL is specified + */ +public class JiraCsv203Test { + + @Test + public void testQuoteModeAll() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("\"N/A\",\"Hello\",\"N/A\",\"World\"\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeAllNonNull() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL_NON_NULL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("N/A,\"Hello\",N/A,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithoutQuoteMode() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("N/A,Hello,N/A,World\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeMinimal() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.MINIMAL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("N/A,Hello,N/A,World\r\n", buffer.toString()); + } + + @Test + public void testQuoteModeNonNumeric() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.NON_NUMERIC); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("N/A,\"Hello\",N/A,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithoutNullString() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + //.withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals(",\"Hello\",,\"World\"\r\n", buffer.toString()); + } + + @Test + public void testWithEmptyValues() throws Exception { + final CSVFormat format = CSVFormat.EXCEL + .withNullString("N/A") + .withIgnoreSurroundingSpaces(true) + .withQuoteMode(QuoteMode.ALL); + + final StringBuffer buffer = new StringBuffer(); + try (final CSVPrinter printer = new CSVPrinter(buffer, format)) { + printer.printRecord(new Object[] { "", "Hello", "", "World" }); + //printer.printRecord(new Object[] { null, "Hello", null, "World" }); + } + assertEquals("\"\",\"Hello\",\"\",\"World\"\r\n", buffer.toString()); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java new file mode 100644 index 0000000000..30e9403307 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCsv213Test.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv.issues; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.csv.QuoteMode; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Tests https://issues.apache.org/jira/browse/CSV-213 + * + * This is normal behavior with the current architecture: The iterator() API presents an object that is backed by data + * in the CSVParser as the parser is streaming over the file. The CSVParser is like a forward-only stream. When you + * create a new Iterator you are only created a new view on the same position in the parser's stream. For the behavior + * you want, you need to open a new CSVParser. + */ +@Disabled +public class JiraCsv213Test { + + private void createEndChannel(final File csvFile) { + // @formatter:off + final CSVFormat csvFormat = + CSVFormat.DEFAULT + .withDelimiter(';') + .withFirstRecordAsHeader() + .withRecordSeparator('\n') + .withQuoteMode(QuoteMode.ALL); + // @formatter:on + try (CSVParser parser = csvFormat + .parse(new InputStreamReader(new FileInputStream(csvFile), StandardCharsets.UTF_8))) { + if (parser.iterator().hasNext()) { + System.out.println(parser.getCurrentLineNumber()); + System.out.println(parser.getRecordNumber()); + // get only first record we don't need other's + final CSVRecord firstRecord = parser.iterator().next(); // this fails + + return; + } + } catch (final IOException e) { + throw new IllegalStateException("Error while adding end channel to csv", e); + } + + return; + } + + @Test + public void test() { + createEndChannel(new File("src/test/resources/CSV-213/999751170.patch.csv")); + } +} diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java new file mode 100644 index 0000000000..760f6a27f1 --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/issues/JiraCvs249Test.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv.issues; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.List; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +import org.junit.jupiter.api.Test; + +public class JiraCvs249Test { + + @Test + public void testJiraCsv249() throws IOException { + + final CSVFormat csvFormat = CSVFormat.DEFAULT.withEscape('\\'); + + final StringWriter stringWriter = new StringWriter(); + + try (CSVPrinter printer = new CSVPrinter(stringWriter, csvFormat)) { + printer.printRecord("foo \\", "bar"); + } + final StringReader stringReader = new StringReader(stringWriter.toString()); + List records; + try (CSVParser parser = new CSVParser(stringReader, csvFormat)) { + records = parser.getRecords(); + } + + records.forEach(record -> { + assertEquals("foo \\", record.get(0)); + assertEquals("bar", record.get(1)); + }); + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java new file mode 100644 index 0000000000..d35f59845c --- /dev/null +++ b/src/test/resources/oracle/commits/commons-csv-e2f0a4d8a83a41eaa984086636a3712c682307ea/src/test/java/org/apache/commons/csv/perf/PerformanceTest.java @@ -0,0 +1,129 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv.perf; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.util.zip.GZIPInputStream; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; +import org.apache.commons.io.IOUtils; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * Tests performance. + * + * To run this test, use: mvn test -Dtest=PeformanceTest + */ +@SuppressWarnings("boxing") // test code +public class PerformanceTest { + + private final int max = 10; + + private static final File BIG_FILE = new File(System.getProperty("java.io.tmpdir"), "worldcitiespop.txt"); + + @BeforeAll + public static void setUpClass() throws FileNotFoundException, IOException { + if (BIG_FILE.exists()) { + System.out.println(String.format("Found test fixture %s: %,d bytes.", BIG_FILE, BIG_FILE.length())); + return; + } + System.out.println("Decompressing test fixture " + BIG_FILE + "..."); + try (final InputStream input = new GZIPInputStream( + new FileInputStream("src/test/resources/perf/worldcitiespop.txt.gz")); + final OutputStream output = new FileOutputStream(BIG_FILE)) { + IOUtils.copy(input, output); + System.out.println(String.format("Decompressed test fixture %s: %,d bytes.", BIG_FILE, BIG_FILE.length())); + } + } + + private BufferedReader createBufferedReader() throws IOException { + return new BufferedReader(new FileReader(BIG_FILE)); + } + + private long parse(final Reader in, final boolean traverseColumns) throws IOException { + final CSVFormat format = CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(false); + long recordCount = 0; + for (final CSVRecord record : format.parse(in)) { + recordCount++; + if (traverseColumns) { + for (@SuppressWarnings("unused") final String value : record) { + // do nothing for now + } + } + } + return recordCount; + } + + private void println(final String s) { + System.out.println(s); + } + + private long readAll(final BufferedReader in) throws IOException { + long count = 0; + while (in.readLine() != null) { + count++; + } + return count; + } + + public long testParseBigFile(final boolean traverseColumns) throws Exception { + final long startMillis = System.currentTimeMillis(); + final long count = this.parse(this.createBufferedReader(), traverseColumns); + final long totalMillis = System.currentTimeMillis() - startMillis; + this.println(String.format("File parsed in %,d milliseconds with Commons CSV: %,d lines.", totalMillis, count)); + return totalMillis; + } + + @Test + public void testParseBigFileRepeat() throws Exception { + long bestTime = Long.MAX_VALUE; + for (int i = 0; i < this.max; i++) { + bestTime = Math.min(this.testParseBigFile(false), bestTime); + } + this.println(String.format("Best time out of %,d is %,d milliseconds.", this.max, bestTime)); + } + + @Test + public void testReadBigFile() throws Exception { + long bestTime = Long.MAX_VALUE; + for (int i = 0; i < this.max; i++) { + final long startMillis; + long count; + try (final BufferedReader in = this.createBufferedReader()) { + startMillis = System.currentTimeMillis(); + count = 0; + count = this.readAll(in); + } + final long totalMillis = System.currentTimeMillis() - startMillis; + bestTime = Math.min(totalMillis, bestTime); + this.println(String.format("File read in %,d milliseconds: %,d lines.", totalMillis, count)); + } + this.println(String.format("Best time out of %,d is %,d milliseconds.", this.max, bestTime)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.json b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.json new file mode 100644 index 0000000000..d90e6c060f --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c.json @@ -0,0 +1 @@ +{"parentCommitId":"61c50a6c834c1c0f2e57945d1f0828078b647806","currentCommitId":"340f23ef88a32ceb8341820c15bfd9537303219c","filesBefore":["src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java","src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java","src/test/java/com/lmax/disruptor/RingBufferTest.java","src/test/java/com/lmax/disruptor/SequenceBarrierTest.java","src/test/java/com/lmax/disruptor/SequencerTest.java","src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java"],"filesCurrent":["src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java","src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java","src/test/java/com/lmax/disruptor/RingBufferTest.java","src/test/java/com/lmax/disruptor/SequenceBarrierTest.java","src/test/java/com/lmax/disruptor/SequencerTest.java","src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["src/test/java","src/test/java/com/lmax/disruptor","src/test","src","src/test/java/com","src/test/java/com/lmax"],"repositoryDirectoriesCurrent":["src/test/java","src/test/java/com/lmax/disruptor","src/test","src","src/test/java/com","src/test/java/com/lmax"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java new file mode 100644 index 0000000000..158e397a6d --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.TestEvent; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public final class FatalExceptionHandlerTest +{ + @Test + public void shouldHandleFatalException() + { + final Exception causeException = new Exception(); + final TestEvent event = new TestEvent(); + + ExceptionHandler exceptionHandler = new FatalExceptionHandler(); + + Throwable ex = assertThrows(RuntimeException.class, () -> exceptionHandler.handleEventException(causeException, 0L, event)); + + assertEquals(causeException, ex.getCause()); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java new file mode 100644 index 0000000000..365f77c15f --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java @@ -0,0 +1,32 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummySequenceBarrier; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class LiteTimeoutBlockingWaitStrategyTest +{ + @Test + public void shouldTimeoutWaitFor() + { + final SequenceBarrier sequenceBarrier = new DummySequenceBarrier(); + + long theTimeout = 500; + LiteTimeoutBlockingWaitStrategy waitStrategy = new LiteTimeoutBlockingWaitStrategy(theTimeout, TimeUnit.MILLISECONDS); + Sequence cursor = new Sequence(5); + + long t0 = System.currentTimeMillis(); + + assertThrows(TimeoutException.class, () -> waitStrategy.waitFor(6, cursor, cursor, sequenceBarrier)); + + long t1 = System.currentTimeMillis(); + + long timeWaiting = t1 - t0; + + assertTrue(timeWaiting >= theTimeout); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/RingBufferTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/RingBufferTest.java new file mode 100644 index 0000000000..6fb9597573 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/RingBufferTest.java @@ -0,0 +1,1605 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.StubEvent; +import com.lmax.disruptor.support.TestWaiter; +import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.lmax.disruptor.RingBuffer.createMultiProducer; +import static com.lmax.disruptor.RingBufferEventMatcher.ringBufferWithEvents; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RingBufferTest +{ + private final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE); + private final RingBuffer ringBuffer = RingBuffer.createMultiProducer(StubEvent.EVENT_FACTORY, 32); + private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + { + ringBuffer.addGatingSequences(new NoOpEventProcessor(ringBuffer).getSequence()); + } + + @Test + public void shouldClaimAndGet() throws Exception + { + assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, ringBuffer.getCursor()); + + StubEvent expectedEvent = new StubEvent(2701); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, expectedEvent.getValue(), expectedEvent.getTestString()); + + long sequence = sequenceBarrier.waitFor(0); + assertEquals(0, sequence); + + StubEvent event = ringBuffer.get(sequence); + assertEquals(expectedEvent, event); + + assertEquals(0L, ringBuffer.getCursor()); + } + + @Test + public void shouldClaimAndGetInSeparateThread() throws Exception + { + Future> messages = getMessages(0, 0); + + StubEvent expectedEvent = new StubEvent(2701); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, expectedEvent.getValue(), expectedEvent.getTestString()); + + assertEquals(expectedEvent, messages.get().get(0)); + } + + @Test + public void shouldClaimAndGetMultipleMessages() throws Exception + { + int numMessages = ringBuffer.getBufferSize(); + for (int i = 0; i < numMessages; i++) + { + ringBuffer.publishEvent(StubEvent.TRANSLATOR, i, ""); + } + + long expectedSequence = numMessages - 1; + long available = sequenceBarrier.waitFor(expectedSequence); + assertEquals(expectedSequence, available); + + for (int i = 0; i < numMessages; i++) + { + assertEquals(i, ringBuffer.get(i).getValue()); + } + } + + @Test + public void shouldWrap() throws Exception + { + int numMessages = ringBuffer.getBufferSize(); + int offset = 1000; + for (int i = 0; i < numMessages + offset; i++) + { + ringBuffer.publishEvent(StubEvent.TRANSLATOR, i, ""); + } + + long expectedSequence = numMessages + offset - 1; + long available = sequenceBarrier.waitFor(expectedSequence); + assertEquals(expectedSequence, available); + + for (int i = offset; i < numMessages + offset; i++) + { + assertEquals(i, ringBuffer.get(i).getValue()); + } + } + + @Test + public void shouldPreventWrapping() throws Exception + { + Sequence sequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE); + final RingBuffer ringBuffer = createMultiProducer(StubEvent.EVENT_FACTORY, 4); + ringBuffer.addGatingSequences(sequence); + + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 0, "0"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 1, "1"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 2, "2"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 3, "3"); + + assertFalse(ringBuffer.tryPublishEvent(StubEvent.TRANSLATOR, 3, "3")); + } + + @Test + public void shouldThrowExceptionIfBufferIsFull() throws Exception + { + ringBuffer.addGatingSequences(new Sequence(ringBuffer.getBufferSize())); + + for (int i = 0; i < ringBuffer.getBufferSize(); i++) + { + ringBuffer.publish(ringBuffer.tryNext()); + } + + assertThrows(InsufficientCapacityException.class, ringBuffer::tryNext); + } + + @Test + public void shouldPreventPublishersOvertakingEventProcessorWrapPoint() throws InterruptedException + { + final int ringBufferSize = 16; + final CountDownLatch latch = new CountDownLatch(ringBufferSize); + final AtomicBoolean publisherComplete = new AtomicBoolean(false); + final RingBuffer buffer2 = createMultiProducer(StubEvent.EVENT_FACTORY, ringBufferSize); + final TestEventProcessor processor = new TestEventProcessor(buffer2.newBarrier()); + buffer2.addGatingSequences(processor.getSequence()); + + Thread thread = new Thread( + () -> + { + // Attempt to put in enough events to wrap around the ringbuffer + for (int i = 0; i < ringBufferSize + 1; i++) + { + long sequence = buffer2.next(); + StubEvent event = buffer2.get(sequence); + event.setValue(i); + buffer2.publish(sequence); + latch.countDown(); + } + + // Only marked complete after enough events published that the ringbuffer must have wrapped + publisherComplete.set(true); + }); + thread.start(); + + latch.await(); + + // Publisher should not be complete, blocked at RingBuffer::next + assertFalse(publisherComplete.get()); + + // Run the processor, freeing up entries in the ringbuffer for the producer to continue and "complete" + processor.run(); + thread.join(); + + // Check producer completes, ideally this should be in some kind of waiter + assertTrue(publisherComplete.get()); + } + + @Test + public void shouldPublishEvent() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator translator = new NoArgEventTranslator(); + + ringBuffer.publishEvent(translator); + ringBuffer.tryPublishEvent(translator); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L)); + } + + @Test + public void shouldPublishEventOneArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo"); + ringBuffer.tryPublishEvent(translator, "Foo"); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1")); + } + + @Test + public void shouldPublishEventTwoArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBar-0", "FooBar-1")); + } + + @Test + public void shouldPublishEventThreeArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar", "Baz"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar", "Baz"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBaz-0", "FooBarBaz-1")); + } + + @Test + public void shouldPublishEventVarArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar", "Baz", "Bam"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar", "Baz", "Bam"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBazBam-0", "FooBarBazBam-1")); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEvents() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = new EventTranslator[]{eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators); + assertTrue(ringBuffer.tryPublishEvents(translators)); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L, 2L, 3L)); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator, eventTranslator, eventTranslator}; + + try + { + ringBuffer.tryPublishEvents(translators); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEventsWithBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators, 0, 1); + assertTrue(ringBuffer.tryPublishEvents(translators, 0, 1)); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) 0L), is((Object) 1L), is(nullValue()), is( + nullValue()))); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEventsWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators, 1, 2); + assertTrue(ringBuffer.tryPublishEvents(translators, 1, 2)); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L, 2L, 3L)); + } + + @Test + public void shouldPublishEventsOneArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, new String[]{"Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo"})); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1", "Foo-2", "Foo-3")); + } + + @Test + public void shouldNotPublishEventsOneArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsOneArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, 0, 1, new String[]{"Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, 0, 1, new String[]{"Foo", "Foo"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "Foo-0"), is((Object) "Foo-1"), is(nullValue()), is( + nullValue()))); + } + + @Test + public void shouldPublishEventsOneArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, 1, 2, new String[]{"Foo", "Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, 1, 2, new String[]{"Foo", "Foo", "Foo"})); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1", "Foo-2", "Foo-3")); + } + + @Test + public void shouldPublishEventsTwoArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents(translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + + assertThat(ringBuffer, ringBufferWithEvents("FooBar-0", "FooBar-1", "FooBar-2", "FooBar-3")); + } + + @Test + public void shouldNotPublishEventsITwoArgIfBatchSizeIsBiggerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}, + new String[]{"Bar", "Bar", "Bar", "Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsTwoArgWithBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents(translator, 0, 1, new String[]{"Foo0", "Foo1"}, new String[]{"Bar0", "Bar1"}); + ringBuffer.tryPublishEvents(translator, 0, 1, new String[]{"Foo2", "Foo3"}, new String[]{"Bar2", "Bar3"}); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "Foo0Bar0-0"), is((Object) "Foo2Bar2-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsTwoArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Foo1", "Foo2"}, new String[]{"Bar0", "Bar1", "Bar2"}); + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Foo4", "Foo5"}, new String[]{"Bar3", "Bar4", "Bar5"}); + + assertThat(ringBuffer, ringBufferWithEvents("Foo1Bar1-0", "Foo2Bar2-1", "Foo4Bar4-2", "Foo5Bar5-3")); + } + + @Test + public void shouldPublishEventsThreeArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + ringBuffer.tryPublishEvents( + translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBaz-0", "FooBarBaz-1", "FooBarBaz-2", "FooBarBaz-3")); + } + + @Test + public void shouldNotPublishEventsThreeArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}, + new String[]{"Bar", "Bar", "Bar", "Bar", "Bar"}, + new String[]{"Baz", "Baz", "Baz", "Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsThreeArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 0, 1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + ringBuffer.tryPublishEvents( + translator, 0, 1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "FooBarBaz-0"), is((Object) "FooBarBaz-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsThreeArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Foo1", "Foo2"}, new String[]{"Bar0", "Bar1", "Bar2"}, + new String[]{"Baz0", "Baz1", "Baz2"} + ); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Foo4", "Foo5"}, new String[]{"Bar3", "Bar4", "Bar5"}, + new String[]{"Baz3", "Baz4", "Baz5"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "Foo1Bar1Baz1-0", "Foo2Bar2Baz2-1", "Foo4Bar4Baz4-2", "Foo5Bar5Baz5-3")); + } + + @Test + public void shouldPublishEventsVarArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "FooBarBazBam-0", "FooBarBazBam-1", "FooBarBazBam-2", "FooBarBazBam-3")); + } + + @Test + public void shouldNotPublishEventsVarArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsVarArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 0, 1, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 0, 1, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "FooBarBazBam-0"), is((Object) "FooBarBazBam-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsVarArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, + new String[]{"Foo2", "Bar2", "Baz2", "Bam2"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Bar3", "Baz3", "Bam3"}, + new String[]{"Foo4", "Bar4", "Baz4", "Bam4"}, + new String[]{"Foo5", "Bar5", "Baz5", "Bam5"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "Foo1Bar1Baz1Bam1-0", "Foo2Bar2Baz2Bam2-1", "Foo4Bar4Baz4Bam4-2", "Foo5Bar5Baz5Bam5-3")); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, 0); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, 0); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator}, 1, 3); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator}, 1, 3); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, -1); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, -1); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, -1, 2); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, -1, 2); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + try + { + ringBuffer.publishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + assertFalse(ringBuffer.tryPublishEvents(translator, 1, -1, new String[]{"Foo", "Foo"})); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + try + { + ringBuffer.publishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 0, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, -1, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, -1, 2, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 0, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 0, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, + new String[]{"Foo2", "Bar2", "Baz2", "Bam2"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 3, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, -1, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, -1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 3, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, -1, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, -1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldAddAndRemoveSequences() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 16); + + Sequence sequenceThree = new Sequence(-1); + Sequence sequenceSeven = new Sequence(-1); + ringBuffer.addGatingSequences(sequenceThree, sequenceSeven); + + for (int i = 0; i < 10; i++) + { + ringBuffer.publish(ringBuffer.next()); + } + + sequenceThree.set(3); + sequenceSeven.set(7); + + assertThat(ringBuffer.getMinimumGatingSequence(), is(3L)); + assertTrue(ringBuffer.removeGatingSequence(sequenceThree)); + assertThat(ringBuffer.getMinimumGatingSequence(), is(7L)); + } + + @Test + public void shouldHandleResetToAndNotWrapUnnecessarilySingleProducer() throws Exception + { + assertHandleResetAndNotWrap(RingBuffer.createSingleProducer(StubEvent.EVENT_FACTORY, 4)); + } + + @Test + public void shouldHandleResetToAndNotWrapUnnecessarilyMultiProducer() throws Exception + { + assertHandleResetAndNotWrap(RingBuffer.createMultiProducer(StubEvent.EVENT_FACTORY, 4)); + } + + @SuppressWarnings("deprecation") + private void assertHandleResetAndNotWrap(final RingBuffer rb) + { + Sequence sequence = new Sequence(); + rb.addGatingSequences(sequence); + + for (int i = 0; i < 128; i++) + { + rb.publish(rb.next()); + sequence.incrementAndGet(); + } + + assertThat(rb.getCursor(), is(127L)); + + rb.resetTo(31); + sequence.set(31); + + for (int i = 0; i < 4; i++) + { + rb.publish(rb.next()); + } + + assertThat(rb.hasAvailableCapacity(1), is(false)); + } + + private Future> getMessages(final long initial, final long toWaitFor) throws InterruptedException, + BrokenBarrierException + { + final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + final Future> f = executor.submit( + new TestWaiter( + cyclicBarrier, sequenceBarrier, ringBuffer, + initial, toWaitFor)); + + cyclicBarrier.await(); + + return f; + } + + private void assertEmptyRingBuffer(final RingBuffer ringBuffer) + { + assertThat(ringBuffer.get(0)[0], is(nullValue())); + assertThat(ringBuffer.get(1)[0], is(nullValue())); + assertThat(ringBuffer.get(2)[0], is(nullValue())); + assertThat(ringBuffer.get(3)[0], is(nullValue())); + } + + private static final class TestEventProcessor implements EventProcessor + { + private final SequenceBarrier sequenceBarrier; + private final Sequence sequence = new Sequence(SingleProducerSequencer.INITIAL_CURSOR_VALUE); + private final AtomicBoolean running = new AtomicBoolean(); + + + TestEventProcessor(final SequenceBarrier sequenceBarrier) + { + this.sequenceBarrier = sequenceBarrier; + } + + @Override + public Sequence getSequence() + { + return sequence; + } + + @Override + public void halt() + { + running.set(false); + } + + @Override + public boolean isRunning() + { + return running.get(); + } + + @Override + public void run() + { + if (!running.compareAndSet(false, true)) + { + throw new IllegalStateException("Already running"); + } + try + { + sequenceBarrier.waitFor(0L); + } + catch (Exception ex) + { + throw new RuntimeException(ex); + } + + sequence.set(sequence.get() + 1L); + } + } + + private static class ArrayFactory implements EventFactory + { + private final int size; + + ArrayFactory(final int size) + { + this.size = size; + } + + @Override + public Object[] newInstance() + { + return new Object[size]; + } + } + + private static class NoArgEventTranslator implements EventTranslator + { + @Override + public void translateTo(final Object[] event, final long sequence) + { + event[0] = sequence; + } + } + + private static class VarArgEventTranslator implements EventTranslatorVararg + { + @Override + public void translateTo(final Object[] event, final long sequence, final Object... args) + { + event[0] = (String) args[0] + args[1] + args[2] + args[3] + "-" + sequence; + } + } + + private static class ThreeArgEventTranslator implements EventTranslatorThreeArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0, final String arg1, final String arg2) + { + event[0] = arg0 + arg1 + arg2 + "-" + sequence; + } + } + + private static class TwoArgEventTranslator implements EventTranslatorTwoArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0, final String arg1) + { + event[0] = arg0 + arg1 + "-" + sequence; + } + } + + private static class OneArgEventTranslator implements EventTranslatorOneArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0) + { + event[0] = arg0 + "-" + sequence; + } + } +} diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java new file mode 100644 index 0000000000..876252d7d3 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java @@ -0,0 +1,191 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummyEventProcessor; +import com.lmax.disruptor.support.StubEvent; +import com.lmax.disruptor.util.Util; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static com.lmax.disruptor.RingBuffer.createMultiProducer; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public final class SequenceBarrierTest +{ + private final RingBuffer ringBuffer = createMultiProducer(StubEvent.EVENT_FACTORY, 64); + + public SequenceBarrierTest() + { + ringBuffer.addGatingSequences(new NoOpEventProcessor(ringBuffer).getSequence()); + } + + @Test + public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsAhead() throws Exception + { + final long expectedNumberMessages = 10; + final long expectedWorkSequence = 9; + fillRingBuffer(expectedNumberMessages); + + final Sequence sequence1 = new Sequence(expectedNumberMessages); + final Sequence sequence2 = new Sequence(expectedWorkSequence); + final Sequence sequence3 = new Sequence(expectedNumberMessages); + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(sequence1, sequence2, sequence3); + + long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldWaitForWorkCompleteWhereAllWorkersAreBlockedOnRingBuffer() throws Exception + { + long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final DummyEventProcessor[] workers = new DummyEventProcessor[3]; + for (int i = 0, size = workers.length; i < size; i++) + { + workers[i] = new DummyEventProcessor(); + workers[i].setSequence(expectedNumberMessages - 1); + } + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(Util.getSequencesFor(workers)); + + Runnable runnable = () -> + { + long sequence = ringBuffer.next(); + StubEvent event = ringBuffer.get(sequence); + event.setValue((int) sequence); + ringBuffer.publish(sequence); + + for (DummyEventProcessor stubWorker : workers) + { + stubWorker.setSequence(sequence); + } + }; + + new Thread(runnable).start(); + + long expectedWorkSequence = expectedNumberMessages; + long completedWorkSequence = sequenceBarrier.waitFor(expectedNumberMessages); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldInterruptDuringBusySpin() throws Exception + { + final long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final CountDownLatch latch = new CountDownLatch(3); + final Sequence sequence1 = new CountDownLatchSequence(8L, latch); + final Sequence sequence2 = new CountDownLatchSequence(8L, latch); + final Sequence sequence3 = new CountDownLatchSequence(8L, latch); + + final SequenceBarrier sequenceBarrier = + ringBuffer.newBarrier(sequence1, sequence2, sequence3); + + Thread t = new Thread( + () -> assertThrows(AlertException.class, () -> + sequenceBarrier.waitFor(expectedNumberMessages - 1))); + + t.start(); + latch.await(3, TimeUnit.SECONDS); + sequenceBarrier.alert(); + t.join(); + } + + @Test + public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsBehind() throws Exception + { + long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final DummyEventProcessor[] eventProcessors = new DummyEventProcessor[3]; + for (int i = 0, size = eventProcessors.length; i < size; i++) + { + eventProcessors[i] = new DummyEventProcessor(); + eventProcessors[i].setSequence(expectedNumberMessages - 2); + } + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(Util.getSequencesFor(eventProcessors)); + + Runnable runnable = () -> + { + for (DummyEventProcessor stubWorker : eventProcessors) + { + stubWorker.setSequence(stubWorker.getSequence().get() + 1L); + } + }; + + Thread thread = new Thread(runnable); + thread.start(); + thread.join(); + + long expectedWorkSequence = expectedNumberMessages - 1; + long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldSetAndClearAlertStatus() + { + SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + assertFalse(sequenceBarrier.isAlerted()); + + sequenceBarrier.alert(); + assertTrue(sequenceBarrier.isAlerted()); + + sequenceBarrier.clearAlert(); + assertFalse(sequenceBarrier.isAlerted()); + } + + private void fillRingBuffer(final long expectedNumberMessages) throws InterruptedException + { + for (long i = 0; i < expectedNumberMessages; i++) + { + long sequence = ringBuffer.next(); + StubEvent event = ringBuffer.get(sequence); + event.setValue((int) i); + ringBuffer.publish(sequence); + } + } + + private static final class CountDownLatchSequence extends Sequence + { + private final CountDownLatch latch; + + private CountDownLatchSequence(final long initialValue, final CountDownLatch latch) + { + super(initialValue); + this.latch = latch; + } + + @Override + public long get() + { + latch.countDown(); + return super.get(); + } + } +} diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequencerTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequencerTest.java new file mode 100644 index 0000000000..775c2b73f1 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/SequencerTest.java @@ -0,0 +1,315 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.dsl.ProducerType; +import com.lmax.disruptor.support.DummyWaitStrategy; +import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class SequencerTest +{ + private static final int BUFFER_SIZE = 16; + private final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE); + private final Sequence gatingSequence = new Sequence(); + + private static Stream sequencerGenerator() + { + return Stream.of( + arguments(newProducer(ProducerType.SINGLE, new BlockingWaitStrategy())), + arguments(newProducer(ProducerType.MULTI, new BlockingWaitStrategy())) + ); + } + + private static Stream producerTypeGenerator() + { + return Stream.of(arguments(ProducerType.SINGLE), arguments(ProducerType.MULTI)); + } + + private static Sequencer newProducer(final ProducerType producerType, final WaitStrategy waitStrategy) + { + switch (producerType) + { + case SINGLE: + return new SingleProducerSequencer(BUFFER_SIZE, waitStrategy); + case MULTI: + return new MultiProducerSequencer(BUFFER_SIZE, waitStrategy); + default: + throw new IllegalStateException(producerType.toString()); + } + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldStartWithInitialValue(final Sequencer sequencer) + { + assertEquals(0, sequencer.next()); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldBatchClaim(final Sequencer sequencer) + { + assertEquals(3, sequencer.next(4)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldIndicateHasAvailableCapacity(final Sequencer sequencer) + { + sequencer.addGatingSequences(gatingSequence); + + assertTrue(sequencer.hasAvailableCapacity(1)); + assertTrue(sequencer.hasAvailableCapacity(BUFFER_SIZE)); + assertFalse(sequencer.hasAvailableCapacity(BUFFER_SIZE + 1)); + + sequencer.publish(sequencer.next()); + + assertTrue(sequencer.hasAvailableCapacity(BUFFER_SIZE - 1)); + assertFalse(sequencer.hasAvailableCapacity(BUFFER_SIZE)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldIndicateNoAvailableCapacity(final Sequencer sequencer) + { + sequencer.addGatingSequences(gatingSequence); + long sequence = sequencer.next(BUFFER_SIZE); + sequencer.publish(sequence - (BUFFER_SIZE - 1), sequence); + + assertFalse(sequencer.hasAvailableCapacity(1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldHoldUpPublisherWhenBufferIsFull(final Sequencer sequencer) + throws InterruptedException + { + sequencer.addGatingSequences(gatingSequence); + long sequence = sequencer.next(BUFFER_SIZE); + sequencer.publish(sequence - (BUFFER_SIZE - 1), sequence); + + final CountDownLatch waitingLatch = new CountDownLatch(1); + final CountDownLatch doneLatch = new CountDownLatch(1); + + final long expectedFullSequence = Sequencer.INITIAL_CURSOR_VALUE + sequencer.getBufferSize(); + assertThat( + sequencer.getHighestPublishedSequence(Sequencer.INITIAL_CURSOR_VALUE + 1, sequencer.getCursor()), + is(expectedFullSequence)); + + executor.submit( + () -> + { + waitingLatch.countDown(); + + long next = sequencer.next(); + sequencer.publish(next); + + doneLatch.countDown(); + }); + + waitingLatch.await(); + assertThat( + sequencer.getHighestPublishedSequence(expectedFullSequence, sequencer.getCursor()), + is(expectedFullSequence)); + + gatingSequence.set(Sequencer.INITIAL_CURSOR_VALUE + 1L); + + doneLatch.await(); + assertThat(sequencer.getHighestPublishedSequence(expectedFullSequence, sequencer.getCursor()), is(expectedFullSequence + 1L)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldThrowInsufficientCapacityExceptionWhenSequencerIsFull(final Sequencer sequencer) throws Exception + { + assertThrows(InsufficientCapacityException.class, () -> + { + sequencer.addGatingSequences(gatingSequence); + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.next(); + } + sequencer.tryNext(); + }); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldCalculateRemainingCapacity(final Sequencer sequencer) throws Exception + { + sequencer.addGatingSequences(gatingSequence); + + assertThat(sequencer.remainingCapacity(), is((long) BUFFER_SIZE)); + for (int i = 1; i < BUFFER_SIZE; i++) + { + sequencer.next(); + assertThat(sequencer.remainingCapacity(), is((long) BUFFER_SIZE - i)); + } + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotBeAvailableUntilPublished(final Sequencer sequencer) throws Exception + { + long next = sequencer.next(6); + + for (int i = 0; i <= 5; i++) + { + assertThat(sequencer.isAvailable(i), is(false)); + } + + sequencer.publish(next - (6 - 1), next); + + for (int i = 0; i <= 5; i++) + { + assertThat(sequencer.isAvailable(i), is(true)); + } + + assertThat(sequencer.isAvailable(6), is(false)); + } + + @ParameterizedTest + @MethodSource("producerTypeGenerator") + public void shouldNotifyWaitStrategyOnPublish(final ProducerType producerType) throws Exception + { + final DummyWaitStrategy waitStrategy = new DummyWaitStrategy(); + final Sequenced sequencer = newProducer(producerType, waitStrategy); + + sequencer.publish(sequencer.next()); + + assertThat(waitStrategy.signalAllWhenBlockingCalls, is(1)); + } + + @ParameterizedTest + @MethodSource("producerTypeGenerator") + public void shouldNotifyWaitStrategyOnPublishBatch(final ProducerType producerType) throws Exception + { + final DummyWaitStrategy waitStrategy = new DummyWaitStrategy(); + final Sequenced sequencer = newProducer(producerType, waitStrategy); + + long next = sequencer.next(4); + sequencer.publish(next - (4 - 1), next); + + assertThat(waitStrategy.signalAllWhenBlockingCalls, is(1)); + } + + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldWaitOnPublication(final Sequencer sequencer) throws Exception + { + SequenceBarrier barrier = sequencer.newBarrier(); + + long next = sequencer.next(10); + long lo = next - (10 - 1); + long mid = next - 5; + + for (long l = lo; l < mid; l++) + { + sequencer.publish(l); + } + + assertThat(barrier.waitFor(-1), is(mid - 1)); + + for (long l = mid; l <= next; l++) + { + sequencer.publish(l); + } + + assertThat(barrier.waitFor(-1), is(next)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldTryNext(final Sequencer sequencer) throws Exception + { + sequencer.addGatingSequences(gatingSequence); + + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.publish(sequencer.tryNext()); + } + + assertThrows(InsufficientCapacityException.class, sequencer::tryNext); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldClaimSpecificSequence(final Sequencer sequencer) throws Exception + { + long sequence = 14L; + + sequencer.claim(sequence); + sequencer.publish(sequence); + assertThat(sequencer.next(), is(sequence + 1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkNextLessThanZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.next(-1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkNextOfZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.next(0)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkTryNextLessThanZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.tryNext(-1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkTryNextOfZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.tryNext(0)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + void sequencesBecomeAvailableAfterAPublish(final Sequencer sequencer) + { + final long seq = sequencer.next(); + assertFalse(sequencer.isAvailable(seq)); + sequencer.publish(seq); + + assertTrue(sequencer.isAvailable(seq)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + void sequencesBecomeUnavailableAfterWrapping(final Sequencer sequencer) + { + final long seq = sequencer.next(); + sequencer.publish(seq); + assertTrue(sequencer.isAvailable(seq)); + + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.publish(sequencer.next()); + } + + assertFalse(sequencer.isAvailable(seq)); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java new file mode 100644 index 0000000000..54e8051bdc --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-340f23ef88a32ceb8341820c15bfd9537303219c/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java @@ -0,0 +1,33 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummySequenceBarrier; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class TimeoutBlockingWaitStrategyTest +{ + @Test + public void shouldTimeoutWaitFor() + { + final SequenceBarrier sequenceBarrier = new DummySequenceBarrier(); + + long theTimeout = 500; + TimeoutBlockingWaitStrategy waitStrategy = new TimeoutBlockingWaitStrategy(theTimeout, TimeUnit.MILLISECONDS); + Sequence cursor = new Sequence(5); + + long t0 = System.currentTimeMillis(); + + assertThrows(TimeoutException.class, () -> waitStrategy.waitFor(6, cursor, cursor, sequenceBarrier)); + + long t1 = System.currentTimeMillis(); + + long timeWaiting = t1 - t0; + + assertTrue(timeWaiting >= theTimeout); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java new file mode 100644 index 0000000000..461d431b26 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/FatalExceptionHandlerTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.TestEvent; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public final class FatalExceptionHandlerTest +{ + @Test + public void shouldHandleFatalException() + { + final Exception causeException = new Exception(); + final TestEvent event = new TestEvent(); + + ExceptionHandler exceptionHandler = new FatalExceptionHandler(); + + try + { + exceptionHandler.handleEventException(causeException, 0L, event); + } + catch (RuntimeException ex) + { + assertEquals(causeException, ex.getCause()); + } + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java new file mode 100644 index 0000000000..4eda988165 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/LiteTimeoutBlockingWaitStrategyTest.java @@ -0,0 +1,40 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummySequenceBarrier; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public class LiteTimeoutBlockingWaitStrategyTest +{ + @Test + public void shouldTimeoutWaitFor() throws Exception + { + final SequenceBarrier sequenceBarrier = new DummySequenceBarrier(); + + long theTimeout = 500; + LiteTimeoutBlockingWaitStrategy waitStrategy = new LiteTimeoutBlockingWaitStrategy(theTimeout, TimeUnit.MILLISECONDS); + Sequence cursor = new Sequence(5); + Sequence dependent = cursor; + + long t0 = System.currentTimeMillis(); + + try + { + waitStrategy.waitFor(6, cursor, dependent, sequenceBarrier); + fail("TimeoutException should have been thrown"); + } + catch (TimeoutException e) + { + } + + long t1 = System.currentTimeMillis(); + + long timeWaiting = t1 - t0; + + assertTrue(timeWaiting >= theTimeout); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/RingBufferTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/RingBufferTest.java new file mode 100644 index 0000000000..e11d5129d3 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/RingBufferTest.java @@ -0,0 +1,1620 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.StubEvent; +import com.lmax.disruptor.support.TestWaiter; +import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.lmax.disruptor.RingBuffer.createMultiProducer; +import static com.lmax.disruptor.RingBufferEventMatcher.ringBufferWithEvents; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public class RingBufferTest +{ + private final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE); + private final RingBuffer ringBuffer = RingBuffer.createMultiProducer(StubEvent.EVENT_FACTORY, 32); + private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + { + ringBuffer.addGatingSequences(new NoOpEventProcessor(ringBuffer).getSequence()); + } + + @Test + public void shouldClaimAndGet() throws Exception + { + assertEquals(SingleProducerSequencer.INITIAL_CURSOR_VALUE, ringBuffer.getCursor()); + + StubEvent expectedEvent = new StubEvent(2701); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, expectedEvent.getValue(), expectedEvent.getTestString()); + + long sequence = sequenceBarrier.waitFor(0); + assertEquals(0, sequence); + + StubEvent event = ringBuffer.get(sequence); + assertEquals(expectedEvent, event); + + assertEquals(0L, ringBuffer.getCursor()); + } + + @Test + public void shouldClaimAndGetInSeparateThread() throws Exception + { + Future> messages = getMessages(0, 0); + + StubEvent expectedEvent = new StubEvent(2701); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, expectedEvent.getValue(), expectedEvent.getTestString()); + + assertEquals(expectedEvent, messages.get().get(0)); + } + + @Test + public void shouldClaimAndGetMultipleMessages() throws Exception + { + int numMessages = ringBuffer.getBufferSize(); + for (int i = 0; i < numMessages; i++) + { + ringBuffer.publishEvent(StubEvent.TRANSLATOR, i, ""); + } + + long expectedSequence = numMessages - 1; + long available = sequenceBarrier.waitFor(expectedSequence); + assertEquals(expectedSequence, available); + + for (int i = 0; i < numMessages; i++) + { + assertEquals(i, ringBuffer.get(i).getValue()); + } + } + + @Test + public void shouldWrap() throws Exception + { + int numMessages = ringBuffer.getBufferSize(); + int offset = 1000; + for (int i = 0; i < numMessages + offset; i++) + { + ringBuffer.publishEvent(StubEvent.TRANSLATOR, i, ""); + } + + long expectedSequence = numMessages + offset - 1; + long available = sequenceBarrier.waitFor(expectedSequence); + assertEquals(expectedSequence, available); + + for (int i = offset; i < numMessages + offset; i++) + { + assertEquals(i, ringBuffer.get(i).getValue()); + } + } + + @Test + public void shouldPreventWrapping() throws Exception + { + Sequence sequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE); + final RingBuffer ringBuffer = createMultiProducer(StubEvent.EVENT_FACTORY, 4); + ringBuffer.addGatingSequences(sequence); + + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 0, "0"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 1, "1"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 2, "2"); + ringBuffer.publishEvent(StubEvent.TRANSLATOR, 3, "3"); + + assertFalse(ringBuffer.tryPublishEvent(StubEvent.TRANSLATOR, 3, "3")); + } + + @Test + public void shouldThrowExceptionIfBufferIsFull() throws Exception + { + ringBuffer.addGatingSequences(new Sequence(ringBuffer.getBufferSize())); + + try + { + for (int i = 0; i < ringBuffer.getBufferSize(); i++) + { + ringBuffer.publish(ringBuffer.tryNext()); + } + } + catch (Exception e) + { + fail("Should not of thrown exception"); + } + + try + { + ringBuffer.tryNext(); + fail("Exception should have been thrown"); + } + catch (InsufficientCapacityException e) + { + } + } + + @Test + public void shouldPreventPublishersOvertakingEventProcessorWrapPoint() throws InterruptedException + { + final int ringBufferSize = 16; + final CountDownLatch latch = new CountDownLatch(ringBufferSize); + final AtomicBoolean publisherComplete = new AtomicBoolean(false); + final RingBuffer buffer2 = createMultiProducer(StubEvent.EVENT_FACTORY, ringBufferSize); + final TestEventProcessor processor = new TestEventProcessor(buffer2.newBarrier()); + buffer2.addGatingSequences(processor.getSequence()); + + Thread thread = new Thread( + () -> + { + // Attempt to put in enough events to wrap around the ringbuffer + for (int i = 0; i < ringBufferSize + 1; i++) + { + long sequence = buffer2.next(); + StubEvent event = buffer2.get(sequence); + event.setValue(i); + buffer2.publish(sequence); + latch.countDown(); + } + + // Only marked complete after enough events published that the ringbuffer must have wrapped + publisherComplete.set(true); + }); + thread.start(); + + latch.await(); + + // Publisher should not be complete, blocked at RingBuffer::next + assertFalse(publisherComplete.get()); + + // Run the processor, freeing up entries in the ringbuffer for the producer to continue and "complete" + processor.run(); + thread.join(); + + // Check producer completes, ideally this should be in some kind of waiter + assertTrue(publisherComplete.get()); + } + + @Test + public void shouldPublishEvent() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator translator = new NoArgEventTranslator(); + + ringBuffer.publishEvent(translator); + ringBuffer.tryPublishEvent(translator); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L)); + } + + @Test + public void shouldPublishEventOneArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo"); + ringBuffer.tryPublishEvent(translator, "Foo"); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1")); + } + + @Test + public void shouldPublishEventTwoArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBar-0", "FooBar-1")); + } + + @Test + public void shouldPublishEventThreeArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar", "Baz"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar", "Baz"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBaz-0", "FooBarBaz-1")); + } + + @Test + public void shouldPublishEventVarArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvent(translator, "Foo", "Bar", "Baz", "Bam"); + ringBuffer.tryPublishEvent(translator, "Foo", "Bar", "Baz", "Bam"); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBazBam-0", "FooBarBazBam-1")); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEvents() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = new EventTranslator[]{eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators); + assertTrue(ringBuffer.tryPublishEvents(translators)); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L, 2L, 3L)); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator, eventTranslator, eventTranslator}; + + try + { + ringBuffer.tryPublishEvents(translators); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEventsWithBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators, 0, 1); + assertTrue(ringBuffer.tryPublishEvents(translators, 0, 1)); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) 0L), is((Object) 1L), is(nullValue()), is( + nullValue()))); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldPublishEventsWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + final EventTranslator eventTranslator = new NoArgEventTranslator(); + final EventTranslator[] translators = + new EventTranslator[]{eventTranslator, eventTranslator, eventTranslator}; + + ringBuffer.publishEvents(translators, 1, 2); + assertTrue(ringBuffer.tryPublishEvents(translators, 1, 2)); + + assertThat(ringBuffer, ringBufferWithEvents(0L, 1L, 2L, 3L)); + } + + @Test + public void shouldPublishEventsOneArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, new String[]{"Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo"})); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1", "Foo-2", "Foo-3")); + } + + @Test + public void shouldNotPublishEventsOneArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsOneArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, 0, 1, new String[]{"Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, 0, 1, new String[]{"Foo", "Foo"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "Foo-0"), is((Object) "Foo-1"), is(nullValue()), is( + nullValue()))); + } + + @Test + public void shouldPublishEventsOneArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + ringBuffer.publishEvents(translator, 1, 2, new String[]{"Foo", "Foo", "Foo"}); + assertTrue(ringBuffer.tryPublishEvents(translator, 1, 2, new String[]{"Foo", "Foo", "Foo"})); + + assertThat(ringBuffer, ringBufferWithEvents("Foo-0", "Foo-1", "Foo-2", "Foo-3")); + } + + @Test + public void shouldPublishEventsTwoArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents(translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + ringBuffer.tryPublishEvents(translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + + assertThat(ringBuffer, ringBufferWithEvents("FooBar-0", "FooBar-1", "FooBar-2", "FooBar-3")); + } + + @Test + public void shouldNotPublishEventsITwoArgIfBatchSizeIsBiggerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}, + new String[]{"Bar", "Bar", "Bar", "Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsTwoArgWithBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents(translator, 0, 1, new String[]{"Foo0", "Foo1"}, new String[]{"Bar0", "Bar1"}); + ringBuffer.tryPublishEvents(translator, 0, 1, new String[]{"Foo2", "Foo3"}, new String[]{"Bar2", "Bar3"}); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "Foo0Bar0-0"), is((Object) "Foo2Bar2-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsTwoArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Foo1", "Foo2"}, new String[]{"Bar0", "Bar1", "Bar2"}); + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Foo4", "Foo5"}, new String[]{"Bar3", "Bar4", "Bar5"}); + + assertThat(ringBuffer, ringBufferWithEvents("Foo1Bar1-0", "Foo2Bar2-1", "Foo4Bar4-2", "Foo5Bar5-3")); + } + + @Test + public void shouldPublishEventsThreeArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + ringBuffer.tryPublishEvents( + translator, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + + assertThat(ringBuffer, ringBufferWithEvents("FooBarBaz-0", "FooBarBaz-1", "FooBarBaz-2", "FooBarBaz-3")); + } + + @Test + public void shouldNotPublishEventsThreeArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Foo", "Foo", "Foo", "Foo"}, + new String[]{"Bar", "Bar", "Bar", "Bar", "Bar"}, + new String[]{"Baz", "Baz", "Baz", "Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsThreeArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 0, 1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + ringBuffer.tryPublishEvents( + translator, 0, 1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "FooBarBaz-0"), is((Object) "FooBarBaz-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsThreeArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Foo1", "Foo2"}, new String[]{"Bar0", "Bar1", "Bar2"}, + new String[]{"Baz0", "Baz1", "Baz2"} + ); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Foo4", "Foo5"}, new String[]{"Bar3", "Bar4", "Bar5"}, + new String[]{"Baz3", "Baz4", "Baz5"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "Foo1Bar1Baz1-0", "Foo2Bar2Baz2-1", "Foo4Bar4Baz4-2", "Foo5Bar5Baz5-3")); + } + + @Test + public void shouldPublishEventsVarArg() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "FooBarBazBam-0", "FooBarBazBam-1", "FooBarBazBam-2", "FooBarBazBam-3")); + } + + @Test + public void shouldNotPublishEventsVarArgIfBatchIsLargerThanRingBuffer() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}, + new String[]{"Foo", "Bar", "Baz", "Bam"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldPublishEventsVarArgBatchSizeOfOne() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 0, 1, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 0, 1, new String[]{"Foo", "Bar", "Baz", "Bam"}, new String[]{"Foo", "Bar", "Baz", "Bam"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + is((Object) "FooBarBazBam-0"), is((Object) "FooBarBazBam-1"), is( + nullValue()), is(nullValue()))); + } + + @Test + public void shouldPublishEventsVarArgWithinBatch() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorVararg translator = new VarArgEventTranslator(); + + ringBuffer.publishEvents( + translator, 1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, + new String[]{"Foo2", "Bar2", "Baz2", "Bam2"}); + assertTrue( + ringBuffer.tryPublishEvents( + translator, 1, 2, new String[]{"Foo3", "Bar3", "Baz3", "Bam3"}, + new String[]{"Foo4", "Bar4", "Baz4", "Bam4"}, + new String[]{"Foo5", "Bar5", "Baz5", "Bam5"})); + + assertThat( + ringBuffer, ringBufferWithEvents( + "Foo1Bar1Baz1Bam1-0", "Foo2Bar2Baz2Bam2-1", "Foo4Bar4Baz4Bam4-2", "Foo5Bar5Baz5Bam5-3")); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, 0); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, 0); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator}, 1, 3); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator}, 1, 3); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, -1); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, 1, -1); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotPublishEventsWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + try + { + ringBuffer.publishEvents(new EventTranslator[]{translator, translator, translator, translator}, -1, 2); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @SuppressWarnings("unchecked") + @Test + public void shouldNotTryPublishEventsWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslator translator = new NoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(new EventTranslator[]{translator, translator, translator, translator}, -1, 2); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsOneArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + try + { + ringBuffer.publishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + assertFalse(ringBuffer.tryPublishEvents(translator, 1, -1, new String[]{"Foo", "Foo"})); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsOneArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorOneArg translator = new OneArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.publishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsTwoArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + try + { + ringBuffer.publishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsTwoArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorTwoArg translator = new TwoArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents(translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 0, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 0, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, -1, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsThreeArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, -1, 2, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 3, new String[]{"Foo", "Foo"}, new String[]{"Bar", "Bar"}, + new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, -1, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsThreeArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + EventTranslatorThreeArg translator = new ThreeArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, -1, 2, new String[]{"Foo", "Foo"}, + new String[]{"Bar", "Bar"}, new String[]{"Baz", "Baz"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 0, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchSizeIs0() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 0, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, + new String[]{"Foo2", "Bar2", "Baz2", "Bam2"}); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, 3, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, 1, -1, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotPublishEventsVarArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.publishEvents( + translator, -1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchExtendsPastEndOfArray() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, 3, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchSizeIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, 1, -1, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldNotTryPublishEventsVarArgWhenBatchStartsAtIsNegative() throws Exception + { + assertThrows(IllegalArgumentException.class, () -> + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 4); + VarArgEventTranslator translator = new VarArgEventTranslator(); + + try + { + ringBuffer.tryPublishEvents( + translator, -1, 2, new String[]{"Foo0", "Bar0", "Baz0", "Bam0"}, + new String[]{"Foo1", "Bar1", "Baz1", "Bam1"}, new String[]{ + "Foo2", "Bar2", + "Baz2", "Bam2" + }); + } + finally + { + assertEmptyRingBuffer(ringBuffer); + } + }); + } + + @Test + public void shouldAddAndRemoveSequences() throws Exception + { + RingBuffer ringBuffer = RingBuffer.createSingleProducer(new ArrayFactory(1), 16); + + Sequence sequenceThree = new Sequence(-1); + Sequence sequenceSeven = new Sequence(-1); + ringBuffer.addGatingSequences(sequenceThree, sequenceSeven); + + for (int i = 0; i < 10; i++) + { + ringBuffer.publish(ringBuffer.next()); + } + + sequenceThree.set(3); + sequenceSeven.set(7); + + assertThat(ringBuffer.getMinimumGatingSequence(), is(3L)); + assertTrue(ringBuffer.removeGatingSequence(sequenceThree)); + assertThat(ringBuffer.getMinimumGatingSequence(), is(7L)); + } + + @Test + public void shouldHandleResetToAndNotWrapUnnecessarilySingleProducer() throws Exception + { + assertHandleResetAndNotWrap(RingBuffer.createSingleProducer(StubEvent.EVENT_FACTORY, 4)); + } + + @Test + public void shouldHandleResetToAndNotWrapUnnecessarilyMultiProducer() throws Exception + { + assertHandleResetAndNotWrap(RingBuffer.createMultiProducer(StubEvent.EVENT_FACTORY, 4)); + } + + @SuppressWarnings("deprecation") + private void assertHandleResetAndNotWrap(final RingBuffer rb) + { + Sequence sequence = new Sequence(); + rb.addGatingSequences(sequence); + + for (int i = 0; i < 128; i++) + { + rb.publish(rb.next()); + sequence.incrementAndGet(); + } + + assertThat(rb.getCursor(), is(127L)); + + rb.resetTo(31); + sequence.set(31); + + for (int i = 0; i < 4; i++) + { + rb.publish(rb.next()); + } + + assertThat(rb.hasAvailableCapacity(1), is(false)); + } + + private Future> getMessages(final long initial, final long toWaitFor) throws InterruptedException, + BrokenBarrierException + { + final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + final Future> f = executor.submit( + new TestWaiter( + cyclicBarrier, sequenceBarrier, ringBuffer, + initial, toWaitFor)); + + cyclicBarrier.await(); + + return f; + } + + private void assertEmptyRingBuffer(final RingBuffer ringBuffer) + { + assertThat(ringBuffer.get(0)[0], is(nullValue())); + assertThat(ringBuffer.get(1)[0], is(nullValue())); + assertThat(ringBuffer.get(2)[0], is(nullValue())); + assertThat(ringBuffer.get(3)[0], is(nullValue())); + } + + private static final class TestEventProcessor implements EventProcessor + { + private final SequenceBarrier sequenceBarrier; + private final Sequence sequence = new Sequence(SingleProducerSequencer.INITIAL_CURSOR_VALUE); + private final AtomicBoolean running = new AtomicBoolean(); + + + TestEventProcessor(final SequenceBarrier sequenceBarrier) + { + this.sequenceBarrier = sequenceBarrier; + } + + @Override + public Sequence getSequence() + { + return sequence; + } + + @Override + public void halt() + { + running.set(false); + } + + @Override + public boolean isRunning() + { + return running.get(); + } + + @Override + public void run() + { + if (!running.compareAndSet(false, true)) + { + throw new IllegalStateException("Already running"); + } + try + { + sequenceBarrier.waitFor(0L); + } + catch (Exception ex) + { + throw new RuntimeException(ex); + } + + sequence.set(sequence.get() + 1L); + } + } + + private static class ArrayFactory implements EventFactory + { + private final int size; + + ArrayFactory(final int size) + { + this.size = size; + } + + @Override + public Object[] newInstance() + { + return new Object[size]; + } + } + + private static class NoArgEventTranslator implements EventTranslator + { + @Override + public void translateTo(final Object[] event, final long sequence) + { + event[0] = sequence; + } + } + + private static class VarArgEventTranslator implements EventTranslatorVararg + { + @Override + public void translateTo(final Object[] event, final long sequence, final Object... args) + { + event[0] = (String) args[0] + args[1] + args[2] + args[3] + "-" + sequence; + } + } + + private static class ThreeArgEventTranslator implements EventTranslatorThreeArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0, final String arg1, final String arg2) + { + event[0] = arg0 + arg1 + arg2 + "-" + sequence; + } + } + + private static class TwoArgEventTranslator implements EventTranslatorTwoArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0, final String arg1) + { + event[0] = arg0 + arg1 + "-" + sequence; + } + } + + private static class OneArgEventTranslator implements EventTranslatorOneArg + { + @Override + public void translateTo(final Object[] event, final long sequence, final String arg0) + { + event[0] = arg0 + "-" + sequence; + } + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java new file mode 100644 index 0000000000..5ad57f2d75 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequenceBarrierTest.java @@ -0,0 +1,206 @@ +/* + * Copyright 2011 LMAX Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummyEventProcessor; +import com.lmax.disruptor.support.StubEvent; +import com.lmax.disruptor.util.Util; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static com.lmax.disruptor.RingBuffer.createMultiProducer; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public final class SequenceBarrierTest +{ + private final RingBuffer ringBuffer = createMultiProducer(StubEvent.EVENT_FACTORY, 64); + + public SequenceBarrierTest() + { + ringBuffer.addGatingSequences(new NoOpEventProcessor(ringBuffer).getSequence()); + } + + @Test + public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsAhead() throws Exception + { + final long expectedNumberMessages = 10; + final long expectedWorkSequence = 9; + fillRingBuffer(expectedNumberMessages); + + final Sequence sequence1 = new Sequence(expectedNumberMessages); + final Sequence sequence2 = new Sequence(expectedWorkSequence); + final Sequence sequence3 = new Sequence(expectedNumberMessages); + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(sequence1, sequence2, sequence3); + + long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldWaitForWorkCompleteWhereAllWorkersAreBlockedOnRingBuffer() throws Exception + { + long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final DummyEventProcessor[] workers = new DummyEventProcessor[3]; + for (int i = 0, size = workers.length; i < size; i++) + { + workers[i] = new DummyEventProcessor(); + workers[i].setSequence(expectedNumberMessages - 1); + } + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(Util.getSequencesFor(workers)); + + Runnable runnable = () -> + { + long sequence = ringBuffer.next(); + StubEvent event = ringBuffer.get(sequence); + event.setValue((int) sequence); + ringBuffer.publish(sequence); + + for (DummyEventProcessor stubWorker : workers) + { + stubWorker.setSequence(sequence); + } + }; + + new Thread(runnable).start(); + + long expectedWorkSequence = expectedNumberMessages; + long completedWorkSequence = sequenceBarrier.waitFor(expectedNumberMessages); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldInterruptDuringBusySpin() throws Exception + { + final long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final CountDownLatch latch = new CountDownLatch(3); + final Sequence sequence1 = new CountDownLatchSequence(8L, latch); + final Sequence sequence2 = new CountDownLatchSequence(8L, latch); + final Sequence sequence3 = new CountDownLatchSequence(8L, latch); + + final SequenceBarrier sequenceBarrier = + ringBuffer.newBarrier(sequence1, sequence2, sequence3); + + final boolean[] alerted = {false}; + Thread t = new Thread( + () -> + { + try + { + sequenceBarrier.waitFor(expectedNumberMessages - 1); + } + catch (AlertException e) + { + alerted[0] = true; + } + catch (Exception e) + { + // don't care + } + }); + + t.start(); + latch.await(3, TimeUnit.SECONDS); + sequenceBarrier.alert(); + t.join(); + + assertTrue(alerted[0], "Thread was not interrupted"); + } + + @Test + public void shouldWaitForWorkCompleteWhereCompleteWorkThresholdIsBehind() throws Exception + { + long expectedNumberMessages = 10; + fillRingBuffer(expectedNumberMessages); + + final DummyEventProcessor[] eventProcessors = new DummyEventProcessor[3]; + for (int i = 0, size = eventProcessors.length; i < size; i++) + { + eventProcessors[i] = new DummyEventProcessor(); + eventProcessors[i].setSequence(expectedNumberMessages - 2); + } + + final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(Util.getSequencesFor(eventProcessors)); + + Runnable runnable = () -> + { + for (DummyEventProcessor stubWorker : eventProcessors) + { + stubWorker.setSequence(stubWorker.getSequence().get() + 1L); + } + }; + + Thread thread = new Thread(runnable); + thread.start(); + thread.join(); + + long expectedWorkSequence = expectedNumberMessages - 1; + long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); + assertTrue(completedWorkSequence >= expectedWorkSequence); + } + + @Test + public void shouldSetAndClearAlertStatus() + { + SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(); + + assertFalse(sequenceBarrier.isAlerted()); + + sequenceBarrier.alert(); + assertTrue(sequenceBarrier.isAlerted()); + + sequenceBarrier.clearAlert(); + assertFalse(sequenceBarrier.isAlerted()); + } + + private void fillRingBuffer(final long expectedNumberMessages) throws InterruptedException + { + for (long i = 0; i < expectedNumberMessages; i++) + { + long sequence = ringBuffer.next(); + StubEvent event = ringBuffer.get(sequence); + event.setValue((int) i); + ringBuffer.publish(sequence); + } + } + + private static final class CountDownLatchSequence extends Sequence + { + private final CountDownLatch latch; + + private CountDownLatchSequence(final long initialValue, final CountDownLatch latch) + { + super(initialValue); + this.latch = latch; + } + + @Override + public long get() + { + latch.countDown(); + return super.get(); + } + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequencerTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequencerTest.java new file mode 100644 index 0000000000..d625fb41f8 --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/SequencerTest.java @@ -0,0 +1,324 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.dsl.ProducerType; +import com.lmax.disruptor.support.DummyWaitStrategy; +import com.lmax.disruptor.util.DaemonThreadFactory; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +public class SequencerTest +{ + private static final int BUFFER_SIZE = 16; + private final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE); + private final Sequence gatingSequence = new Sequence(); + + private static Stream sequencerGenerator() + { + return Stream.of( + arguments(newProducer(ProducerType.SINGLE, new BlockingWaitStrategy())), + arguments(newProducer(ProducerType.MULTI, new BlockingWaitStrategy())) + ); + } + + private static Stream producerTypeGenerator() + { + return Stream.of(arguments(ProducerType.SINGLE), arguments(ProducerType.MULTI)); + } + + private static Sequencer newProducer(final ProducerType producerType, final WaitStrategy waitStrategy) + { + switch (producerType) + { + case SINGLE: + return new SingleProducerSequencer(BUFFER_SIZE, waitStrategy); + case MULTI: + return new MultiProducerSequencer(BUFFER_SIZE, waitStrategy); + default: + throw new IllegalStateException(producerType.toString()); + } + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldStartWithInitialValue(final Sequencer sequencer) + { + assertEquals(0, sequencer.next()); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldBatchClaim(final Sequencer sequencer) + { + assertEquals(3, sequencer.next(4)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldIndicateHasAvailableCapacity(final Sequencer sequencer) + { + sequencer.addGatingSequences(gatingSequence); + + assertTrue(sequencer.hasAvailableCapacity(1)); + assertTrue(sequencer.hasAvailableCapacity(BUFFER_SIZE)); + assertFalse(sequencer.hasAvailableCapacity(BUFFER_SIZE + 1)); + + sequencer.publish(sequencer.next()); + + assertTrue(sequencer.hasAvailableCapacity(BUFFER_SIZE - 1)); + assertFalse(sequencer.hasAvailableCapacity(BUFFER_SIZE)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldIndicateNoAvailableCapacity(final Sequencer sequencer) + { + sequencer.addGatingSequences(gatingSequence); + long sequence = sequencer.next(BUFFER_SIZE); + sequencer.publish(sequence - (BUFFER_SIZE - 1), sequence); + + assertFalse(sequencer.hasAvailableCapacity(1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldHoldUpPublisherWhenBufferIsFull(final Sequencer sequencer) + throws InterruptedException + { + sequencer.addGatingSequences(gatingSequence); + long sequence = sequencer.next(BUFFER_SIZE); + sequencer.publish(sequence - (BUFFER_SIZE - 1), sequence); + + final CountDownLatch waitingLatch = new CountDownLatch(1); + final CountDownLatch doneLatch = new CountDownLatch(1); + + final long expectedFullSequence = Sequencer.INITIAL_CURSOR_VALUE + sequencer.getBufferSize(); + assertThat( + sequencer.getHighestPublishedSequence(Sequencer.INITIAL_CURSOR_VALUE + 1, sequencer.getCursor()), + is(expectedFullSequence)); + + executor.submit( + () -> + { + waitingLatch.countDown(); + + long next = sequencer.next(); + sequencer.publish(next); + + doneLatch.countDown(); + }); + + waitingLatch.await(); + assertThat( + sequencer.getHighestPublishedSequence(expectedFullSequence, sequencer.getCursor()), + is(expectedFullSequence)); + + gatingSequence.set(Sequencer.INITIAL_CURSOR_VALUE + 1L); + + doneLatch.await(); + assertThat(sequencer.getHighestPublishedSequence(expectedFullSequence, sequencer.getCursor()), is(expectedFullSequence + 1L)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldThrowInsufficientCapacityExceptionWhenSequencerIsFull(final Sequencer sequencer) throws Exception + { + assertThrows(InsufficientCapacityException.class, () -> + { + sequencer.addGatingSequences(gatingSequence); + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.next(); + } + sequencer.tryNext(); + }); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldCalculateRemainingCapacity(final Sequencer sequencer) throws Exception + { + sequencer.addGatingSequences(gatingSequence); + + assertThat(sequencer.remainingCapacity(), is((long) BUFFER_SIZE)); + for (int i = 1; i < BUFFER_SIZE; i++) + { + sequencer.next(); + assertThat(sequencer.remainingCapacity(), is((long) BUFFER_SIZE - i)); + } + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotBeAvailableUntilPublished(final Sequencer sequencer) throws Exception + { + long next = sequencer.next(6); + + for (int i = 0; i <= 5; i++) + { + assertThat(sequencer.isAvailable(i), is(false)); + } + + sequencer.publish(next - (6 - 1), next); + + for (int i = 0; i <= 5; i++) + { + assertThat(sequencer.isAvailable(i), is(true)); + } + + assertThat(sequencer.isAvailable(6), is(false)); + } + + @ParameterizedTest + @MethodSource("producerTypeGenerator") + public void shouldNotifyWaitStrategyOnPublish(final ProducerType producerType) throws Exception + { + final DummyWaitStrategy waitStrategy = new DummyWaitStrategy(); + final Sequenced sequencer = newProducer(producerType, waitStrategy); + + sequencer.publish(sequencer.next()); + + assertThat(waitStrategy.signalAllWhenBlockingCalls, is(1)); + } + + @ParameterizedTest + @MethodSource("producerTypeGenerator") + public void shouldNotifyWaitStrategyOnPublishBatch(final ProducerType producerType) throws Exception + { + final DummyWaitStrategy waitStrategy = new DummyWaitStrategy(); + final Sequenced sequencer = newProducer(producerType, waitStrategy); + + long next = sequencer.next(4); + sequencer.publish(next - (4 - 1), next); + + assertThat(waitStrategy.signalAllWhenBlockingCalls, is(1)); + } + + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldWaitOnPublication(final Sequencer sequencer) throws Exception + { + SequenceBarrier barrier = sequencer.newBarrier(); + + long next = sequencer.next(10); + long lo = next - (10 - 1); + long mid = next - 5; + + for (long l = lo; l < mid; l++) + { + sequencer.publish(l); + } + + assertThat(barrier.waitFor(-1), is(mid - 1)); + + for (long l = mid; l <= next; l++) + { + sequencer.publish(l); + } + + assertThat(barrier.waitFor(-1), is(next)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldTryNext(final Sequencer sequencer) throws Exception + { + sequencer.addGatingSequences(gatingSequence); + + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.publish(sequencer.tryNext()); + } + + try + { + sequencer.tryNext(); + fail("Should of thrown: " + InsufficientCapacityException.class.getSimpleName()); + } + catch (InsufficientCapacityException e) + { + // No-op + } + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldClaimSpecificSequence(final Sequencer sequencer) throws Exception + { + long sequence = 14L; + + sequencer.claim(sequence); + sequencer.publish(sequence); + assertThat(sequencer.next(), is(sequence + 1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkNextLessThanZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.next(-1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkNextOfZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.next(0)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkTryNextLessThanZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.tryNext(-1)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + public void shouldNotAllowBulkTryNextOfZero(final Sequencer sequencer) throws Exception + { + assertThrows(IllegalArgumentException.class, () -> sequencer.tryNext(0)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + void sequencesBecomeAvailableAfterAPublish(final Sequencer sequencer) + { + final long seq = sequencer.next(); + assertFalse(sequencer.isAvailable(seq)); + sequencer.publish(seq); + + assertTrue(sequencer.isAvailable(seq)); + } + + @ParameterizedTest + @MethodSource("sequencerGenerator") + void sequencesBecomeUnavailableAfterWrapping(final Sequencer sequencer) + { + final long seq = sequencer.next(); + sequencer.publish(seq); + assertTrue(sequencer.isAvailable(seq)); + + for (int i = 0; i < BUFFER_SIZE; i++) + { + sequencer.publish(sequencer.next()); + } + + assertFalse(sequencer.isAvailable(seq)); + } +} diff --git a/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java new file mode 100644 index 0000000000..8c3d97edbf --- /dev/null +++ b/src/test/resources/oracle/commits/disruptor-61c50a6c834c1c0f2e57945d1f0828078b647806/src/test/java/com/lmax/disruptor/TimeoutBlockingWaitStrategyTest.java @@ -0,0 +1,41 @@ +package com.lmax.disruptor; + +import com.lmax.disruptor.support.DummySequenceBarrier; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +public class TimeoutBlockingWaitStrategyTest +{ + @Test + public void shouldTimeoutWaitFor() throws Exception + { + final SequenceBarrier sequenceBarrier = new DummySequenceBarrier(); + + long theTimeout = 500; + TimeoutBlockingWaitStrategy waitStrategy = new TimeoutBlockingWaitStrategy(theTimeout, TimeUnit.MILLISECONDS); + Sequence cursor = new Sequence(5); + Sequence dependent = cursor; + + long t0 = System.currentTimeMillis(); + + try + { + waitStrategy.waitFor(6, cursor, dependent, sequenceBarrier); + fail("TimeoutException should have been thrown"); + } + catch (TimeoutException e) + { + } + + long t1 = System.currentTimeMillis(); + + long timeWaiting = t1 - t0; + + assertTrue(timeWaiting >= theTimeout); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java new file mode 100644 index 0000000000..23f3692dc9 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.SortedMap; +import java.util.SortedSet; + +import org.eclipse.collections.api.LazyBooleanIterable; +import org.eclipse.collections.api.LazyByteIterable; +import org.eclipse.collections.api.LazyCharIterable; +import org.eclipse.collections.api.LazyDoubleIterable; +import org.eclipse.collections.api.LazyFloatIterable; +import org.eclipse.collections.api.LazyIntIterable; +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.LazyLongIterable; +import org.eclipse.collections.api.LazyShortIterable; +import org.eclipse.collections.api.collection.ImmutableCollection; +import org.eclipse.collections.api.collection.MutableCollection; +import org.eclipse.collections.api.factory.Sets; +import org.eclipse.collections.api.list.ListIterable; +import org.eclipse.collections.api.list.primitive.BooleanList; +import org.eclipse.collections.api.list.primitive.ByteList; +import org.eclipse.collections.api.list.primitive.CharList; +import org.eclipse.collections.api.list.primitive.DoubleList; +import org.eclipse.collections.api.list.primitive.FloatList; +import org.eclipse.collections.api.list.primitive.IntList; +import org.eclipse.collections.api.list.primitive.LongList; +import org.eclipse.collections.api.list.primitive.ShortList; +import org.eclipse.collections.api.ordered.ReversibleIterable; +import org.eclipse.collections.api.ordered.SortedIterable; +import org.eclipse.collections.api.set.MutableSet; +import org.eclipse.collections.impl.list.mutable.MultiReaderFastList; +import org.eclipse.collections.impl.test.SerializeTestHelper; +import org.eclipse.collections.impl.test.Verify; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.impl.test.Verify.assertIterablesEqual; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public interface IterableTestCase +{ + Iterable newWith(T... elements); + + boolean allowsDuplicates(); + + static void assertEquals(Object o1, Object o2) + { + if (o1 instanceof ListIterable && o2 instanceof LazyIterable) + { + IterableTestCase.assertEquals(o1, ((LazyIterable) o2).toList()); + return; + } + if (o1 instanceof BooleanList && o2 instanceof LazyBooleanIterable) + { + IterableTestCase.assertEquals(o1, ((LazyBooleanIterable) o2).toList()); + return; + } + if (o1 instanceof ByteList && o2 instanceof LazyByteIterable) + { + IterableTestCase.assertEquals(o1, ((LazyByteIterable) o2).toList()); + return; + } + if (o1 instanceof CharList && o2 instanceof LazyCharIterable) + { + IterableTestCase.assertEquals(o1, ((LazyCharIterable) o2).toList()); + return; + } + if (o1 instanceof DoubleList && o2 instanceof LazyDoubleIterable) + { + IterableTestCase.assertEquals(o1, ((LazyDoubleIterable) o2).toList()); + return; + } + if (o1 instanceof FloatList && o2 instanceof LazyFloatIterable) + { + IterableTestCase.assertEquals(o1, ((LazyFloatIterable) o2).toList()); + return; + } + if (o1 instanceof IntList && o2 instanceof LazyIntIterable) + { + IterableTestCase.assertEquals(o1, ((LazyIntIterable) o2).toList()); + return; + } + if (o1 instanceof LongList && o2 instanceof LazyLongIterable) + { + IterableTestCase.assertEquals(o1, ((LazyLongIterable) o2).toList()); + return; + } + if (o1 instanceof ShortList && o2 instanceof LazyShortIterable) + { + IterableTestCase.assertEquals(o1, ((LazyShortIterable) o2).toList()); + return; + } + + Assert.assertEquals(o1, o2); + + assertFalse("Neither item should equal null", o1.equals(null)); + assertFalse("Neither item should equal null", o2.equals(null)); + assertNotEquals("Neither item should equal new Object()", o1.equals(new Object())); + assertNotEquals("Neither item should equal new Object()", o2.equals(new Object())); + Assert.assertEquals(o1, o1); + Assert.assertEquals(o2, o2); + Assert.assertEquals(o1, o2); + Assert.assertEquals(o2, o1); + Assert.assertEquals(o1.hashCode(), o2.hashCode()); + + checkNotSame(o1, o2); + + if (o1 instanceof MultiReaderFastList || o2 instanceof MultiReaderFastList) + { + return; + } + if (o1 instanceof SortedIterable || o2 instanceof SortedIterable + || o1 instanceof ReversibleIterable || o2 instanceof ReversibleIterable + || o1 instanceof List || o2 instanceof List + || o1 instanceof SortedSet || o2 instanceof SortedSet) + { + assertIterablesEqual((Iterable) o1, (Iterable) o2); + if (o1 instanceof SortedIterable || o2 instanceof SortedIterable) + { + Comparator comparator1 = ((SortedIterable) o1).comparator(); + Comparator comparator2 = ((SortedIterable) o2).comparator(); + if (comparator1 != null && comparator2 != null) + { + assertSame(comparator1.getClass(), comparator2.getClass()); + } + } + } + else if (o1 instanceof SortedMap || o2 instanceof SortedMap) + { + IterableTestCase.assertEquals(((SortedMap) o1).keySet(), ((SortedMap) o2).keySet()); + } + } + + static void checkNotSame(Object o1, Object o2) + { + if (o1 instanceof String && o2 instanceof String) + { + return; + } + if ((o1 instanceof Number && o2 instanceof Number) + || (o1 instanceof Boolean && o2 instanceof Boolean) + || o1 instanceof ImmutableCollection && o2 instanceof ImmutableCollection + && ((ImmutableCollection) o1).isEmpty() && ((ImmutableCollection) o2).isEmpty() + && !(o1 instanceof SortedIterable) && !(o2 instanceof SortedIterable)) + { + assertSame(o1, o2); + return; + } + assertNotSame(o1, o2); + } + + static void assertNotEquals(Object o1, Object o2) + { + Assert.assertNotEquals(o1, o2); + Assert.assertNotEquals(o2, o1); + + assertFalse("Neither item should equal null", o1.equals(null)); + assertFalse("Neither item should equal null", o2.equals(null)); + Assert.assertNotEquals("Neither item should equal new Object()", o1.equals(new Object())); + Assert.assertNotEquals("Neither item should equal new Object()", o2.equals(new Object())); + Assert.assertEquals(o1, o1); + Assert.assertEquals(o2, o2); + } + + static void addAllTo(T[] elements, MutableCollection result) + { + for (T element : elements) + { + if (!result.add(element)) + { + throw new IllegalStateException(); + } + } + } + + @Test + default void Object_PostSerializedEqualsAndHashCode() + { + Iterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + Object deserialized = SerializeTestHelper.serializeDeserialize(iterable); + assertNotSame(iterable, deserialized); + } + + @Test + default void Object_equalsAndHashCode() + { + Verify.assertEqualsAndHashCode(this.newWith(3, 3, 3, 2, 2, 1), this.newWith(3, 3, 3, 2, 2, 1)); + + assertNotEquals(this.newWith(4, 3, 2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(4, 3, 2, 1)); + + assertNotEquals(this.newWith(2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(2, 1)); + + assertNotEquals(this.newWith(3, 3, 2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(3, 3, 2, 1)); + + assertNotEquals(this.newWith(3, 3, 2, 1), this.newWith(3, 2, 2, 1)); + assertNotEquals(this.newWith(3, 2, 2, 1), this.newWith(3, 3, 2, 1)); + } + + @Test + default void Iterable_hasNext() + { + assertTrue(this.newWith(3, 2, 1).iterator().hasNext()); + assertFalse(this.newWith().iterator().hasNext()); + } + + @Test + default void Iterable_next() + { + Iterator iterator = this.newWith(3, 2, 1).iterator(); + MutableSet set = Sets.mutable.with(); + assertTrue(set.add(iterator.next())); + assertTrue(set.add(iterator.next())); + assertTrue(set.add(iterator.next())); + IterableTestCase.assertEquals(Sets.immutable.with(3, 2, 1), set); + } + + @Test(expected = NoSuchElementException.class) + default void Iterable_next_throws_on_empty() + { + this.newWith().iterator().next(); + } + + @Test + default void Iterable_next_throws_at_end() + { + Iterable iterable = this.newWith(3, 2, 1); + Iterator iterator = iterable.iterator(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + + Iterator iterator2 = iterable.iterator(); + iterator2.next(); + iterator2.next(); + iterator2.next(); + assertThrows(NoSuchElementException.class, iterator2::next); + assertThrows(NoSuchElementException.class, iterator2::next); + } + + void Iterable_remove(); + + void Iterable_toString(); +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java new file mode 100644 index 0000000000..51ccec9a87 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2021 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test; + +import java.util.Iterator; +import java.util.Optional; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.Sets; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.api.tuple.primitive.ObjectIntPair; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.impl.factory.primitive.IntLists; +import org.eclipse.collections.impl.factory.primitive.IntSets; +import org.eclipse.collections.impl.tuple.Tuples; +import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertSame; + +public interface OrderedIterableTestCase extends RichIterableTestCase +{ + /** + * @since 9.1. + */ + @Test + default void OrderedIterable_collectWithIndex() + { + RichIterable> pairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair); + Assert.assertEquals( + IntLists.mutable.with(0, 1, 2, 3), + pairs.collectInt(ObjectIntPair::getTwo, IntLists.mutable.empty())); + Assert.assertEquals( + Lists.mutable.with(3, 2, 1, 0), + pairs.collect(ObjectIntPair::getOne, Lists.mutable.empty())); + } + + /** + * @since 9.1. + */ + @Test + default void OrderedIterable_collectWithIndexWithTarget() + { + RichIterable> pairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair, Lists.mutable.empty()); + Assert.assertEquals( + IntLists.mutable.with(0, 1, 2, 3), + pairs.collectInt(ObjectIntPair::getTwo, IntLists.mutable.empty())); + Assert.assertEquals( + Lists.mutable.with(3, 2, 1, 0), + pairs.collect(ObjectIntPair::getOne, Lists.mutable.empty())); + + RichIterable> setOfPairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair, Lists.mutable.empty()); + Assert.assertEquals( + IntSets.mutable.with(0, 1, 2, 3), + setOfPairs.collectInt(ObjectIntPair::getTwo, IntSets.mutable.empty())); + Assert.assertEquals( + Sets.mutable.with(3, 2, 1, 0), + setOfPairs.collect(ObjectIntPair::getOne, Sets.mutable.empty())); + } + + @Test + default void OrderedIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 3, 3, 2, 2, 1).getFirst()); + } + + @Test + default void OrderedIterable_getFirstOptional_empty() + { + assertSame(Optional.empty(), ((OrderedIterable) this.newWith()).getFirstOptional()); + } + + @Test + default void OrderedIterable_getFirstOptional() + { + assertEquals(Optional.of(Integer.valueOf(3)), ((OrderedIterable) this.newWith(3, 3, 3, 2, 2, 1)).getFirstOptional()); + } + + @Test(expected = NullPointerException.class) + default void OrderedIterable_getFirstOptional_null_element() + { + ((OrderedIterable) this.newWith(new Object[]{null})).getFirstOptional(); + } + + @Test + default void OrderedIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 3, 3, 2, 2, 1).getLast()); + } + + @Test + default void OrderedIterable_getLastOptional_empty() + { + assertSame(Optional.empty(), ((OrderedIterable) this.newWith()).getLastOptional()); + } + + @Test + default void OrderedIterable_getLastOptional() + { + assertEquals(Optional.of(Integer.valueOf(1)), ((OrderedIterable) this.newWith(3, 3, 3, 2, 2, 1)).getLastOptional()); + } + + @Test(expected = NullPointerException.class) + default void OrderedIterable_getLastOptional_null_element() + { + ((OrderedIterable) this.newWith(new Object[]{null})).getLastOptional(); + } + + @Test + default void OrderedIterable_next() + { + Iterator iterator = this.newWith(3, 2, 1).iterator(); + assertEquals(Integer.valueOf(3), iterator.next()); + assertEquals(Integer.valueOf(2), iterator.next()); + assertEquals(Integer.valueOf(1), iterator.next()); + } + + @Test + default void OrderedIterable_min() + { + Holder first = new Holder<>(-1); + Holder second = new Holder<>(-1); + assertSame(first, this.newWith(new Holder<>(2), first, new Holder<>(0), second).min()); + } + + @Test + default void OrderedIterable_max() + { + Holder first = new Holder<>(1); + Holder second = new Holder<>(1); + assertSame(first, this.newWith(new Holder<>(-2), first, new Holder<>(0), second).max()); + } + + @Test + default void OrderedIterable_min_comparator() + { + Holder first = new Holder<>(1); + Holder second = new Holder<>(1); + assertSame(first, this.newWith(new Holder<>(-2), first, new Holder<>(0), second).min(Comparators.reverseNaturalOrder())); + } + + @Test + default void OrderedIterable_max_comparator() + { + Holder first = new Holder<>(-1); + Holder second = new Holder<>(-1); + assertSame(first, this.newWith(new Holder<>(2), first, new Holder<>(0), second).max(Comparators.reverseNaturalOrder())); + } + + @Test + default void OrderedIterable_zipWithIndex() + { + RichIterable iterable = this.newWith(4, 4, 4, 4, 3, 3, 3, 2, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(4, 1), + Tuples.pair(4, 2), + Tuples.pair(4, 3), + Tuples.pair(3, 4), + Tuples.pair(3, 5), + Tuples.pair(3, 6), + Tuples.pair(2, 7), + Tuples.pair(2, 8), + Tuples.pair(1, 9)), + iterable.zipWithIndex().toList()); + } + + @Test + default void OrderedIterable_zipWithIndex_target() + { + RichIterable iterable = this.newWith(4, 4, 4, 4, 3, 3, 3, 2, 2, 1); + MutableList> target = Lists.mutable.empty(); + MutableList> result = iterable.zipWithIndex(target); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(4, 1), + Tuples.pair(4, 2), + Tuples.pair(4, 3), + Tuples.pair(3, 4), + Tuples.pair(3, 5), + Tuples.pair(3, 6), + Tuples.pair(2, 7), + Tuples.pair(2, 8), + Tuples.pair(1, 9)), + result); + assertSame(target, result); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java new file mode 100644 index 0000000000..b7278a6f2f --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.bag.mutable.sorted; + +import org.eclipse.collections.api.bag.sorted.MutableSortedBag; +import org.eclipse.collections.impl.bag.sorted.mutable.TreeBag; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.test.MutableOrderedIterableTestCase; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public interface MutableSortedBagTestCase extends SortedBagTestCase, MutableOrderedIterableTestCase, MutableBagIterableTestCase +{ + @Override + MutableSortedBag newWith(T... elements); + + @Override + @Test + default void MutableBagIterable_addOccurrences() + { + MutableSortedBag mutableSortedBag = this.newWith(3, 3, 3, 2, 2, 1); + assertEquals(4, mutableSortedBag.addOccurrences(4, 4)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1), mutableSortedBag); + assertEquals(3, mutableSortedBag.addOccurrences(1, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, 1, 1), mutableSortedBag); + assertEquals(3, mutableSortedBag.addOccurrences(1, 0)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, 1, 1), mutableSortedBag); + } + + @Override + @Test(expected = IllegalArgumentException.class) + default void MutableBagIterable_addOccurrences_throws() + { + MutableSortedBag mutableSortedBag = this.newWith(3, 3, 3, 2, 2, 1); + mutableSortedBag.addOccurrences(4, -1); + } + + @Override + @Test + default void MutableBagIterable_removeOccurrences() + { + MutableSortedBag mutableBag = this.newWith(3, 3, 3, 2, 2, 1); + assertFalse(mutableBag.removeOccurrences(4, 4)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2, 1), mutableBag); + assertFalse(mutableBag.removeOccurrences(3, 0)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2, 1), mutableBag); + assertTrue(mutableBag.removeOccurrences(1, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(3, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 2, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(2, 1)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(2, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3), mutableBag); + } + + @Override + @Test(expected = IllegalArgumentException.class) + default void MutableBagIterable_removeOccurrences_throws() + { + MutableSortedBag mutableBag = this.newWith(3, 3, 3, 2, 2, 1); + assertFalse(mutableBag.removeOccurrences(4, -1)); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java new file mode 100644 index 0000000000..e7c1a4ceff --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.collection.mutable; + +import org.eclipse.collections.impl.collection.mutable.AbstractMultiReaderMutableCollection; +import org.junit.Test; + +public interface MultiReaderMutableCollectionTestCase extends MutableCollectionTestCase +{ + @Override + AbstractMultiReaderMutableCollection newWith(T... elements); + + @Test(expected = UnsupportedOperationException.class) + default void Iterable_iterator_throws() + { + this.newWith(3, 2, 1).iterator(); + } + + @Test + @Override + default void Iterable_remove() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_hasNext() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next_throws_at_end() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next_throws_on_empty() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void RichIterable_getFirst() + { + // Does not support iterator outside withReadLockAndDelegate + } + + @Test + @Override + default void RichIterable_getLast() + { + // Does not support iterator outside withReadLockAndDelegate + } + + @Test + @Override + default void RichIterable_getOnly() + { + // Does not support iterator outside withReadLockAndDelegate + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java new file mode 100644 index 0000000000..7cc67698b6 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.list; + +import java.util.Iterator; +import java.util.List; + +import org.eclipse.collections.test.CollectionTestCase; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertThrows; + +public interface ListTestCase extends CollectionTestCase +{ + @Override + List newWith(T... elements); + + @Override + default boolean allowsDuplicates() + { + return true; + } + + @Test + @Override + default void Iterable_remove() + { + List list = this.newWith(3, 3, 3, 2, 2, 1); + Iterator iterator = list.iterator(); + iterator.next(); + iterator.remove(); + assertEquals(this.newWith(3, 3, 2, 2, 1), list); + } + + @Override + default void Iterable_toString() + { + Iterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + Assert.assertEquals("[3, 3, 3, 2, 2, 1]", iterable.toString()); + } + + @Test + default void List_get() + { + List list = this.newWith(1, 2, 3); + assertEquals(Integer.valueOf(1), list.get(0)); + assertEquals(Integer.valueOf(2), list.get(1)); + assertEquals(Integer.valueOf(3), list.get(2)); + } + + @Test(expected = IndexOutOfBoundsException.class) + default void List_get_negative() + { + this.newWith(1, 2, 3).get(-1); + } + + @Test(expected = IndexOutOfBoundsException.class) + default void List_get_out_of_bounds() + { + this.newWith(1, 2, 3).get(4); + } + + @Test + default void List_set() + { + List list = this.newWith(3, 2, 1); + assertEquals(3, list.set(0, 4)); + assertEquals(this.newWith(4, 2, 1), list); + assertEquals(2, list.set(1, 4)); + assertEquals(this.newWith(4, 4, 1), list); + assertEquals(1, list.set(2, 4)); + assertEquals(this.newWith(4, 4, 4), list); + + assertThrows(IndexOutOfBoundsException.class, () -> list.set(-1, 4)); + assertEquals(this.newWith(4, 4, 4), list); + assertThrows(IndexOutOfBoundsException.class, () -> list.set(3, 4)); + assertEquals(this.newWith(4, 4, 4), list); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java new file mode 100644 index 0000000000..1ab531e676 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.list.mutable; + +import java.util.Random; + +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.test.UnmodifiableMutableCollectionTestCase; +import org.eclipse.collections.test.list.UnmodifiableListTestCase; +import org.junit.Assert; +import org.junit.Test; + +public interface UnmodifiableMutableListTestCase extends UnmodifiableMutableCollectionTestCase, UnmodifiableListTestCase, MutableListTestCase +{ + @Override + @Test(expected = UnsupportedOperationException.class) + default void MutableList_sortThis() + { + this.newWith(5, 1, 4, 2, 3).sortThis(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void MutableList_shuffleThis() + { + this.newWith(5, 1, 4, 2, 3).shuffleThis(); + this.newWith(5, 1, 4, 2, 3).shuffleThis(new Random(8)); + } + + @Override + @Test + default void Iterable_remove() + { + UnmodifiableMutableCollectionTestCase.super.Iterable_remove(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void MutableList_sortThis_comparator() + { + this.newWith(5, 1, 4, 2, 3).sortThis(Comparators.reverseNaturalOrder()); + } + + @Override + @Test + default void MutableList_subList_subList_remove() + { + Assert.assertThrows(UnsupportedOperationException.class, () -> this.newWith().subList(0, 0).remove(new Object())); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java new file mode 100644 index 0000000000..8b83fa57e3 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.mutable; + +import java.util.Set; + +import org.eclipse.collections.api.bimap.MutableBiMap; +import org.eclipse.collections.impl.bimap.mutable.HashBiMap; +import org.eclipse.collections.impl.test.junit.Java8Runner; +import org.eclipse.collections.test.set.SetTestCase; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(Java8Runner.class) +public class HashBiMapKeySetTest implements SetTestCase +{ + @SafeVarargs + @Override + public final Set newWith(T... elements) + { + MutableBiMap result = new HashBiMap<>(); + for (T element : elements) + { + if (result.containsKey(element)) + { + throw new IllegalStateException(); + } + result.put(element, element); + } + return result.keySet(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + public void Collection_add() + { + // TODO Move up to a keySet view abstraction + SetTestCase.super.Collection_add(); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java new file mode 100644 index 0000000000..c0c46c3c9a --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.mutable; + +import java.util.Random; +import java.util.Set; + +import org.eclipse.collections.api.map.MutableMap; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.test.junit.Java8Runner; +import org.eclipse.collections.test.set.SetTestCase; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertNull; + +// TODO MapIterable.keySet() should return SetIterable, and use SetIterableTestCase here +@RunWith(Java8Runner.class) +public class UnifiedMapKeySetTest implements SetTestCase +{ + private static final long CURRENT_TIME_MILLIS = System.currentTimeMillis(); + + @SafeVarargs + @Override + public final Set newWith(T... elements) + { + Random random = new Random(CURRENT_TIME_MILLIS); + + MutableMap result = new UnifiedMap<>(); + for (T element : elements) + { + assertNull(result.put(element, random.nextDouble())); + } + return result.keySet(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + public void Collection_add() + { + // TODO Move up to a keySet view abstraction + SetTestCase.super.Collection_add(); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java new file mode 100644 index 0000000000..5b52fbaf34 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.sorted; + +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.SortedSets; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.ordered.SortedIterable; +import org.eclipse.collections.api.set.sorted.MutableSortedSet; +import org.eclipse.collections.api.set.sorted.SortedSetIterable; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.impl.tuple.Tuples; +import org.eclipse.collections.test.SortedIterableTestCase; +import org.eclipse.collections.test.domain.A; +import org.eclipse.collections.test.domain.B; +import org.eclipse.collections.test.domain.C; +import org.eclipse.collections.test.list.TransformsToListTrait; +import org.eclipse.collections.test.set.SetIterableTestCase; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.impl.test.Verify.assertThrows; +import static org.eclipse.collections.test.IterableTestCase.assertEquals; + +public interface SortedSetIterableTestCase extends SetIterableTestCase, SortedIterableTestCase, TransformsToListTrait +{ + @Override + SortedSetIterable newWith(T... elements); + + @Override + default boolean allowsNull() + { + return false; + } + + @Override + default SortedSetIterable getExpectedFiltered(T... elements) + { + return SortedSets.immutable.with(Comparators.reverseNaturalOrder(), elements); + } + + @Override + default MutableSortedSet newMutableForFilter(T... elements) + { + return SortedSets.mutable.with(Comparators.reverseNaturalOrder(), elements); + } + + @Test + default void SortedSetIterable_union() + { + SortedSetIterable union = this.newWith(1, 2, 3).union(this.newWith(3, 4, 5)); + assertEquals(SortedSets.immutable.with(Comparators.reverseNaturalOrder(), 5, 4, 3, 2, 1), union); + } + + @Override + @Test(expected = NoSuchElementException.class) + default void RichIterable_getFirst_empty_null() + { + this.newWith().getFirst(); + } + + @Override + @Test(expected = NoSuchElementException.class) + default void RichIterable_getLast_empty_null() + { + this.newWith().getLast(); + } + + @Override + @Test + default void RichIterable_selectInstancesOf() + { + // Must test with two classes that are mutually Comparable + + SortedSetIterable numbers = this.newWith(new C(4.0), new B(3), new C(2.0), new B(1)); + assertEquals(this.getExpectedFiltered(new B(3), new B(1)), numbers.selectInstancesOf(B.class)); + assertEquals(this.getExpectedFiltered(new C(4.0), new B(3), new C(2.0), new B(1)), numbers.selectInstancesOf(A.class)); + } + + @Override + default void OrderedIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 2, 1).getFirst()); + } + + @Override + @Test + default void OrderedIterable_getFirstOptional() + { + assertEquals(Optional.of(Integer.valueOf(3)), ((OrderedIterable) this.newWith(3, 2, 1)).getFirstOptional()); + } + + @Override + default void OrderedIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 2, 1).getLast()); + } + + @Override + @Test + default void OrderedIterable_getLastOptional() + { + assertEquals(Optional.of(Integer.valueOf(1)), ((OrderedIterable) this.newWith(3, 2, 1)).getLastOptional()); + } + + @Override + default void RichIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 2, 1).getFirst()); + } + + @Override + default void RichIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 2, 1).getLast()); + } + + @Override + default void OrderedIterable_min() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_max() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_min_comparator() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_max_comparator() + { + // Cannot contain duplicates + } + + @Override + @Test + default void OrderedIterable_zipWithIndex() + { + RichIterable iterable = this.newWith(4, 3, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(3, 1), + Tuples.pair(2, 2), + Tuples.pair(1, 3)), + iterable.zipWithIndex().toList()); + } + + @Override + @Test + default void OrderedIterable_zipWithIndex_target() + { + RichIterable iterable = this.newWith(4, 3, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(3, 1), + Tuples.pair(2, 2), + Tuples.pair(1, 3)), + iterable.zipWithIndex(Lists.mutable.empty())); + } + + @Test + default void OrderedIterable_forEach_from_to() + { + SortedIterable integers = this.newWith(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + + MutableList result = Lists.mutable.empty(); + integers.forEach(5, 7, result::add); + assertEquals(Lists.immutable.with(4, 3, 2), result); + + MutableList result2 = Lists.mutable.empty(); + integers.forEach(5, 5, result2::add); + assertEquals(Lists.immutable.with(4), result2); + + MutableList result3 = Lists.mutable.empty(); + integers.forEach(0, 9, result3::add); + assertEquals(Lists.immutable.with(9, 8, 7, 6, 5, 4, 3, 2, 1, 0), result3); + + MutableList result4 = Lists.mutable.empty(); + integers.forEach(0, 0, result4::add); + assertEquals(Lists.immutable.with(9), result4); + + MutableList result5 = Lists.mutable.empty(); + integers.forEach(9, 9, result5::add); + assertEquals(Lists.immutable.with(0), result5); + + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(-1, 0, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(0, -1, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(0, 10, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(10, 0, result::add)); + } + + @Test + default void OrderedIterable_forEach_from_to_reverse_order() + { + SortedIterable integers = this.newWith(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + MutableList result = Lists.mutable.empty(); + assertThrows(IllegalArgumentException.class, () -> integers.forEach(7, 5, result::add)); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java new file mode 100644 index 0000000000..0b06d39e66 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2021 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.stack; + +import java.util.EmptyStackException; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.Stacks; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.stack.MutableStack; +import org.eclipse.collections.api.stack.StackIterable; +import org.eclipse.collections.impl.block.factory.Procedures; +import org.eclipse.collections.test.OrderedIterableWithDuplicatesTestCase; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.fail; + +public interface StackIterableTestCase extends OrderedIterableWithDuplicatesTestCase, TransformsToStackTrait +{ + @Override + StackIterable newWith(T... elements); + + @Override + default void newMutable_sanity() + { + // Cannot treat an ArrayStack as a MutableCollection + } + + @Override + default StackIterable getExpectedFiltered(T... elements) + { + return Stacks.immutable.withReversed(elements); + } + + @Override + default MutableList newMutableForFilter(T... elements) + { + return Lists.mutable.with(elements); + } + + @Override + @Test + default void InternalIterable_forEach() + { + RichIterable integers = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + integers.forEach(Procedures.cast(result::push)); + assertEquals(this.newWith(1, 2, 2, 3, 3, 3), result); + } + + @Override + @Test + default void RichIterable_tap() + { + RichIterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + iterable.tap(result::push).forEach(Procedures.noop()); + assertEquals(this.newWith(1, 2, 2, 3, 3, 3), result); + + this.newWith().tap(Procedures.cast(each -> fail())); + } + + @Override + default void InternalIterable_forEachWith() + { + RichIterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + iterable.forEachWith((argument1, argument2) -> result.push(argument1 + argument2), 10); + assertEquals(this.getExpectedFiltered(11, 12, 12, 13, 13, 13), result); + } + + @Override + @Test + default void RichIterable_getFirst_and_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith()::getLast); + } + + @Override + @Test + default void RichIterable_getFirst_empty_null() + { + assertThrows(EmptyStackException.class, this.newWith()::getFirst); + } + + @Override + @Test + default void RichIterable_getLast_empty_null() + { + assertThrows(UnsupportedOperationException.class, this.newWith()::getLast); + } + + @Override + @Test + default void RichIterable_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith(3, 3, 3, 2, 2, 1)::getLast); + } + + @Override + @Test + default void OrderedIterable_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith(3, 3, 3, 2, 2, 1)::getLast); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void OrderedIterable_getLastOptional() + { + ((OrderedIterable) this.newWith(3, 2, 1)).getLastOptional(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void OrderedIterable_getLastOptional_null_element() + { + ((OrderedIterable) this.newWith(new Object[]{null})).getLastOptional(); + } + + @Test + default void StackIterable_peek() + { + assertEquals(Integer.valueOf(5), this.newWith(5, 1, 4, 2, 3).peek()); + } + + @Test(expected = EmptyStackException.class) + default void StackIterable_peek_throws() + { + this.newWith().peek(); + } + + @Test + default void StackIterable_peekAt() + { + assertEquals(Integer.valueOf(5), this.newWith(5, 1, 4, 2, 3).peekAt(0)); + assertEquals(Integer.valueOf(1), this.newWith(5, 1, 4, 2, 3).peekAt(1)); + assertEquals(Integer.valueOf(4), this.newWith(5, 1, 4, 2, 3).peekAt(2)); + assertEquals(Integer.valueOf(2), this.newWith(5, 1, 4, 2, 3).peekAt(3)); + assertEquals(Integer.valueOf(3), this.newWith(5, 1, 4, 2, 3).peekAt(4)); + } + + @Test + default void StackIterable_peekAt_throws() + { + StackIterable stackIterable = this.newWith(5, 1, 4, 2, 3); + assertThrows(IllegalArgumentException.class, () -> stackIterable.peekAt(-1)); + assertThrows(IllegalArgumentException.class, () -> stackIterable.peekAt(5)); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java new file mode 100644 index 0000000000..3811ee7f27 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-4081c367bee996eb08efec159c41041f2beed3c3/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.stack.mutable; + +import org.eclipse.collections.api.stack.MutableStack; +import org.eclipse.collections.test.FixedSizeIterableTestCase; +import org.junit.Test; + +public interface UnmodifiableMutableStackTestCase extends MutableStackTestCase, FixedSizeIterableTestCase +{ + @Override + @Test + default void Iterable_remove() + { + FixedSizeIterableTestCase.super.Iterable_remove(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void MutableStack_pop() + { + MutableStack mutableStack = this.newWith(5, 1, 4, 2, 3); + mutableStack.pop(); + } + + @Override + @Test(expected = UnsupportedOperationException.class) + default void MutableStack_pop_throws() + { + MutableStack mutableStack = this.newWith(); + mutableStack.pop(); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.json b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.json new file mode 100644 index 0000000000..5e4e532843 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7.json @@ -0,0 +1 @@ +{"parentCommitId":"4081c367bee996eb08efec159c41041f2beed3c3","currentCommitId":"f26addbce8e843f208805aa22f45dcfb6f8177f7","filesBefore":["unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java"],"filesCurrent":["unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable","unit-tests-java8/src/test","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted","unit-tests-java8/src/test/java/org/eclipse/collections/test/set","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable","unit-tests-java8/src/test/java/org/eclipse","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable","unit-tests-java8/src/test/java/org/eclipse/collections","unit-tests-java8/src/test/java/org","unit-tests-java8/src","unit-tests-java8/src/test/java/org/eclipse/collections/test","unit-tests-java8/src/test/java","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable","unit-tests-java8","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag","unit-tests-java8/src/test/java/org/eclipse/collections/test/list"],"repositoryDirectoriesCurrent":["unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable","unit-tests-java8/src/test","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack","unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted","unit-tests-java8/src/test/java/org/eclipse/collections/test/set","unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable","unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable","unit-tests-java8/src/test/java/org/eclipse","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection","unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable","unit-tests-java8/src/test/java/org/eclipse/collections","unit-tests-java8/src/test/java/org","unit-tests-java8/src","unit-tests-java8/src/test/java/org/eclipse/collections/test","unit-tests-java8/src/test/java","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable","unit-tests-java8","unit-tests-java8/src/test/java/org/eclipse/collections/test/bag","unit-tests-java8/src/test/java/org/eclipse/collections/test/list"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java new file mode 100644 index 0000000000..538de6ef5a --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/IterableTestCase.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test; + +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.SortedMap; +import java.util.SortedSet; + +import org.eclipse.collections.api.LazyBooleanIterable; +import org.eclipse.collections.api.LazyByteIterable; +import org.eclipse.collections.api.LazyCharIterable; +import org.eclipse.collections.api.LazyDoubleIterable; +import org.eclipse.collections.api.LazyFloatIterable; +import org.eclipse.collections.api.LazyIntIterable; +import org.eclipse.collections.api.LazyIterable; +import org.eclipse.collections.api.LazyLongIterable; +import org.eclipse.collections.api.LazyShortIterable; +import org.eclipse.collections.api.collection.ImmutableCollection; +import org.eclipse.collections.api.collection.MutableCollection; +import org.eclipse.collections.api.factory.Sets; +import org.eclipse.collections.api.list.ListIterable; +import org.eclipse.collections.api.list.primitive.BooleanList; +import org.eclipse.collections.api.list.primitive.ByteList; +import org.eclipse.collections.api.list.primitive.CharList; +import org.eclipse.collections.api.list.primitive.DoubleList; +import org.eclipse.collections.api.list.primitive.FloatList; +import org.eclipse.collections.api.list.primitive.IntList; +import org.eclipse.collections.api.list.primitive.LongList; +import org.eclipse.collections.api.list.primitive.ShortList; +import org.eclipse.collections.api.ordered.ReversibleIterable; +import org.eclipse.collections.api.ordered.SortedIterable; +import org.eclipse.collections.api.set.MutableSet; +import org.eclipse.collections.impl.list.mutable.MultiReaderFastList; +import org.eclipse.collections.impl.test.SerializeTestHelper; +import org.eclipse.collections.impl.test.Verify; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.impl.test.Verify.assertIterablesEqual; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public interface IterableTestCase +{ + Iterable newWith(T... elements); + + boolean allowsDuplicates(); + + static void assertEquals(Object o1, Object o2) + { + if (o1 instanceof ListIterable && o2 instanceof LazyIterable) + { + IterableTestCase.assertEquals(o1, ((LazyIterable) o2).toList()); + return; + } + if (o1 instanceof BooleanList && o2 instanceof LazyBooleanIterable) + { + IterableTestCase.assertEquals(o1, ((LazyBooleanIterable) o2).toList()); + return; + } + if (o1 instanceof ByteList && o2 instanceof LazyByteIterable) + { + IterableTestCase.assertEquals(o1, ((LazyByteIterable) o2).toList()); + return; + } + if (o1 instanceof CharList && o2 instanceof LazyCharIterable) + { + IterableTestCase.assertEquals(o1, ((LazyCharIterable) o2).toList()); + return; + } + if (o1 instanceof DoubleList && o2 instanceof LazyDoubleIterable) + { + IterableTestCase.assertEquals(o1, ((LazyDoubleIterable) o2).toList()); + return; + } + if (o1 instanceof FloatList && o2 instanceof LazyFloatIterable) + { + IterableTestCase.assertEquals(o1, ((LazyFloatIterable) o2).toList()); + return; + } + if (o1 instanceof IntList && o2 instanceof LazyIntIterable) + { + IterableTestCase.assertEquals(o1, ((LazyIntIterable) o2).toList()); + return; + } + if (o1 instanceof LongList && o2 instanceof LazyLongIterable) + { + IterableTestCase.assertEquals(o1, ((LazyLongIterable) o2).toList()); + return; + } + if (o1 instanceof ShortList && o2 instanceof LazyShortIterable) + { + IterableTestCase.assertEquals(o1, ((LazyShortIterable) o2).toList()); + return; + } + + Assert.assertEquals(o1, o2); + + assertFalse("Neither item should equal null", o1.equals(null)); + assertFalse("Neither item should equal null", o2.equals(null)); + assertNotEquals("Neither item should equal new Object()", o1.equals(new Object())); + assertNotEquals("Neither item should equal new Object()", o2.equals(new Object())); + Assert.assertEquals(o1, o1); + Assert.assertEquals(o2, o2); + Assert.assertEquals(o1, o2); + Assert.assertEquals(o2, o1); + Assert.assertEquals(o1.hashCode(), o2.hashCode()); + + checkNotSame(o1, o2); + + if (o1 instanceof MultiReaderFastList || o2 instanceof MultiReaderFastList) + { + return; + } + if (o1 instanceof SortedIterable || o2 instanceof SortedIterable + || o1 instanceof ReversibleIterable || o2 instanceof ReversibleIterable + || o1 instanceof List || o2 instanceof List + || o1 instanceof SortedSet || o2 instanceof SortedSet) + { + assertIterablesEqual((Iterable) o1, (Iterable) o2); + if (o1 instanceof SortedIterable || o2 instanceof SortedIterable) + { + Comparator comparator1 = ((SortedIterable) o1).comparator(); + Comparator comparator2 = ((SortedIterable) o2).comparator(); + if (comparator1 != null && comparator2 != null) + { + assertSame(comparator1.getClass(), comparator2.getClass()); + } + } + } + else if (o1 instanceof SortedMap || o2 instanceof SortedMap) + { + IterableTestCase.assertEquals(((SortedMap) o1).keySet(), ((SortedMap) o2).keySet()); + } + } + + static void checkNotSame(Object o1, Object o2) + { + if (o1 instanceof String && o2 instanceof String) + { + return; + } + if ((o1 instanceof Number && o2 instanceof Number) + || (o1 instanceof Boolean && o2 instanceof Boolean) + || o1 instanceof ImmutableCollection && o2 instanceof ImmutableCollection + && ((ImmutableCollection) o1).isEmpty() && ((ImmutableCollection) o2).isEmpty() + && !(o1 instanceof SortedIterable) && !(o2 instanceof SortedIterable)) + { + assertSame(o1, o2); + return; + } + assertNotSame(o1, o2); + } + + static void assertNotEquals(Object o1, Object o2) + { + Assert.assertNotEquals(o1, o2); + Assert.assertNotEquals(o2, o1); + + assertFalse("Neither item should equal null", o1.equals(null)); + assertFalse("Neither item should equal null", o2.equals(null)); + Assert.assertNotEquals("Neither item should equal new Object()", o1.equals(new Object())); + Assert.assertNotEquals("Neither item should equal new Object()", o2.equals(new Object())); + Assert.assertEquals(o1, o1); + Assert.assertEquals(o2, o2); + } + + static void addAllTo(T[] elements, MutableCollection result) + { + for (T element : elements) + { + if (!result.add(element)) + { + throw new IllegalStateException(); + } + } + } + + @Test + default void Object_PostSerializedEqualsAndHashCode() + { + Iterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + Object deserialized = SerializeTestHelper.serializeDeserialize(iterable); + assertNotSame(iterable, deserialized); + } + + @Test + default void Object_equalsAndHashCode() + { + Verify.assertEqualsAndHashCode(this.newWith(3, 3, 3, 2, 2, 1), this.newWith(3, 3, 3, 2, 2, 1)); + + assertNotEquals(this.newWith(4, 3, 2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(4, 3, 2, 1)); + + assertNotEquals(this.newWith(2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(2, 1)); + + assertNotEquals(this.newWith(3, 3, 2, 1), this.newWith(3, 2, 1)); + assertNotEquals(this.newWith(3, 2, 1), this.newWith(3, 3, 2, 1)); + + assertNotEquals(this.newWith(3, 3, 2, 1), this.newWith(3, 2, 2, 1)); + assertNotEquals(this.newWith(3, 2, 2, 1), this.newWith(3, 3, 2, 1)); + } + + @Test + default void Iterable_hasNext() + { + assertTrue(this.newWith(3, 2, 1).iterator().hasNext()); + assertFalse(this.newWith().iterator().hasNext()); + } + + @Test + default void Iterable_next() + { + Iterator iterator = this.newWith(3, 2, 1).iterator(); + MutableSet set = Sets.mutable.with(); + assertTrue(set.add(iterator.next())); + assertTrue(set.add(iterator.next())); + assertTrue(set.add(iterator.next())); + IterableTestCase.assertEquals(Sets.immutable.with(3, 2, 1), set); + } + + @Test + default void Iterable_next_throws_on_empty() + { + assertThrows(NoSuchElementException.class, () -> this.newWith().iterator().next()); + } + + @Test + default void Iterable_next_throws_at_end() + { + Iterable iterable = this.newWith(3, 2, 1); + Iterator iterator = iterable.iterator(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertTrue(iterator.hasNext()); + iterator.next(); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + + Iterator iterator2 = iterable.iterator(); + iterator2.next(); + iterator2.next(); + iterator2.next(); + assertThrows(NoSuchElementException.class, iterator2::next); + assertThrows(NoSuchElementException.class, iterator2::next); + } + + void Iterable_remove(); + + void Iterable_toString(); +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java new file mode 100644 index 0000000000..2f6c754094 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/OrderedIterableTestCase.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2021 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test; + +import java.util.Iterator; +import java.util.Optional; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.Sets; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.tuple.Pair; +import org.eclipse.collections.api.tuple.primitive.ObjectIntPair; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.impl.factory.primitive.IntLists; +import org.eclipse.collections.impl.factory.primitive.IntSets; +import org.eclipse.collections.impl.tuple.Tuples; +import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; + +public interface OrderedIterableTestCase extends RichIterableTestCase +{ + /** + * @since 9.1. + */ + @Test + default void OrderedIterable_collectWithIndex() + { + RichIterable> pairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair); + Assert.assertEquals( + IntLists.mutable.with(0, 1, 2, 3), + pairs.collectInt(ObjectIntPair::getTwo, IntLists.mutable.empty())); + Assert.assertEquals( + Lists.mutable.with(3, 2, 1, 0), + pairs.collect(ObjectIntPair::getOne, Lists.mutable.empty())); + } + + /** + * @since 9.1. + */ + @Test + default void OrderedIterable_collectWithIndexWithTarget() + { + RichIterable> pairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair, Lists.mutable.empty()); + Assert.assertEquals( + IntLists.mutable.with(0, 1, 2, 3), + pairs.collectInt(ObjectIntPair::getTwo, IntLists.mutable.empty())); + Assert.assertEquals( + Lists.mutable.with(3, 2, 1, 0), + pairs.collect(ObjectIntPair::getOne, Lists.mutable.empty())); + + RichIterable> setOfPairs = ((OrderedIterable) this.newWith(3, 2, 1, 0)) + .collectWithIndex(PrimitiveTuples::pair, Lists.mutable.empty()); + Assert.assertEquals( + IntSets.mutable.with(0, 1, 2, 3), + setOfPairs.collectInt(ObjectIntPair::getTwo, IntSets.mutable.empty())); + Assert.assertEquals( + Sets.mutable.with(3, 2, 1, 0), + setOfPairs.collect(ObjectIntPair::getOne, Sets.mutable.empty())); + } + + @Test + default void OrderedIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 3, 3, 2, 2, 1).getFirst()); + } + + @Test + default void OrderedIterable_getFirstOptional_empty() + { + assertSame(Optional.empty(), ((OrderedIterable) this.newWith()).getFirstOptional()); + } + + @Test + default void OrderedIterable_getFirstOptional() + { + assertEquals(Optional.of(Integer.valueOf(3)), ((OrderedIterable) this.newWith(3, 3, 3, 2, 2, 1)).getFirstOptional()); + } + + @Test + default void OrderedIterable_getFirstOptional_null_element() + { + assertThrows(NullPointerException.class, () -> ((OrderedIterable) this.newWith(new Object[]{null})).getFirstOptional()); + } + + @Test + default void OrderedIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 3, 3, 2, 2, 1).getLast()); + } + + @Test + default void OrderedIterable_getLastOptional_empty() + { + assertSame(Optional.empty(), ((OrderedIterable) this.newWith()).getLastOptional()); + } + + @Test + default void OrderedIterable_getLastOptional() + { + assertEquals(Optional.of(Integer.valueOf(1)), ((OrderedIterable) this.newWith(3, 3, 3, 2, 2, 1)).getLastOptional()); + } + + @Test(expected = NullPointerException.class) + default void OrderedIterable_getLastOptional_null_element() + { + ((OrderedIterable) this.newWith(new Object[]{null})).getLastOptional(); + } + + @Test + default void OrderedIterable_next() + { + Iterator iterator = this.newWith(3, 2, 1).iterator(); + assertEquals(Integer.valueOf(3), iterator.next()); + assertEquals(Integer.valueOf(2), iterator.next()); + assertEquals(Integer.valueOf(1), iterator.next()); + } + + @Test + default void OrderedIterable_min() + { + Holder first = new Holder<>(-1); + Holder second = new Holder<>(-1); + assertSame(first, this.newWith(new Holder<>(2), first, new Holder<>(0), second).min()); + } + + @Test + default void OrderedIterable_max() + { + Holder first = new Holder<>(1); + Holder second = new Holder<>(1); + assertSame(first, this.newWith(new Holder<>(-2), first, new Holder<>(0), second).max()); + } + + @Test + default void OrderedIterable_min_comparator() + { + Holder first = new Holder<>(1); + Holder second = new Holder<>(1); + assertSame(first, this.newWith(new Holder<>(-2), first, new Holder<>(0), second).min(Comparators.reverseNaturalOrder())); + } + + @Test + default void OrderedIterable_max_comparator() + { + Holder first = new Holder<>(-1); + Holder second = new Holder<>(-1); + assertSame(first, this.newWith(new Holder<>(2), first, new Holder<>(0), second).max(Comparators.reverseNaturalOrder())); + } + + @Test + default void OrderedIterable_zipWithIndex() + { + RichIterable iterable = this.newWith(4, 4, 4, 4, 3, 3, 3, 2, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(4, 1), + Tuples.pair(4, 2), + Tuples.pair(4, 3), + Tuples.pair(3, 4), + Tuples.pair(3, 5), + Tuples.pair(3, 6), + Tuples.pair(2, 7), + Tuples.pair(2, 8), + Tuples.pair(1, 9)), + iterable.zipWithIndex().toList()); + } + + @Test + default void OrderedIterable_zipWithIndex_target() + { + RichIterable iterable = this.newWith(4, 4, 4, 4, 3, 3, 3, 2, 2, 1); + MutableList> target = Lists.mutable.empty(); + MutableList> result = iterable.zipWithIndex(target); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(4, 1), + Tuples.pair(4, 2), + Tuples.pair(4, 3), + Tuples.pair(3, 4), + Tuples.pair(3, 5), + Tuples.pair(3, 6), + Tuples.pair(2, 7), + Tuples.pair(2, 8), + Tuples.pair(1, 9)), + result); + assertSame(target, result); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java new file mode 100644 index 0000000000..acd57a080a --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/bag/mutable/sorted/MutableSortedBagTestCase.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.bag.mutable.sorted; + +import org.eclipse.collections.api.bag.sorted.MutableSortedBag; +import org.eclipse.collections.impl.bag.sorted.mutable.TreeBag; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.test.MutableOrderedIterableTestCase; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public interface MutableSortedBagTestCase extends SortedBagTestCase, MutableOrderedIterableTestCase, MutableBagIterableTestCase +{ + @Override + MutableSortedBag newWith(T... elements); + + @Override + @Test + default void MutableBagIterable_addOccurrences() + { + MutableSortedBag mutableSortedBag = this.newWith(3, 3, 3, 2, 2, 1); + assertEquals(4, mutableSortedBag.addOccurrences(4, 4)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1), mutableSortedBag); + assertEquals(3, mutableSortedBag.addOccurrences(1, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, 1, 1), mutableSortedBag); + assertEquals(3, mutableSortedBag.addOccurrences(1, 0)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, 1, 1), mutableSortedBag); + } + + @Override + @Test + default void MutableBagIterable_addOccurrences_throws() + { + MutableSortedBag mutableSortedBag = this.newWith(3, 3, 3, 2, 2, 1); + assertThrows(IllegalArgumentException.class, () -> mutableSortedBag.addOccurrences(4, -1)); + } + + @Override + @Test + default void MutableBagIterable_removeOccurrences() + { + MutableSortedBag mutableBag = this.newWith(3, 3, 3, 2, 2, 1); + assertFalse(mutableBag.removeOccurrences(4, 4)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2, 1), mutableBag); + assertFalse(mutableBag.removeOccurrences(3, 0)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2, 1), mutableBag); + assertTrue(mutableBag.removeOccurrences(1, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 3, 3, 2, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(3, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 2, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(2, 1)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3, 2), mutableBag); + assertTrue(mutableBag.removeOccurrences(2, 2)); + assertEquals(TreeBag.newBagWith(Comparators.reverseNaturalOrder(), 3), mutableBag); + } + + @Override + @Test + default void MutableBagIterable_removeOccurrences_throws() + { + assertThrows(IllegalArgumentException.class, () -> { + MutableSortedBag mutableBag = this.newWith(3, 3, 3, 2, 2, 1); + assertFalse(mutableBag.removeOccurrences(4, -1)); + }); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java new file mode 100644 index 0000000000..fc6546a23f --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/collection/mutable/MultiReaderMutableCollectionTestCase.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.collection.mutable; + +import org.eclipse.collections.impl.collection.mutable.AbstractMultiReaderMutableCollection; +import org.junit.Test; + +import static org.junit.Assert.assertThrows; + +public interface MultiReaderMutableCollectionTestCase extends MutableCollectionTestCase +{ + @Override + AbstractMultiReaderMutableCollection newWith(T... elements); + + @Test + default void Iterable_iterator_throws() + { + assertThrows(UnsupportedOperationException.class, () -> this.newWith(3, 2, 1).iterator()); + } + + @Test + @Override + default void Iterable_remove() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_hasNext() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next_throws_at_end() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void Iterable_next_throws_on_empty() + { + // Multi-reader collections don't support iterator() + } + + @Test + @Override + default void RichIterable_getFirst() + { + // Does not support iterator outside withReadLockAndDelegate + } + + @Test + @Override + default void RichIterable_getLast() + { + // Does not support iterator outside withReadLockAndDelegate + } + + @Test + @Override + default void RichIterable_getOnly() + { + // Does not support iterator outside withReadLockAndDelegate + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java new file mode 100644 index 0000000000..de48cef549 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/ListTestCase.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.list; + +import java.util.Iterator; +import java.util.List; + +import org.eclipse.collections.test.CollectionTestCase; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertThrows; + +public interface ListTestCase extends CollectionTestCase +{ + @Override + List newWith(T... elements); + + @Override + default boolean allowsDuplicates() + { + return true; + } + + @Test + @Override + default void Iterable_remove() + { + List list = this.newWith(3, 3, 3, 2, 2, 1); + Iterator iterator = list.iterator(); + iterator.next(); + iterator.remove(); + assertEquals(this.newWith(3, 3, 2, 2, 1), list); + } + + @Override + default void Iterable_toString() + { + Iterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + Assert.assertEquals("[3, 3, 3, 2, 2, 1]", iterable.toString()); + } + + @Test + default void List_get() + { + List list = this.newWith(1, 2, 3); + assertEquals(Integer.valueOf(1), list.get(0)); + assertEquals(Integer.valueOf(2), list.get(1)); + assertEquals(Integer.valueOf(3), list.get(2)); + } + + @Test + default void List_get_negative() + { + assertThrows(IndexOutOfBoundsException.class, () -> this.newWith(1, 2, 3).get(-1)); + } + + @Test + default void List_get_out_of_bounds() + { + assertThrows(IndexOutOfBoundsException.class, () -> this.newWith(1, 2, 3).get(4)); + } + + @Test + default void List_set() + { + List list = this.newWith(3, 2, 1); + assertEquals(3, list.set(0, 4)); + assertEquals(this.newWith(4, 2, 1), list); + assertEquals(2, list.set(1, 4)); + assertEquals(this.newWith(4, 4, 1), list); + assertEquals(1, list.set(2, 4)); + assertEquals(this.newWith(4, 4, 4), list); + + assertThrows(IndexOutOfBoundsException.class, () -> list.set(-1, 4)); + assertEquals(this.newWith(4, 4, 4), list); + assertThrows(IndexOutOfBoundsException.class, () -> list.set(3, 4)); + assertEquals(this.newWith(4, 4, 4), list); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java new file mode 100644 index 0000000000..9ec297d7b1 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/list/mutable/UnmodifiableMutableListTestCase.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.list.mutable; + +import java.util.Random; + +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.test.UnmodifiableMutableCollectionTestCase; +import org.eclipse.collections.test.list.UnmodifiableListTestCase; +import org.junit.Test; + +import static org.junit.Assert.assertThrows; + +public interface UnmodifiableMutableListTestCase extends UnmodifiableMutableCollectionTestCase, UnmodifiableListTestCase, MutableListTestCase +{ + @Override + @Test + default void MutableList_sortThis() + { + assertThrows(UnsupportedOperationException.class, () -> this.newWith(5, 1, 4, 2, 3).sortThis()); + } + + @Override + @Test + default void MutableList_shuffleThis() + { + assertThrows(UnsupportedOperationException.class, () -> this.newWith(5, 1, 4, 2, 3).shuffleThis()); + assertThrows(UnsupportedOperationException.class, () -> this.newWith(5, 1, 4, 2, 3).shuffleThis(new Random(8))); + } + + @Override + @Test + default void Iterable_remove() + { + UnmodifiableMutableCollectionTestCase.super.Iterable_remove(); + } + + @Override + @Test + default void MutableList_sortThis_comparator() + { + assertThrows(UnsupportedOperationException.class, () -> + this.newWith(5, 1, 4, 2, 3).sortThis(Comparators.reverseNaturalOrder())); + } + + @Override + @Test + default void MutableList_subList_subList_remove() + { + assertThrows(UnsupportedOperationException.class, () -> this.newWith().subList(0, 0).remove(new Object())); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java new file mode 100644 index 0000000000..94a9d702cc --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/HashBiMapKeySetTest.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.mutable; + +import java.util.Set; + +import org.eclipse.collections.api.bimap.MutableBiMap; +import org.eclipse.collections.impl.bimap.mutable.HashBiMap; +import org.eclipse.collections.impl.test.junit.Java8Runner; +import org.eclipse.collections.test.set.SetTestCase; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertThrows; + +@RunWith(Java8Runner.class) +public class HashBiMapKeySetTest implements SetTestCase +{ + @SafeVarargs + @Override + public final Set newWith(T... elements) + { + MutableBiMap result = new HashBiMap<>(); + for (T element : elements) + { + if (result.containsKey(element)) + { + throw new IllegalStateException(); + } + result.put(element, element); + } + return result.keySet(); + } + + @Override + @Test + public void Collection_add() + { + // TODO Move up to a keySet view abstraction + assertThrows(UnsupportedOperationException.class, () -> SetTestCase.super.Collection_add()); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java new file mode 100644 index 0000000000..50cb522115 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/mutable/UnifiedMapKeySetTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.mutable; + +import java.util.Random; +import java.util.Set; + +import org.eclipse.collections.api.map.MutableMap; +import org.eclipse.collections.impl.map.mutable.UnifiedMap; +import org.eclipse.collections.impl.test.junit.Java8Runner; +import org.eclipse.collections.test.set.SetTestCase; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; + +// TODO MapIterable.keySet() should return SetIterable, and use SetIterableTestCase here +@RunWith(Java8Runner.class) +public class UnifiedMapKeySetTest implements SetTestCase +{ + private static final long CURRENT_TIME_MILLIS = System.currentTimeMillis(); + + @SafeVarargs + @Override + public final Set newWith(T... elements) + { + Random random = new Random(CURRENT_TIME_MILLIS); + + MutableMap result = new UnifiedMap<>(); + for (T element : elements) + { + assertNull(result.put(element, random.nextDouble())); + } + return result.keySet(); + } + + @Override + @Test + public void Collection_add() + { + // TODO Move up to a keySet view abstraction + assertThrows(UnsupportedOperationException.class, () -> SetTestCase.super.Collection_add()); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java new file mode 100644 index 0000000000..91e4d97b7d --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/set/sorted/SortedSetIterableTestCase.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2021 Goldman Sachs. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.set.sorted; + +import java.util.NoSuchElementException; +import java.util.Optional; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.SortedSets; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.ordered.SortedIterable; +import org.eclipse.collections.api.set.sorted.MutableSortedSet; +import org.eclipse.collections.api.set.sorted.SortedSetIterable; +import org.eclipse.collections.impl.block.factory.Comparators; +import org.eclipse.collections.impl.tuple.Tuples; +import org.eclipse.collections.test.SortedIterableTestCase; +import org.eclipse.collections.test.domain.A; +import org.eclipse.collections.test.domain.B; +import org.eclipse.collections.test.domain.C; +import org.eclipse.collections.test.list.TransformsToListTrait; +import org.eclipse.collections.test.set.SetIterableTestCase; +import org.junit.Assert; +import org.junit.Test; + +import static org.eclipse.collections.impl.test.Verify.assertThrows; +import static org.eclipse.collections.test.IterableTestCase.assertEquals; + +public interface SortedSetIterableTestCase extends SetIterableTestCase, SortedIterableTestCase, TransformsToListTrait +{ + @Override + SortedSetIterable newWith(T... elements); + + @Override + default boolean allowsNull() + { + return false; + } + + @Override + default SortedSetIterable getExpectedFiltered(T... elements) + { + return SortedSets.immutable.with(Comparators.reverseNaturalOrder(), elements); + } + + @Override + default MutableSortedSet newMutableForFilter(T... elements) + { + return SortedSets.mutable.with(Comparators.reverseNaturalOrder(), elements); + } + + @Test + default void SortedSetIterable_union() + { + SortedSetIterable union = this.newWith(1, 2, 3).union(this.newWith(3, 4, 5)); + assertEquals(SortedSets.immutable.with(Comparators.reverseNaturalOrder(), 5, 4, 3, 2, 1), union); + } + + @Override + @Test + default void RichIterable_getFirst_empty_null() + { + Assert.assertThrows(NoSuchElementException.class, () -> this.newWith().getFirst()); + } + + @Override + @Test + default void RichIterable_getLast_empty_null() + { + Assert.assertThrows(NoSuchElementException.class, () -> this.newWith().getLast()); + } + + @Override + @Test + default void RichIterable_selectInstancesOf() + { + // Must test with two classes that are mutually Comparable + + SortedSetIterable numbers = this.newWith(new C(4.0), new B(3), new C(2.0), new B(1)); + assertEquals(this.getExpectedFiltered(new B(3), new B(1)), numbers.selectInstancesOf(B.class)); + assertEquals(this.getExpectedFiltered(new C(4.0), new B(3), new C(2.0), new B(1)), numbers.selectInstancesOf(A.class)); + } + + @Override + default void OrderedIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 2, 1).getFirst()); + } + + @Override + @Test + default void OrderedIterable_getFirstOptional() + { + assertEquals(Optional.of(Integer.valueOf(3)), ((OrderedIterable) this.newWith(3, 2, 1)).getFirstOptional()); + } + + @Override + default void OrderedIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 2, 1).getLast()); + } + + @Override + @Test + default void OrderedIterable_getLastOptional() + { + assertEquals(Optional.of(Integer.valueOf(1)), ((OrderedIterable) this.newWith(3, 2, 1)).getLastOptional()); + } + + @Override + default void RichIterable_getFirst() + { + assertEquals(Integer.valueOf(3), this.newWith(3, 2, 1).getFirst()); + } + + @Override + default void RichIterable_getLast() + { + assertEquals(Integer.valueOf(1), this.newWith(3, 2, 1).getLast()); + } + + @Override + default void OrderedIterable_min() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_max() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_min_comparator() + { + // Cannot contain duplicates + } + + @Override + default void OrderedIterable_max_comparator() + { + // Cannot contain duplicates + } + + @Override + @Test + default void OrderedIterable_zipWithIndex() + { + RichIterable iterable = this.newWith(4, 3, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(3, 1), + Tuples.pair(2, 2), + Tuples.pair(1, 3)), + iterable.zipWithIndex().toList()); + } + + @Override + @Test + default void OrderedIterable_zipWithIndex_target() + { + RichIterable iterable = this.newWith(4, 3, 2, 1); + Assert.assertEquals( + Lists.immutable.with( + Tuples.pair(4, 0), + Tuples.pair(3, 1), + Tuples.pair(2, 2), + Tuples.pair(1, 3)), + iterable.zipWithIndex(Lists.mutable.empty())); + } + + @Test + default void OrderedIterable_forEach_from_to() + { + SortedIterable integers = this.newWith(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + + MutableList result = Lists.mutable.empty(); + integers.forEach(5, 7, result::add); + assertEquals(Lists.immutable.with(4, 3, 2), result); + + MutableList result2 = Lists.mutable.empty(); + integers.forEach(5, 5, result2::add); + assertEquals(Lists.immutable.with(4), result2); + + MutableList result3 = Lists.mutable.empty(); + integers.forEach(0, 9, result3::add); + assertEquals(Lists.immutable.with(9, 8, 7, 6, 5, 4, 3, 2, 1, 0), result3); + + MutableList result4 = Lists.mutable.empty(); + integers.forEach(0, 0, result4::add); + assertEquals(Lists.immutable.with(9), result4); + + MutableList result5 = Lists.mutable.empty(); + integers.forEach(9, 9, result5::add); + assertEquals(Lists.immutable.with(0), result5); + + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(-1, 0, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(0, -1, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(0, 10, result::add)); + assertThrows(IndexOutOfBoundsException.class, () -> integers.forEach(10, 0, result::add)); + } + + @Test + default void OrderedIterable_forEach_from_to_reverse_order() + { + SortedIterable integers = this.newWith(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + MutableList result = Lists.mutable.empty(); + assertThrows(IllegalArgumentException.class, () -> integers.forEach(7, 5, result::add)); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java new file mode 100644 index 0000000000..fc525e301d --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/StackIterableTestCase.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2021 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.stack; + +import java.util.EmptyStackException; + +import org.eclipse.collections.api.RichIterable; +import org.eclipse.collections.api.factory.Lists; +import org.eclipse.collections.api.factory.Stacks; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.api.ordered.OrderedIterable; +import org.eclipse.collections.api.stack.MutableStack; +import org.eclipse.collections.api.stack.StackIterable; +import org.eclipse.collections.impl.block.factory.Procedures; +import org.eclipse.collections.test.OrderedIterableWithDuplicatesTestCase; +import org.junit.Test; + +import static org.eclipse.collections.test.IterableTestCase.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.fail; + +public interface StackIterableTestCase extends OrderedIterableWithDuplicatesTestCase, TransformsToStackTrait +{ + @Override + StackIterable newWith(T... elements); + + @Override + default void newMutable_sanity() + { + // Cannot treat an ArrayStack as a MutableCollection + } + + @Override + default StackIterable getExpectedFiltered(T... elements) + { + return Stacks.immutable.withReversed(elements); + } + + @Override + default MutableList newMutableForFilter(T... elements) + { + return Lists.mutable.with(elements); + } + + @Override + @Test + default void InternalIterable_forEach() + { + RichIterable integers = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + integers.forEach(Procedures.cast(result::push)); + assertEquals(this.newWith(1, 2, 2, 3, 3, 3), result); + } + + @Override + @Test + default void RichIterable_tap() + { + RichIterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + iterable.tap(result::push).forEach(Procedures.noop()); + assertEquals(this.newWith(1, 2, 2, 3, 3, 3), result); + + this.newWith().tap(Procedures.cast(each -> fail())); + } + + @Override + default void InternalIterable_forEachWith() + { + RichIterable iterable = this.newWith(3, 3, 3, 2, 2, 1); + MutableStack result = Stacks.mutable.with(); + iterable.forEachWith((argument1, argument2) -> result.push(argument1 + argument2), 10); + assertEquals(this.getExpectedFiltered(11, 12, 12, 13, 13, 13), result); + } + + @Override + @Test + default void RichIterable_getFirst_and_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith()::getLast); + } + + @Override + @Test + default void RichIterable_getFirst_empty_null() + { + assertThrows(EmptyStackException.class, this.newWith()::getFirst); + } + + @Override + @Test + default void RichIterable_getLast_empty_null() + { + assertThrows(UnsupportedOperationException.class, this.newWith()::getLast); + } + + @Override + @Test + default void RichIterable_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith(3, 3, 3, 2, 2, 1)::getLast); + } + + @Override + @Test + default void OrderedIterable_getLast() + { + assertThrows(UnsupportedOperationException.class, this.newWith(3, 3, 3, 2, 2, 1)::getLast); + } + + @Override + @Test + default void OrderedIterable_getLastOptional() + { + assertThrows(UnsupportedOperationException.class, () -> + ((OrderedIterable) this.newWith(3, 2, 1)).getLastOptional()); + } + + @Override + @Test + default void OrderedIterable_getLastOptional_null_element() + { + assertThrows(UnsupportedOperationException.class, () -> + ((OrderedIterable) this.newWith(new Object[]{null})).getLastOptional()); + } + + @Test + default void StackIterable_peek() + { + assertEquals(Integer.valueOf(5), this.newWith(5, 1, 4, 2, 3).peek()); + } + + @Test + default void StackIterable_peek_throws() + { + assertThrows(EmptyStackException.class, () -> this.newWith().peek()); + } + + @Test + default void StackIterable_peekAt() + { + assertEquals(Integer.valueOf(5), this.newWith(5, 1, 4, 2, 3).peekAt(0)); + assertEquals(Integer.valueOf(1), this.newWith(5, 1, 4, 2, 3).peekAt(1)); + assertEquals(Integer.valueOf(4), this.newWith(5, 1, 4, 2, 3).peekAt(2)); + assertEquals(Integer.valueOf(2), this.newWith(5, 1, 4, 2, 3).peekAt(3)); + assertEquals(Integer.valueOf(3), this.newWith(5, 1, 4, 2, 3).peekAt(4)); + } + + @Test + default void StackIterable_peekAt_throws() + { + StackIterable stackIterable = this.newWith(5, 1, 4, 2, 3); + assertThrows(IllegalArgumentException.class, () -> stackIterable.peekAt(-1)); + assertThrows(IllegalArgumentException.class, () -> stackIterable.peekAt(5)); + } +} diff --git a/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java new file mode 100644 index 0000000000..cad23660d4 --- /dev/null +++ b/src/test/resources/oracle/commits/eclipse-collections-f26addbce8e843f208805aa22f45dcfb6f8177f7/unit-tests-java8/src/test/java/org/eclipse/collections/test/stack/mutable/UnmodifiableMutableStackTestCase.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 Goldman Sachs and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v. 1.0 which accompany this distribution. + * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + */ + +package org.eclipse.collections.test.stack.mutable; + +import org.eclipse.collections.api.stack.MutableStack; +import org.eclipse.collections.test.FixedSizeIterableTestCase; +import org.junit.Test; + +import static org.junit.Assert.assertThrows; + +public interface UnmodifiableMutableStackTestCase extends MutableStackTestCase, FixedSizeIterableTestCase +{ + @Override + @Test + default void Iterable_remove() + { + FixedSizeIterableTestCase.super.Iterable_remove(); + } + + @Override + @Test + default void MutableStack_pop() + { + MutableStack mutableStack = this.newWith(5, 1, 4, 2, 3); + assertThrows(UnsupportedOperationException.class, () -> mutableStack.pop()); + } + + @Override + @Test + default void MutableStack_pop_throws() + { + MutableStack mutableStack = this.newWith(); + assertThrows(UnsupportedOperationException.class, () -> mutableStack.pop()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.json b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.json new file mode 100644 index 0000000000..5109244a7d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24.json @@ -0,0 +1 @@ +{"parentCommitId":"86fdd8d01b38b2754c9720094dbc52f527c93ae0","currentCommitId":"5e0e683531b756ac62a497cca15ddb7211a34e24","filesBefore":["address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java","address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java","address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java","amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java","amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java","amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java","api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java","api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java","api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java","api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java","api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java","api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java","api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java","discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java","keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java","keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java","mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java","mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java","service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java","service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java","service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java","service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java","service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java","topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java"],"filesCurrent":["address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java","address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java","address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java","address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java","address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java","amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java","amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java","amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java","api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java","api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java","api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java","api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java","api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java","api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java","api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java","api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java","api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java","discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java","k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java","keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java","keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java","mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java","mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java","service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java","service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java","service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java","service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java","service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java","service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java","standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java","topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["api-model/src/test/java/io/enmasse/user/model","standard-controller/src/test/java","api-server/src/test/java","broker-plugin/sasl-delegation/src/test/java","mqtt-gateway/src/test/java/enmasse","address-model-lib/src/test","keycloak-controller/src/test/java/io/enmasse/keycloak/controller","api-model/src/test/java/io/enmasse/address/model/v1","keycloak-plugin/sasl-plugin/src/test/java/io","topic-forwarder/src/test","api-server/src/test/java/io/enmasse/api/v1","keycloak-controller/src/test/java","mqtt-gateway/src/test/java","service-broker/src/test/java/io/enmasse","api-common/src/test","api-model/src","service-broker/src/test/java","k8s-api/src/test/java/io","api-model/src/test/java","standard-controller/src","amqp-utils","api-common","standard-controller/src/test/java/io","discovery-lib","amqp-utils/src/test","broker-plugin/shutdown-hook/src","amqp-utils/src","keycloak-controller/src/test/java/io/enmasse/keycloak","standard-controller/src/test/java/io/enmasse/controller/standard","api-server/src","address-model-lib/src/test/java/io","keycloak-controller/src/test/java/io","discovery-lib/src/test","api-common/src/test/java/io/enmasse/api/auth","api-server/src/test/java/io","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop","topic-forwarder","address-model-lib","address-model-lib/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse","mqtt-lwt/src/test/java","keycloak-controller/src","standard-controller/src/test/java/io/enmasse","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis","service-broker/src/test","mqtt-gateway/src/test/java/enmasse/mqtt","address-space-controller/src/test","keycloak-controller","mqtt-lwt/src/test/java/enmasse/mqtt","address-model-lib/src/test/java","mqtt-lwt/src","keycloak-plugin","broker-plugin/shutdown-hook","api-server/src/test/java/io/enmasse/api/server","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation","topic-forwarder/src/test/java","api-model/src/test/java/io/enmasse/admin/model/v1","broker-plugin/shutdown-hook/src/test","amqp-utils/src/test/java/io","api-model","keycloak-plugin/sasl-plugin/src/test/java","amqp-utils/src/test/java/io/enmasse","api-server/src/test/java/io/enmasse","topic-forwarder/src/test/java/enmasse","amqp-utils/src/test/java/io/enmasse/amqp","mqtt-gateway/src","mqtt-gateway/src/test","service-broker/src","address-space-controller/src/test/java/io","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse/address","k8s-api/src/test/java/io/enmasse/k8s","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi","broker-plugin","service-broker","api-server/src/test/java/io/enmasse/api","broker-plugin/sasl-delegation/src/test/java/io","k8s-api","topic-forwarder/src/test/java/enmasse/broker/forwarder","api-common/src/test/java/io","mqtt-lwt/src/test/java/enmasse","k8s-api/src/test/java/io/enmasse","standard-controller/src/test/java/io/enmasse/controller","address-space-controller/src/test/java","api-server/src/test","broker-plugin/sasl-delegation","api-model/src/test/java/io/enmasse/admin/model","api-common/src/test/java/io/enmasse/api/common","topic-forwarder/src/test/java/enmasse/broker","api-model/src/test/java/io/enmasse/user","discovery-lib/src/test/java/enmasse","service-broker/src/test/java/io","api-model/src/test/java/io/enmasse/admin","k8s-api/src/test","keycloak-plugin/sasl-plugin/src/test","address-space-controller/src/test/java/io/enmasse/controller","service-broker/src/test/java/io/enmasse/osb/api","api-common/src","api-model/src/test/java/io/enmasse/address/model","api-server/src/test/java/io/enmasse/api/v1/http","broker-plugin/shutdown-hook/src/test/java/enmasse/broker","keycloak-plugin/sasl-plugin/src","mqtt-gateway","broker-plugin/shutdown-hook/src/test/java","address-model-lib/src","broker-plugin/sasl-delegation/src/test/java/io/enmasse","k8s-api/src","discovery-lib/src/test/java/enmasse/discovery","mqtt-lwt/src/test","amqp-utils/src/test/java","discovery-lib/src/test/java","address-space-controller/src/test/java/io/enmasse","k8s-api/src/test/java/io/enmasse/k8s/api","keycloak-controller/src/test","api-model/src/test","address-model-lib/src/test/java/io/enmasse/address/model","mqtt-lwt","api-server","api-model/src/test/java/io","k8s-api/src/test/java/io/enmasse/k8s/api/cache","api-common/src/test/java","address-model-lib/src/test/java/io/enmasse/address","broker-plugin/shutdown-hook/src/test/java/enmasse","broker-plugin/sasl-delegation/src","keycloak-plugin/sasl-plugin","api-model/src/test/java/io/enmasse/user/model/v1","address-space-controller/src/test/java/io/enmasse/controller/auth","discovery-lib/src","keycloak-controller/src/test/java/io/enmasse","api-common/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse/address/model/v1/address","address-space-controller/src","address-space-controller","service-broker/src/test/java/io/enmasse/osb","topic-forwarder/src","api-common/src/test/java/io/enmasse/api","standard-controller","k8s-api/src/test/java","broker-plugin/sasl-delegation/src/test","standard-controller/src/test"],"repositoryDirectoriesCurrent":["api-model/src/test/java/io/enmasse/user/model","standard-controller/src/test/java","api-server/src/test/java","broker-plugin/sasl-delegation/src/test/java","mqtt-gateway/src/test/java/enmasse","address-model-lib/src/test","keycloak-controller/src/test/java/io/enmasse/keycloak/controller","api-model/src/test/java/io/enmasse/address/model/v1","keycloak-plugin/sasl-plugin/src/test/java/io","topic-forwarder/src/test","api-server/src/test/java/io/enmasse/api/v1","keycloak-controller/src/test/java","mqtt-gateway/src/test/java","service-broker/src/test/java/io/enmasse","api-common/src/test","api-model/src","service-broker/src/test/java","k8s-api/src/test/java/io","api-model/src/test/java","standard-controller/src","amqp-utils","api-common","standard-controller/src/test/java/io","discovery-lib","amqp-utils/src/test","broker-plugin/shutdown-hook/src","amqp-utils/src","keycloak-controller/src/test/java/io/enmasse/keycloak","standard-controller/src/test/java/io/enmasse/controller/standard","api-server/src","address-model-lib/src/test/java/io","keycloak-controller/src/test/java/io","discovery-lib/src/test","api-common/src/test/java/io/enmasse/api/auth","api-server/src/test/java/io","broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop","topic-forwarder","address-model-lib","address-model-lib/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse","mqtt-lwt/src/test/java","keycloak-controller/src","standard-controller/src/test/java/io/enmasse","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis","service-broker/src/test","mqtt-gateway/src/test/java/enmasse/mqtt","address-space-controller/src/test","keycloak-controller","mqtt-lwt/src/test/java/enmasse/mqtt","address-model-lib/src/test/java","mqtt-lwt/src","keycloak-plugin","broker-plugin/shutdown-hook","api-server/src/test/java/io/enmasse/api/server","broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation","topic-forwarder/src/test/java","api-model/src/test/java/io/enmasse/admin/model/v1","broker-plugin/shutdown-hook/src/test","amqp-utils/src/test/java/io","api-model","keycloak-plugin/sasl-plugin/src/test/java","amqp-utils/src/test/java/io/enmasse","api-server/src/test/java/io/enmasse","topic-forwarder/src/test/java/enmasse","amqp-utils/src/test/java/io/enmasse/amqp","mqtt-gateway/src","mqtt-gateway/src/test","service-broker/src","address-space-controller/src/test/java/io","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse/address","k8s-api/src/test/java/io/enmasse/k8s","keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi","broker-plugin","service-broker","api-server/src/test/java/io/enmasse/api","broker-plugin/sasl-delegation/src/test/java/io","k8s-api","topic-forwarder/src/test/java/enmasse/broker/forwarder","api-common/src/test/java/io","mqtt-lwt/src/test/java/enmasse","k8s-api/src/test/java/io/enmasse","standard-controller/src/test/java/io/enmasse/controller","address-space-controller/src/test/java","api-server/src/test","broker-plugin/sasl-delegation","api-model/src/test/java/io/enmasse/admin/model","api-common/src/test/java/io/enmasse/api/common","topic-forwarder/src/test/java/enmasse/broker","api-model/src/test/java/io/enmasse/user","discovery-lib/src/test/java/enmasse","service-broker/src/test/java/io","api-model/src/test/java/io/enmasse/admin","k8s-api/src/test","keycloak-plugin/sasl-plugin/src/test","address-space-controller/src/test/java/io/enmasse/controller","service-broker/src/test/java/io/enmasse/osb/api","api-common/src","api-model/src/test/java/io/enmasse/address/model","api-server/src/test/java/io/enmasse/api/v1/http","broker-plugin/shutdown-hook/src/test/java/enmasse/broker","keycloak-plugin/sasl-plugin/src","mqtt-gateway","broker-plugin/shutdown-hook/src/test/java","address-model-lib/src","broker-plugin/sasl-delegation/src/test/java/io/enmasse","k8s-api/src","discovery-lib/src/test/java/enmasse/discovery","mqtt-lwt/src/test","amqp-utils/src/test/java","discovery-lib/src/test/java","address-space-controller/src/test/java/io/enmasse","k8s-api/src/test/java/io/enmasse/k8s/api","keycloak-controller/src/test","api-model/src/test","address-model-lib/src/test/java/io/enmasse/address/model","mqtt-lwt","api-server","api-model/src/test/java/io","k8s-api/src/test/java/io/enmasse/k8s/api/cache","api-common/src/test/java","address-model-lib/src/test/java/io/enmasse/address","broker-plugin/shutdown-hook/src/test/java/enmasse","broker-plugin/sasl-delegation/src","keycloak-plugin/sasl-plugin","api-model/src/test/java/io/enmasse/user/model/v1","address-space-controller/src/test/java/io/enmasse/controller/auth","discovery-lib/src","keycloak-controller/src/test/java/io/enmasse","api-common/src/test/java/io/enmasse","api-model/src/test/java/io/enmasse/address/model/v1/address","address-space-controller/src","address-space-controller","service-broker/src/test/java/io/enmasse/osb","topic-forwarder/src","api-common/src/test/java/io/enmasse/api","standard-controller","k8s-api/src/test/java","broker-plugin/sasl-delegation/src/test","standard-controller/src/test"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java new file mode 100644 index 0000000000..2e50fbbf10 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.address.model; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +/** + * Unit tests for {@link AuthenticationService} + */ +public class AuthenticationServiceTest { + + /** + * Test if two empty services are equal + */ + @Test + public void testEqualsEmpty() { + assertEquality(true, + new AuthenticationService.Builder().build(), + new AuthenticationService.Builder().build()); + } + + /** + * Test if two services are equal having the same type + */ + @Test + public void testEqualsSameType() { + assertEquality(true, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build()); + } + + /** + * Test if two services are not equal having the different types + */ + @Test + public void testNonEqualsDifferentType() { + assertEquality(false, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.NONE) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build()); + } + + /** + * Test if two services are equal having the same type and the same details + */ + @Test + public void testEqualsSameTypeSameDetails() { + final Map details1 = new HashMap<>(); + final Map details2 = new HashMap<>(); + + for (final Map map : Arrays.asList(details1, details2)) { + map.put("string", "foo"); + map.put("int", 1); + map.put("bool", true); + } + + assertEquality(true, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(details1) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(details2) + .build()); + } + + /** + * Test for equality + * + * @param isEqual are values to be expected equal? + * @param v1 value 1 + * @param v2 value 2 + */ + protected void assertEquality(final boolean isEqual, final Object v1, final Object v2) { + assertEquals(isEqual, v1.equals(v2)); + assertEquals(isEqual, v2.equals(v1)); + assertEquals(isEqual, v1.hashCode() == v2.hashCode()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java new file mode 100644 index 0000000000..bd7fe16c95 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceStatus; +import io.enmasse.controller.common.Kubernetes; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.metrics.api.Metric; +import io.enmasse.metrics.api.Metrics; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +public class ControllerChainTest { + private TestAddressSpaceApi testApi; + private Kubernetes kubernetes; + + @BeforeEach + public void setup() { + kubernetes = mock(Kubernetes.class); + testApi = new TestAddressSpaceApi(); + + when(kubernetes.getNamespace()).thenReturn("myspace"); + } + + @Test + public void testController() throws Exception { + EventLogger testLogger = mock(EventLogger.class); + Metrics metrics = new Metrics(); + ControllerChain controllerChain = new ControllerChain(kubernetes, testApi, new TestSchemaProvider(), testLogger, metrics, "1.0", Duration.ofSeconds(5), Duration.ofSeconds(5)); + Controller mockController = mock(Controller.class); + controllerChain.addController(mockController); + + AddressSpace a1 = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .build(); + + AddressSpace a2 = new AddressSpace.Builder() + .setName("myspace2") + .setType("type1") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .build(); + + when(mockController.handle(eq(a1))).thenReturn(a1); + when(mockController.handle(eq(a2))).thenReturn(a2); + + controllerChain.onUpdate(Arrays.asList(a1, a2)); + + verify(mockController, times(2)).handle(any()); + verify(mockController).handle(eq(a1)); + verify(mockController).handle(eq(a2)); + + List metricList = metrics.snapshot(); + assertThat(metricList.size(), is(5)); + assertTrue(a1.getStatus().isReady()); + assertTrue(a2.getStatus().isReady()); + } +} + diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java new file mode 100644 index 0000000000..a96e0f77cd --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.controller.common.Kubernetes; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.k8s.api.SchemaProvider; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.KubernetesList; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.Arrays; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class CreateControllerTest { + + @Test + public void testAddressSpaceCreate() throws Exception { + Kubernetes kubernetes = mock(Kubernetes.class); + when(kubernetes.getNamespace()).thenReturn("otherspace"); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setUid(UUID.randomUUID().toString()) + .setNamespace("mynamespace") + .setType("type1") + .setPlan("myplan") + .build(); + + + EventLogger eventLogger = mock(EventLogger.class); + InfraResourceFactory mockResourceFactory = mock(InfraResourceFactory.class); + when(mockResourceFactory.createInfraResources(eq(addressSpace), any())).thenReturn(Arrays.asList(new ConfigMapBuilder() + .editOrNewMetadata() + .withName("mymap") + .endMetadata() + .build())); + + SchemaProvider testSchema = new TestSchemaProvider(); + CreateController createController = new CreateController(kubernetes, testSchema, mockResourceFactory, eventLogger, null, "1.0", new TestAddressSpaceApi()); + + createController.handle(addressSpace); + + ArgumentCaptor resourceCaptor = ArgumentCaptor.forClass(KubernetesList.class); + verify(kubernetes).create(resourceCaptor.capture()); + KubernetesList value = resourceCaptor.getValue(); + assertThat(value.getItems().size(), is(1)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java new file mode 100644 index 0000000000..580df43551 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java @@ -0,0 +1,188 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.address.model.ExposeSpec; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.util.Arrays; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@ExtendWith(ExternalResourceSupport.class) +public class EndpointControllerTest { + + private OpenShiftClient client; + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + + @BeforeEach + public void setup() { + client = openShiftServer.getOpenshiftClient(); + } + + @Test + public void testRoutesNotCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, false); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertNull(newspace.getStatus().getEndpointStatuses().get(0).getExternalHost()); + assertTrue(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().isEmpty()); + } + + @Test + public void testExternalLoadBalancerCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setExposeSpec(new ExposeSpec.Builder() + .setType(ExposeSpec.ExposeType.loadbalancer) + .setLoadBalancerPorts(Arrays.asList("amqps")) + .build()) + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, true); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().size(), is(1)); + } + + @Test + public void testExternalRouteCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setExposeSpec(new ExposeSpec.Builder() + .setType(ExposeSpec.ExposeType.route) + .setRouteHost("host1.example.com") + .setRouteServicePort("amqps") + .setRouteTlsTermination(ExposeSpec.TlsTermination.passthrough) + .build()) + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, true); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().get("amqps"), is(443)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalHost(), is("host1.example.com")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java new file mode 100644 index 0000000000..bee8b34598 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java @@ -0,0 +1,209 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.KubeUtil; +import io.enmasse.admin.model.v1.InfraConfig; +import io.enmasse.admin.model.v1.NetworkPolicy; +import io.enmasse.admin.model.v1.NetworkPolicyBuilder; +import io.enmasse.admin.model.v1.StandardInfraConfigBuilder; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.networking.NetworkPolicyEgressRuleBuilder; +import io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRuleBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.util.Collections; + +import static junit.framework.TestCase.assertNotNull; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@ExtendWith(ExternalResourceSupport.class) +public class NetworkPolicyControllerTest { + private static final ObjectMapper mapper = new ObjectMapper(); + private OpenShiftClient client; + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + @BeforeEach + public void setup() { + client = openShiftServer.getOpenshiftClient(); + } + + @Test + public void testCreateFromInfraConfig() throws Exception { + InfraConfig infraConfig = createTestInfra(createTestPolicy("my", "label")); + AddressSpace addressSpace = createTestSpace(infraConfig, null); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testCreateFromAddressSpaceConfig() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testAddressSpaceOverridesInfra() throws Exception { + InfraConfig infraConfig = createTestInfra(createTestPolicy("my", "label")); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "overridden")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertEquals("type1", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_TYPE)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("overridden", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testUpdatesWhenChanged() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, + createTestPolicy("my", "label1")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label1", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label2")); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label2", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label2", "other", "label3")); + controller.handle(addressSpace); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Egress")); + assertEquals("label2", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + assertEquals("label3", networkPolicy.getSpec().getEgress().get(0).getTo().get(0).getPodSelector().getMatchLabels().get("other")); + } + + @Test + public void testDeletesWhenRemoved() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, null); + controller.handle(addressSpace); + assertEquals(0, client.network().networkPolicies().list().getItems().size()); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNull(networkPolicy); + } + + private NetworkPolicy createTestPolicy(String labelKey, String labelValue) { + return new NetworkPolicyBuilder() + .withIngress(Collections.singletonList(new NetworkPolicyIngressRuleBuilder() + .addNewFrom() + .withNewPodSelector() + .addToMatchLabels(labelKey, labelValue) + .endPodSelector() + .endFrom() + .build())) + .build(); + } + + private NetworkPolicy createTestPolicy(String ingressLabelKey, String ingressLabelValue, String egressLabelKey, String egressLabelValue) { + return new NetworkPolicyBuilder() + .withIngress(Collections.singletonList(new NetworkPolicyIngressRuleBuilder() + .addNewFrom() + .withNewPodSelector() + .addToMatchLabels(ingressLabelKey, ingressLabelValue) + .endPodSelector() + .endFrom() + .build())) + .withEgress(Collections.singletonList(new NetworkPolicyEgressRuleBuilder() + .addNewTo() + .withNewPodSelector() + .addToMatchLabels(egressLabelKey, egressLabelValue) + .endPodSelector() + .endTo() + .build())) + .build(); + } + + private InfraConfig createTestInfra(NetworkPolicy networkPolicy) throws JsonProcessingException { + return new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("test") + .build()) + .withNewSpec() + .withNetworkPolicy(networkPolicy) + .endSpec() + .build(); + } + + private AddressSpace createTestSpace(InfraConfig infraConfig, NetworkPolicy networkPolicy) throws JsonProcessingException { + return new AddressSpace.Builder() + .setName("myspace") + .setNamespace("ns") + .setType("type1") + .setPlan("plan1") + .setNetworkPolicy(networkPolicy) + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .putAnnotation(AnnotationKeys.APPLIED_INFRA_CONFIG, mapper.writeValueAsString(infraConfig)) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java new file mode 100644 index 0000000000..979c94c463 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.controller.common.Kubernetes; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class StatusControllerTest { + + @Test + public void testStatusControllerSetsNotReady() throws Exception { + InfraResourceFactory infraResourceFactory = mock(InfraResourceFactory.class); + Kubernetes kubernetes = mock(Kubernetes.class); + + Deployment deployment = new DeploymentBuilder() + .withNewMetadata() + .withName("mydepl1") + .endMetadata() + .withNewStatus() + .withUnavailableReplicas(1) + .withAvailableReplicas(0) + .endStatus() + .build(); + + when(kubernetes.getReadyDeployments()).thenReturn(Collections.emptySet()); + + StatusController controller = new StatusController(kubernetes, new TestSchemaProvider(), infraResourceFactory, null); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .build(); + + when(infraResourceFactory.createInfraResources(eq(addressSpace), any())).thenReturn(Collections.singletonList(deployment)); + + assertFalse(addressSpace.getStatus().isReady()); + controller.handle(addressSpace); + assertFalse(addressSpace.getStatus().isReady()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java new file mode 100644 index 0000000000..761a326862 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java @@ -0,0 +1,117 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AuthenticationServiceResolver; +import io.enmasse.address.model.CertSpec; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.admin.model.v1.*; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.controller.common.KubernetesHelper; +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.io.File; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(ExternalResourceSupport.class) +public class TemplateInfraResourceFactoryTest { + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + private TemplateInfraResourceFactory resourceFactory; + private NamespacedOpenShiftClient client; + + @BeforeEach + public void setup() { + client = openShiftServer.getOpenshiftClient(); + client.secrets().createNew().editOrNewMetadata().withName("certs").endMetadata().addToData("tls.crt", "cert").done(); + AuthenticationServiceResolver authServiceResolver = mock(AuthenticationServiceResolver.class); + when(authServiceResolver.getHost(any())).thenReturn("example.com"); + when(authServiceResolver.getPort(any())).thenReturn(5671); + when(authServiceResolver.getCaSecretName(any())).thenReturn(Optional.of("certs")); + resourceFactory = new TemplateInfraResourceFactory( + new KubernetesHelper("test", + client, + client.getConfiguration().getOauthToken(), + new File("src/test/resources/templates"), + true), + a -> authServiceResolver, + true); + } + + @Test + public void testGenerateStandard() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("myproject") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .setType("standard") + .setPlan("standard-unlimited") + .appendEndpoint(new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .setCertSpec(new CertSpec("selfsigned", "messaging-secret", null, null)) + .build()) + .appendEndpoint(new EndpointSpec.Builder() + .setName("console") + .setService("console") + .setCertSpec(new CertSpec("selfsigned", "console-secret", null, null)) + .build()) + .build(); + + StandardInfraConfig infraConfig = new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("test") + .build()) + .withNewSpec() + .withVersion("master") + .withAdmin(new StandardInfraConfigSpecAdminBuilder() + .withNewResources("2Mi") + .build()) + .withBroker(new StandardInfraConfigSpecBrokerBuilder() + .withNewResources("2Mi", "1Gi") + .withAddressFullPolicy("FAIL") + .build()) + .withRouter(new StandardInfraConfigSpecRouterBuilder() + .withNewResources("2Mi") + .withLinkCapacity(22) + .build()) + .endSpec() + .build(); + List items = resourceFactory.createInfraResources(addressSpace, infraConfig); + assertEquals(1, items.size()); + ConfigMap map = findItem("ConfigMap", "mymap", items); + assertEquals("FAIL", map.getData().get("key")); + } + + private T findItem(String kind, String name, List items) { + T found = null; + for (HasMetadata item : items) { + if (kind.equals(item.getKind()) && name.equals(item.getMetadata().getName())) { + found = (T) item; + break; + } + } + assertNotNull(found); + return found; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java new file mode 100644 index 0000000000..b9321757e1 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(ExternalResourceSupport.class) +public class CertBundleCertProviderTest { + @Rule + public OpenShiftServer server = new OpenShiftServer(true, true); + + private OpenShiftClient client; + private CertProvider certProvider; + + @BeforeEach + public void setup() { + client = server.getOpenshiftClient(); + + certProvider = new CertBundleCertProvider(client); + } + + @Test + public void testProvideCertNoService() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .build(); + + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + } + + @Test + public void testProvideCert() { + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("aGVsbG8=") + .setTlsCert("d29ybGQ=") + .build(); + + space.validate(); + + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNotNull(cert); + assertThat(cert.getData().get("tls.key"), is(spec.getTlsKey())); + assertThat(cert.getData().get("tls.crt"), is(spec.getTlsCert())); + } + + @Test + public void testValidateBadKey() { + assertThrows(IllegalArgumentException.class, () -> new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("/%^$lkg") + .setTlsCert("d29ybGQ=") + .build() + .validate()); + } + + @Test + public void testValidateBadCert() { + assertThrows(IllegalArgumentException.class, () -> new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("d29ybGQ=") + .setTlsCert("/%^$lkg") + .build() + .validate()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java new file mode 100644 index 0000000000..12028b9a1b --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import static junit.framework.TestCase.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@ExtendWith(ExternalResourceSupport.class) +public class OpenShiftCertProviderTest { + @Rule + public OpenShiftServer server = new OpenShiftServer(true, true); + + private OpenShiftClient client; + private CertProvider certProvider; + + @BeforeEach + public void setup() { + client = server.getOpenshiftClient(); + + certProvider = new OpenshiftCertProvider(client); + } + + @Test + public void testProvideCertNoService() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder().setProvider("openshift").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + } + + @Test + public void testProvideCert() { + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .build(); + + client.services().inNamespace("test").create(new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .endSpec() + .build()); + + CertSpec spec = new CertSpec.Builder().setProvider("openshift").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + + Service service = client.services().inNamespace("test").withName("messaging-1234").get(); + assertNotNull(service); + // Should verify that annotation is set, but bug in mock-server seems to not set it + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java new file mode 100644 index 0000000000..bd3f8ed7cf --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.server.mock.KubernetesServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + + +@ExtendWith(ExternalResourceSupport.class) +public class WildcardCertProviderTest { + @Rule + public KubernetesServer server = new KubernetesServer(true, true); + + private KubernetesClient client; + private CertProvider certProvider; + + @BeforeEach + public void setup() { + client = server.getClient(); + String wildcardCert = "wildcardcert"; + + certProvider = new WildcardCertProvider(client, wildcardCert); + } + + @Test + public void testUnknownWildcardSecret() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setType("standard") + .setPlan("myplan") + .build(); + CertSpec spec = new CertSpec.Builder().setProvider("wildcard").setSecretName("mycerts").build(); + + assertThrows(IllegalStateException.class, () -> certProvider.provideCert(space, new EndpointInfo("messaging", spec))); + } + + @Test + public void testProvideCert() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + client.secrets().create(new SecretBuilder() + .editOrNewMetadata() + .withName("wildcardcert") + .endMetadata() + .addToData("tls.key", "mykey") + .addToData("tls.crt", "myvalue") + .build()); + + CertSpec spec = new CertSpec.Builder().setProvider("wildcard").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertThat(cert.getData().get("tls.key"), is("mykey")); + assertThat(cert.getData().get("tls.crt"), is("myvalue")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java new file mode 100644 index 0000000000..b77bb121ad --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.amqp; + +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ArtemisTest { + + private static class TestClient implements SyncRequestClient { + + Message response; + Message request; + + @Override + public void connect(String host, int port, ProtonClientOptions clientOptions, String address, CompletableFuture connectedPromise) { + + } + + @Override + public String getRemoteContainer() { + return null; + } + + @Override + public String getReplyTo() { + return "tome"; + } + + @Override + public void close() { + + } + + @Override + public Message request(Message message, long timeout, TimeUnit timeUnit) { + request = message; + return response; + } + } + + @Test + public void testManagement() throws InterruptedException, ExecutionException, TimeoutException { + TestClient testClient = new TestClient(); + try (Artemis artemis = new Artemis(testClient)) { + + testClient.response = Proton.message(); + artemis.deployQueue("queue1", "queue1"); + String body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[\"queue1\",\"queue1\",null,false]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("deployQueue", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + artemis.deployQueue("queue2", "queue2"); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[\"queue2\",\"queue2\",null,false]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("deployQueue", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + testClient.response = Proton.message(); + testClient.response.setBody(new AmqpValue("[[\"q1\"],[\"q2\"],[\"tome\"]]")); + long numQueues = artemis.getNumQueues(); + assertEquals(2, numQueues); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("getQueueNames", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + testClient.response = Proton.message(); + testClient.response.setBody(new AmqpValue("[42]")); + long messageCount = artemis.getQueueMessageCount("q1"); + assertEquals(42, messageCount); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[]", body); + assertEquals("queue.q1", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("messageCount", testClient.request.getApplicationProperties().getValue().get("_AMQ_Attribute")); + + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java new file mode 100644 index 0000000000..b88f2f4f62 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java @@ -0,0 +1,123 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.amqp; + +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonSession; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class BlockingClientTest { + private static final Logger log = LoggerFactory.getLogger(BlockingClientTest.class); + + private Vertx vertx; + private ProtonServer server; + private BlockingQueue inbox; + private BlockingQueue outbox; + private int actualPort; + + @BeforeEach + public void setup() throws Exception { + vertx = Vertx.vertx(); + server = ProtonServer.create(vertx); + inbox = new LinkedBlockingDeque<>(); + outbox = new LinkedBlockingDeque<>(); + CountDownLatch latch = new CountDownLatch(1); + server.connectHandler(conn -> { + conn.closeHandler(c -> { + conn.close(); + conn.disconnect(); + }); + conn.disconnectHandler(c -> { + conn.disconnect(); + }).open(); + + conn.sessionOpenHandler(ProtonSession::open); + + conn.receiverOpenHandler(receiver -> { + log.debug("Receiver open"); + receiver.setTarget(receiver.getRemoteTarget()); + receiver.handler((delivery, message) -> { + inbox.add(message); + }); + receiver.open(); + }); + + conn.senderOpenHandler(sender -> { + vertx.setPeriodic(100, id -> { + try { + Message m = outbox.poll(0, TimeUnit.SECONDS); + if (m != null) { + sender.send(m); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + // Try again later + } + }); + sender.open(); + }); + }).listen(0, res -> latch.countDown()); + latch.await(); + actualPort = server.actualPort(); + log.debug("Using port {}", actualPort); + } + + @Test + public void testSend() throws Exception { + try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) { + Message m = Message.Factory.create(); + m.setAddress("testsend"); + m.setBody(new AmqpValue("hello there")); + client.send("testsend", Arrays.asList(m), 1, TimeUnit.MINUTES); + + Message received = inbox.poll(1, TimeUnit.MINUTES); + assertNotNull(received); + assertThat(received.getMessageId(), is(m.getMessageId())); + assertThat(((AmqpValue) received.getBody()).getValue(), is("hello there")); + } + } + + @Test + public void testReceive() throws Exception { + try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) { + Message m = Message.Factory.create(); + m.setAddress("testreceive"); + m.setBody(new AmqpValue("hello there")); + outbox.put(m); + + List messages = client.recv("testsend", 1, 1, TimeUnit.MINUTES); + assertThat(messages.size(), is(1)); + + Message received = messages.get(0); + assertNotNull(received); + assertThat(received.getMessageId(), is(m.getMessageId())); + assertThat(((AmqpValue) received.getBody()).getValue(), is("hello there")); + } + } + + @AfterEach + public void teardown() { + server.close(); + vertx.close(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java new file mode 100644 index 0000000000..c75e96c24c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.amqp; + +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonSender; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonSession; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ProtonRequestClientTest { + private Vertx vertx; + private ProtonServer server; + + @BeforeEach + public void setup() throws InterruptedException { + vertx = Vertx.vertx(); + server = ProtonServer.create(vertx); + CountDownLatch latch = new CountDownLatch(1); + CompletableFuture futureSender = new CompletableFuture<>(); + server.connectHandler(conn -> { + conn.closeHandler(c -> { + conn.close(); + conn.disconnect(); + }); + conn.disconnectHandler(c -> { + conn.disconnect(); + }).open(); + + conn.sessionOpenHandler(ProtonSession::open); + + conn.receiverOpenHandler(receiver -> { + System.out.println("Receiver open"); + receiver.setTarget(receiver.getRemoteTarget()); + receiver.handler((delivery, message) -> { + Message response = Message.Factory.create(); + response.setAddress(message.getAddress()); + response.setBody(new AmqpValue(true)); + response.setCorrelationId(message.getCorrelationId()); + response.setReplyTo(message.getReplyTo()); + try { + futureSender.get().send(response); + } catch (Exception e) { + e.printStackTrace(); + } + }); + receiver.open(); + }); + + conn.senderOpenHandler(sender -> { + sender.setSource(sender.getRemoteSource()); + sender.open(); + futureSender.complete(sender); + }); + }).listen(12347, res -> { + latch.countDown(); + }); + latch.await(); + } + + @AfterEach + public void teardown() { + server.close(); + vertx.close(); + } + + @Test + public void testRequest() throws Exception { + try (ProtonRequestClient client = new ProtonRequestClient(Vertx.vertx(), "test-client")) { + CompletableFuture future = new CompletableFuture<>(); + client.connect("127.0.0.1", 12347, future); + future.get(10, TimeUnit.SECONDS); + Message request = Message.Factory.create(); + request.setAddress("health-check"); + request.setBody(new AmqpValue("[{\"name\":\"myqueue\",\"store_and_forward\":true,\"multicast\":false}]")); + request.setSubject("health-check"); + Message response = client.request(request, 10, TimeUnit.SECONDS); + assertTrue((Boolean) ((AmqpValue) response.getBody()).getValue()); + + future = new CompletableFuture<>(); + client.connect("127.0.0.1", 12347, future); + future.get(10, TimeUnit.SECONDS); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java new file mode 100644 index 0000000000..3fec10de1e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java @@ -0,0 +1,191 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.auth; + +import io.vertx.core.http.HttpConnection; +import io.vertx.core.http.HttpServerRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.core.UriInfo; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.function.Predicate; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class AuthInterceptorTest { + + private File tokenFile; + private AuthInterceptor handler; + private ContainerRequestContext mockRequestContext; + private UriInfo mockUriInfo; + private AuthApi mockAuthApi; + + @BeforeEach + public void setUp() throws IOException { + tokenFile = File.createTempFile("token", ""); + mockAuthApi = mock(AuthApi.class); + when(mockAuthApi.getNamespace()).thenReturn("myspace"); + handler = new AuthInterceptor(mockAuthApi, new Predicate() { + @Override + public boolean test(String s) { + return "/healthz".equals(s); + } + }); + mockRequestContext = mock(ContainerRequestContext.class); + + mockUriInfo = mock(UriInfo.class); + when(mockUriInfo.getAbsolutePath()).thenReturn(URI.create("https://localhost:443/apis/enmasse.io/v1alpha1/addressspaces")); + when(mockUriInfo.getPath()).thenReturn("/apis/enmasse.io/v1alpha1/addressspaces"); + when(mockRequestContext.getUriInfo()).thenReturn(mockUriInfo); + } + + + private void assertAuthenticatedAs(ContainerRequestContext requestContext, String userName) { + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + handler.filter(requestContext); + verify(requestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + assertThat(RbacSecurityContext.getUserName(context.getUserPrincipal()), is(userName)); + } + + @Test + public void testNoAuthorizationHeader() { + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn(null); + assertAuthenticatedAs(mockRequestContext, "system:anonymous"); + } + + @Test + public void testBasicAuth() throws IOException { + Files.write(Paths.get(tokenFile.getAbsolutePath()), "valid_token".getBytes()); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Basic dXNlcjpwYXNzCg=="); + + assertAuthenticatedAs(mockRequestContext, "system:anonymous"); + } + + @Test + public void testInvalidToken() { + TokenReview returnedTokenReview = new TokenReview(null, null, false); + when(mockAuthApi.performTokenReview("invalid_token")).thenReturn(returnedTokenReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer invalid_token"); + assertThrows(NotAuthorizedException.class, () -> handler.filter(mockRequestContext)); + } + + @Test + public void testValidTokenButNotAuthorized() { + TokenReview returnedTokenReview = new TokenReview("foo", "myid", true); + when(mockAuthApi.performTokenReview("valid_token")).thenReturn(returnedTokenReview); + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("foo", false); + when(mockAuthApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer valid_token"); + when(mockRequestContext.getMethod()).thenReturn(HttpMethod.POST); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + handler.filter(mockRequestContext); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertNotNull(context); + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("foo")); + assertThat(RbacSecurityContext.getUserId(rbacSecurityContext.getUserPrincipal()), is("myid")); + assertFalse(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "configmaps", ""))); + } + + @Test + public void testHealthAuthz() { + when(mockUriInfo.getPath()).thenReturn("/healthz"); + handler.filter(mockRequestContext); + } + + @Test + public void testCertAuthorization() { + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("me", true); + when(mockAuthApi.performSubjectAccessReviewResource(eq("me"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString("X-Remote-User")).thenReturn("me"); + + HttpServerRequest request = mock(HttpServerRequest.class); + HttpConnection connection = mock(HttpConnection.class); + when(request.isSSL()).thenReturn(true); + when(request.connection()).thenReturn(connection); + + handler.setRequest(request); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("me")); + assertTrue(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "addressspaces", "enmasse.io"))); + } + + @Test + public void testCertAuthorizationFailed() throws SSLPeerUnverifiedException { + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("system:anonymous", false); + when(mockAuthApi.performSubjectAccessReviewResource(eq("system:anonymous"), any(), any(), eq("create"), eq("enmasse.io"))).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString("X-Remote-User")).thenReturn("me"); + + HttpServerRequest request = mock(HttpServerRequest.class); + HttpConnection connection = mock(HttpConnection.class); + when(request.isSSL()).thenReturn(true); + when(request.connection()).thenReturn(connection); + when(connection.peerCertificateChain()).thenThrow(new SSLPeerUnverifiedException("")); + + handler.setRequest(request); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("system:anonymous")); + assertFalse(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "addressspaces", "enmasse.io"))); + } + + @Test + public void testAuthorized() throws IOException { + TokenReview returnedTokenReview = new TokenReview("foo", "myid", true); + when(mockAuthApi.performTokenReview("valid_token")).thenReturn(returnedTokenReview); + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("foo", true); + when(mockAuthApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer valid_token"); + when(mockRequestContext.getMethod()).thenReturn(HttpMethod.POST); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("foo")); + assertTrue(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "configmaps", ""))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java new file mode 100644 index 0000000000..6a129af47e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java @@ -0,0 +1,52 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.common; + +import io.fabric8.kubernetes.api.model.StatusBuilder; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +public class DefaultExceptionMapperTest { + + @Test + public void testToResponse() { + int code = 410; + Response.Status status = Response.Status.fromStatusCode(code); + String message = "Some error message"; + WebApplicationException exception = new WebApplicationException(message, status); + + Response response = new DefaultExceptionMapper().toResponse(exception); + assertEquals(code, response.getStatus()); + assertEquals(status.getReasonPhrase(), response.getStatusInfo().getReasonPhrase()); + assertTrue(response.getEntity() instanceof Status); + Status responseEntity = (Status) response.getEntity(); + assertEquals(status.getReasonPhrase(), responseEntity.getReason()); + assertEquals(message, responseEntity.getMessage()); + } + + @Test + public void testToResponseStatus422() { + int code = 422; + io.fabric8.kubernetes.api.model.Status status = new StatusBuilder().withCode(code).build(); + String message = "Some error message"; + KubernetesClientException kubernetesClientException = new KubernetesClientException(message, code, status); + + Response response = new DefaultExceptionMapper().toResponse(kubernetesClientException); + assertEquals(code, response.getStatus()); + // can't check for response.getStatusInfo().getReasonPhrase() here because 422 isn't known in Response.Status + assertTrue(response.getEntity() instanceof Status); + Status responseEntity = (Status) response.getEntity(); + assertEquals("Unprocessable Entity", responseEntity.getReason()); + assertEquals(message, responseEntity.getMessage()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java new file mode 100644 index 0000000000..18f7829766 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model; + + + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + + +public class AddressSpaceTest { + + @Test + public void testSimpleCreateFromBuilder() { + AddressSpace space = new AddressSpace.Builder() + .setName("name") + .setType("type") + .setPlan("plan") + .build(); + + assertNotNull(space); + + assertThat(space.getName(), is("name")); + assertThat(space.getType(), is("type")); + assertThat(space.getPlan(), is("plan")); + assertThat(space.getStatus(), is(new AddressSpaceStatus(false))); + assertNotNull(space.getEndpoints()); + assertThat(space.getEndpoints().size(), is(0)); + assertNotNull(space.getAuthenticationService()); + assertNotNull(space.getAnnotations()); + assertThat(space.getAnnotations().size(), is(0)); + assertNotNull(space.getLabels()); + assertThat(space.getLabels().size(), is(0)); + } + + + @Test + public void testSimpleWithMissingMandatory() { + try { + new AddressSpace.Builder() + .setType("type") + .setPlan("plan") + .build(); + fail(""); + } catch (NullPointerException e) { + // pass + } + + try { + new AddressSpace.Builder() + .setName("name") + .setPlan("plan") + .build(); + fail(""); + } catch (NullPointerException e) { + // pass + } + + try { + new AddressSpace.Builder() + .setName("name") + .setType("type") + .build(); + fail(""); + } catch (NullPointerException e) { + // pass + } + } + + @Test + public void testEqualityIsBasedOnNameAndNamespace() { + AddressSpace space1 = new AddressSpace.Builder() + .setName("name") + .setType("type") + .setPlan("plan") + .build(); + AddressSpace space2 = new AddressSpace.Builder() + .setName("name") + .setType("type2") + .setPlan("plan") + .build(); + assertEquals(space1, space2); + AddressSpace space3 = new AddressSpace.Builder() + .setName("name") + .setNamespace("ns") + .setType("type2") + .setPlan("plan") + .build(); + assertNotEquals(space1, space3); + AddressSpace space4 = new AddressSpace.Builder() + .setName("name") + .setNamespace("ns") + .setType("type") + .setPlan("plan2") + .build(); + assertEquals(space3, space4); + AddressSpace space5 = new AddressSpace.Builder() + .setName("name2") + .setNamespace("ns") + .setType("type") + .setPlan("plan2") + .build(); + assertNotEquals(space4, space5); + + + + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java new file mode 100644 index 0000000000..819c44a67a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.Status; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class AddressTest { + @Test + public void testCreateFromBuilder() { + Address.Builder b1 = new Address.Builder() + .setAddress("addr1") + .setAddressSpace("space1") + .setName("myname") + .setType("queue") + .setPlan("myplan") + .setStatus(new Status(true)) + .setUid("myuuid") + .setResourceVersion("1234") + .setSelfLink("/my/link") + .setCreationTimestamp("my stamp"); + + Address a1 = b1.build(); + + Address.Builder b2 = new Address.Builder(a1); + + Address a2 = b2.build(); + + assertThat(a1.getAddress(), is(a2.getAddress())); + assertThat(a1.getAddressSpace(), is(a2.getAddressSpace())); + assertThat(a1.getName(), is(a2.getName())); + assertThat(a1.getPlan(), is(a2.getPlan())); + assertThat(a1.getStatus(), is(a2.getStatus())); + assertThat(a1.getType(), is(a2.getType())); + assertThat(a1.getUid(), is(a2.getUid())); + assertThat(a1.getResourceVersion(), is(a2.getResourceVersion())); + assertThat(a1.getSelfLink(), is(a2.getSelfLink())); + assertThat(a1.getCreationTimestamp(), is(a2.getCreationTimestamp())); + } + + @Test + public void testSanitizer() { + Address b1 = new Address.Builder() + .setNamespace("ns1") + .setAddress("myAddr_-") + .setAddressSpace("myspace") + .setPlan("p1") + .setType("t1") + .build(); + + Address b2 = new Address.Builder() + .setNamespace("ns1") + .setAddress(b1.getAddress()) + .setAddressSpace("myspace") + .setName(b1.getName()) + .setPlan(b1.getPlan()) + .setType(b1.getType()) + .build(); + assertNull(b1.getName()); + String generated = Address.generateName(b1.getAddressSpace(), b1.getAddress()); + System.out.println(generated); + assertTrue(generated.startsWith("myspace.myaddr1.")); + assertThat(b1.getName(), is(b2.getName())); + assertThat(b1.getAddress(), is(b2.getAddress())); + assertThat(b1.getPlan(), is(b2.getPlan())); + assertThat(b1.getType(), is(b2.getType())); + } + + @Test + public void testCopy() { + Address a = new Address.Builder() + .setAddress("a1") + .setPlan("p1") + .setType("t1") + .setNamespace("ns") + .setAddressSpace("myspace") + .setStatus(new Status(true).setPhase(Status.Phase.Active).appendMessage("foo")) + .build(); + + Address b = new Address.Builder(a).build(); + + assertThat(a, is(b)); + assertTrue(b.getStatus().isReady()); + assertThat(b.getStatus().getPhase(), is(Status.Phase.Active)); + assertThat(b.getStatus().getMessages(), hasItem("foo")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java new file mode 100644 index 0000000000..0c1925299a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java @@ -0,0 +1,23 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.KubeUtil; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + + +public class KubeUtilTest { + @Test + public void testLeaveSpaceForPodIdentifier() { + String address = "receiver-round-robincli_rhearatherlongaddresswhichcanbeverylongblablabla"; + String id = KubeUtil.sanitizeName(address); + assertThat(id.length(), is(60)); + String id2 = KubeUtil.sanitizeName(id); + assertThat(id, is(id2)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java new file mode 100644 index 0000000000..d51393e219 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java @@ -0,0 +1,491 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.*; +import io.enmasse.address.model.v1.CodecV1; +import io.enmasse.address.model.v1.DeserializeException; +import io.enmasse.admin.model.v1.AddressPlan; +import io.enmasse.admin.model.v1.AddressSpacePlan; +import io.enmasse.admin.model.v1.AddressSpacePlanBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import org.junit.jupiter.api.Test; +import org.mockito.internal.util.collections.Sets; + +import java.io.IOException; +import java.util.*; + +import static io.enmasse.address.model.ExposeSpec.ExposeType.route; +import static io.enmasse.address.model.ExposeSpec.TlsTermination.passthrough; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +// TODO: Add more tests of invalid input to deserialization +public class SerializationTest { + + @Test + public void testSerializeAddress() throws IOException { + String uuid = UUID.randomUUID().toString(); + Address address = new Address.Builder() + .setName("as1.a1") + .setAddress("addr1") + .setAddressSpace("as1") + .setNamespace("ns") + .setType("queue") + .setPlan("inmemory") + .setUid(uuid) + .putAnnotation("my", "annotation") + .setResourceVersion("1234") + .setSelfLink("/my/link") + .setCreationTimestamp("my stamp") + .build(); + + byte[] serialized = CodecV1.getMapper().writeValueAsBytes(address); + + Address deserialized = CodecV1.getMapper().readValue(serialized, Address.class); + + assertThat(deserialized, is(address)); + assertThat(deserialized.getName(), is(address.getName())); + assertThat(deserialized.getAddressSpace(), is(address.getAddressSpace())); + assertThat(deserialized.getType(), is(address.getType())); + assertThat(deserialized.getUid(), is(address.getUid())); + assertThat(deserialized.getResourceVersion(), is(address.getResourceVersion())); + assertThat(deserialized.getSelfLink(), is(address.getSelfLink())); + assertThat(deserialized.getCreationTimestamp(), is(address.getCreationTimestamp())); + assertThat(deserialized.getPlan(), is(address.getPlan())); + assertThat(deserialized.getAddress(), is(address.getAddress())); + assertThat(deserialized.getAnnotations(), is(address.getAnnotations())); + } + + @Test + public void testSerializeAddressList() throws IOException { + Address addr1 = new Address.Builder() + .setName("a1.a1") + .setAddress("addr1") + .setAddressSpace("a1") + .setNamespace("ns") + .setType("queue") + .setPlan("myplan") + .build(); + + Address addr2 = new Address.Builder() + .setName("a1.a2") + .setAddressSpace("a1") + .setAddress("addr2") + .setNamespace("ns") + .setType("anycast") + .setPlan("myplan") + .build(); + + + AddressList list = new AddressList(Sets.newSet(addr1, addr2)); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + List
deserialized = CodecV1.getMapper().readValue(serialized, AddressList.class); + + assertThat(deserialized, is(list)); + } + + + @Test + public void testSerializeEmptyAddressList() throws IOException { + + AddressList list = new AddressList(Collections.emptySet()); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + assertTrue(serialized.matches(".*\"items\"\\s*:\\s*\\[\\s*\\].*"), + "Serialized form '" + serialized + "' does not include empty items list"); + List
deserialized = CodecV1.getMapper().readValue(serialized, AddressList.class); + + assertThat(deserialized, is(list)); + } + + @Test + public void testSerializeAddressSpaceWithIllegalName() throws IOException { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace.bar") + .setPlan("myplan") + .setType("mytype") + .build(); + + String serialized = CodecV1.getMapper().writeValueAsString(addressSpace); + assertThrows(DeserializeException.class, () -> CodecV1.getMapper().readValue(serialized, AddressSpace.class)); + } + + @SuppressWarnings("serial") + @Test + public void testSerializeAddressSpace() throws IOException { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .setPlan("defaultplan") + .setType("standard") + .setCreationTimestamp("some date") + .setResourceVersion("1234") + .setSelfLink("/my/resource") + .setStatus(new AddressSpaceStatus(true).appendMessage("hello").appendEndpointStatus( + new EndpointStatus.Builder() + .setName("myendpoint") + .setExternalHost("example.com") + .setExternalPorts(Collections.singletonMap("amqps", 443)) + .setServiceHost("messaging.svc") + .setServicePorts(Collections.singletonMap("amqp", 5672)) + .build())) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setCertSpec(new CertSpec.Builder().setProvider("provider").setSecretName("mysecret").build()) + .setExposeSpec(new ExposeSpec.Builder() + .setType(route) + .setRouteHost("example.com") + .setRouteTlsTermination(passthrough) + .setRouteServicePort("amqp") + .build()) + .build())) + .setAuthenticationService(new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(new HashMap() {{ + put("host", "my.example.com"); + put("port", 5671); + put("caCertSecretName", "authservicesecret"); + put("clientCertSecretName", "clientcertsecret"); + put("saslInitHost", "my.example.com"); + }}) + .build()) + .build(); + + String serialized = CodecV1.getMapper().writeValueAsString(addressSpace); + AddressSpace deserialized = CodecV1.getMapper().readValue(serialized, AddressSpace.class); + + assertThat(deserialized.getName(), is(addressSpace.getName())); + assertThat(deserialized.getNamespace(), is(addressSpace.getNamespace())); + assertThat(deserialized.getType(), is(addressSpace.getType())); + assertThat(deserialized.getPlan(), is(addressSpace.getPlan())); + assertThat(deserialized.getSelfLink(), is(addressSpace.getSelfLink())); + assertThat(deserialized.getCreationTimestamp(), is(addressSpace.getCreationTimestamp())); + assertThat(deserialized.getResourceVersion(), is(addressSpace.getResourceVersion())); + assertThat(deserialized.getStatus().isReady(), is(addressSpace.getStatus().isReady())); + assertThat(deserialized.getStatus().getMessages(), is(addressSpace.getStatus().getMessages())); + assertThat(deserialized.getStatus().getEndpointStatuses().size(), is(addressSpace.getEndpoints().size())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getName(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getName())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getExternalHost(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getExternalHost())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getExternalPorts().values().iterator().next(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getExternalPorts().values().iterator().next())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getServiceHost(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getServiceHost())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getServicePorts(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getServicePorts())); + assertThat(deserialized.getEndpoints().size(), is(addressSpace.getEndpoints().size())); + assertThat(deserialized.getEndpoints().get(0).getName(), is(addressSpace.getEndpoints().get(0).getName())); + assertThat(deserialized.getEndpoints().get(0).getService(), is(addressSpace.getEndpoints().get(0).getService())); + assertThat(deserialized.getEndpoints().get(0).getCertSpec().get().getProvider(), is(addressSpace.getEndpoints().get(0).getCertSpec().get().getProvider())); + assertThat(deserialized.getEndpoints().get(0).getCertSpec().get().getSecretName(), is(addressSpace.getEndpoints().get(0).getCertSpec().get().getSecretName())); + assertThat(deserialized.getAuthenticationService().getType(), is(addressSpace.getAuthenticationService().getType())); + assertThat(deserialized.getAuthenticationService().getDetails(), is(addressSpace.getAuthenticationService().getDetails())); + assertThat(addressSpace, is(deserialized)); + } + + @Test + public void testDeserializeAddressSpaceCompat() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\":{" + + " \"type\": \"standard\"," + + " \"plan\": \"unlimited-standard\"," + + " \"endpoints\":[" + + " {\"name\":\"messaging\",\"service\":\"messaging\",\"servicePort\":\"amqps\"}" + + " ]" + + "}}"; + AddressSpace addressSpace = CodecV1.getMapper().readValue(json, AddressSpace.class); + assertThat(addressSpace.getEndpoints().size(), is(1)); + assertTrue(addressSpace.getEndpoints().get(0).getExposeSpec().isPresent()); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getType(), is(route)); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getRouteTlsTermination(), is(passthrough)); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getRouteServicePort(), is("amqps")); + } + + @Test + public void testDeserializeAddressSpaceMissingDefaults() throws IOException { + String serialized = "{\"kind\": \"AddressSpace\", \"apiVersion\": \"v1alpha1\"}"; + assertThrows(DeserializeException.class, () -> CodecV1.getMapper().readValue(serialized, AddressSpace.class)); + } + + @Test + public void testDeserializeAddressMissingDefaults() throws IOException { + String serialized = "{\"kind\": \"Address\", \"apiVersion\": \"v1alpha1\"}"; + assertThrows(DeserializeException.class, () -> CodecV1.getMapper().readValue(serialized, Address.class)); + } + + @Test + public void testDeserializeAddressSpacePlan() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpacePlan\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"," + + " \"annotations\": {" + + " \"mykey\": \"myvalue\"" + + " }" + + "}," + + "\"displayName\": \"MySpace\"," + + "\"shortDescription\": \"MySpace is cool\"," + + "\"longDescription\": \"MySpace is cool, but not much used anymore\"," + + "\"uuid\": \"12345\"," + + "\"addressPlans\":[\"plan1\"]," + + "\"addressSpaceType\": \"standard\"," + + "\"resources\": [" + + " { \"name\": \"router\", \"min\": 0.5, \"max\": 1.0 }, " + + " { \"name\": \"broker\", \"min\": 0.1, \"max\": 0.5 }" + + "]" + + "}"; + + AddressSpacePlan addressSpacePlan = CodecV1.getMapper().readValue(json, AddressSpacePlan.class); + assertThat(addressSpacePlan.getMetadata().getName(), is("myspace")); + assertThat(addressSpacePlan.getAdditionalProperties().get("displayName"), is("MySpace")); + assertFalse(addressSpacePlan.getUuid().isEmpty()); + assertThat(addressSpacePlan.getAddressPlans().size(), is(1)); + assertThat(addressSpacePlan.getAddressPlans().get(0), is("plan1")); + assertThat(addressSpacePlan.getResources().size(), is(2)); + assertThat(addressSpacePlan.getResources().get(0).getName(), is("router")); + assertThat(addressSpacePlan.getResources().get(1).getName(), is("broker")); + assertThat(addressSpacePlan.getMetadata().getAnnotations().size(), is(1)); + assertThat(addressSpacePlan.getMetadata().getAnnotations().get("mykey"), is("myvalue")); + } + + @Test + public void testDeserializeAddressSpacePlanWithDefaults() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpacePlan\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"addressPlans\":[\"plan1\"]," + + "\"addressSpaceType\": \"standard\"," + + "\"resources\": [" + + " { \"name\": \"router\", \"min\": 0.5, \"max\": 1.0 }, " + + " { \"name\": \"broker\", \"min\": 0.1, \"max\": 0.5 }" + + "]" + + "}"; + + AddressSpacePlan addressSpacePlan = CodecV1.getMapper().readValue(json, AddressSpacePlan.class); + assertThat(addressSpacePlan.getMetadata().getName(), is("myspace")); + assertNull(addressSpacePlan.getUuid()); + assertThat(addressSpacePlan.getAddressPlans().size(), is(1)); + assertThat(addressSpacePlan.getAddressPlans().get(0), is("plan1")); + assertThat(addressSpacePlan.getResources().size(), is(2)); + assertThat(addressSpacePlan.getResources().get(0).getName(), is("router")); + assertThat(addressSpacePlan.getResources().get(1).getName(), is("broker")); + } + + @Test + public void testBuilder() { + AddressSpacePlan plan = new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace("ns") + .build()) + .withShortDescription("desc") + .withUuid("uuid") + .withAddressPlans(Arrays.asList("a", "b")) + .build(); + assertEquals(2, plan.getAddressPlans().size()); + assertEquals("plan1", plan.getMetadata().getName()); + assertEquals("desc", plan.getShortDescription()); + } + + /* + @Test + public void testDeserializeResourceDefinitionWithTemplate() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"ResourceDefinition\"," + + "\"metadata\":{" + + " \"name\":\"rdef1\"" + + "}," + + "\"template\": \"mytemplate\"," + + "\"parameters\": [" + + " {\"name\": \"MY_VAR1\", \"value\": \"MY_VAL1\"}," + + " {\"name\": \"MY_VAR2\", \"value\": \"MY_VAL2\"}" + + "]}"; + + ResourceDefinition rdef = CodecV1.getMapper().readValue(json, ResourceDefinition.class); + assertThat(rdef.getName(), is("rdef1")); + assertTrue(rdef.getTemplateName().isPresent()); + assertThat(rdef.getTemplateName().get(), is("mytemplate")); + Map parameters = rdef.getTemplateParameters(); + assertThat(parameters.size(), is(2)); + assertThat(parameters.get("MY_VAR1"), is("MY_VAL1")); + assertThat(parameters.get("MY_VAR2"), is("MY_VAL2")); + } + + @Test + public void testDeserializeResourceDefinitionNoTemplate() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"ResourceDefinition\"," + + "\"metadata\":{" + + " \"name\":\"rdef1\"" + + "}" + + "}"; + + ResourceDefinition rdef = CodecV1.getMapper().readValue(json, ResourceDefinition.class); + assertThat(rdef.getName(), is("rdef1")); + assertFalse(rdef.getTemplateName().isPresent()); + }*/ + + @Test + public void testDeserializeAddressPlan() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressPlan\"," + + "\"metadata\":{" + + " \"name\":\"plan1\"" + + "}," + + "\"displayName\": \"MyPlan\"," + + "\"shortDescription\": \"MyPlan is cool\"," + + "\"longDescription\": \"MyPlan is cool, but not much used anymore\"," + + "\"addressType\": \"queue\"," + + "\"requiredResources\": [" + + " { \"name\": \"router\", \"credit\": 0.2 }," + + " { \"name\": \"broker\", \"credit\": 0.5 }" + + "]" + + "}"; + + AddressPlan addressPlan = CodecV1.getMapper().readValue(json, AddressPlan.class); + assertThat(addressPlan.getMetadata().getName(), is("plan1")); + assertThat(addressPlan.getAdditionalProperties().get("displayName"), is("MyPlan")); + assertThat(addressPlan.getAddressType(), is("queue")); + assertNull(addressPlan.getUuid()); + assertThat(addressPlan.getRequiredResources().size(), is(2)); + assertThat(addressPlan.getRequiredResources().get(0).getName(), is("router")); + assertThat(addressPlan.getRequiredResources().get(1).getName(), is("broker")); + } + + @Test + public void testDeserializeAddressPlanWithDefaults() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressPlan\"," + + "\"metadata\":{" + + " \"name\":\"plan1\"" + + "}," + + "\"addressType\": \"queue\"," + + "\"requiredResources\": [" + + " { \"name\": \"router\", \"credit\": 0.2 }," + + " { \"name\": \"broker\", \"credit\": 0.5 }" + + "]" + + "}"; + + AddressPlan addressPlan = CodecV1.getMapper().readValue(json, AddressPlan.class); + assertThat(addressPlan.getMetadata().getName(), is("plan1")); + assertThat(addressPlan.getAddressType(), is("queue")); + assertNull(addressPlan.getUuid()); + assertThat(addressPlan.getRequiredResources().size(), is(2)); + assertThat(addressPlan.getRequiredResources().get(0).getName(), is("router")); + assertThat(addressPlan.getRequiredResources().get(1).getName(), is("broker")); + } + + @Test + public void testDeserializeAddressSpaceWithMissingAuthServiceValues() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\": {" + + " \"type\":\"standard\"," + + " \"authenticationService\": {" + + " \"type\": \"external\"" + + " }" + + "}" + + "}"; + + assertThrows(RuntimeException.class, () -> CodecV1.getMapper().readValue(json, AddressSpace.class)); + } + + @Test + public void testDeserializeAddressSpaceWithExtraAuthServiceValues() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.i/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\": {" + + " \"type\":\"standard\"," + + " \"authenticationService\": {" + + " \"type\": \"standard\"," + + " \"details\": {" + + " \"host\": \"my.example.com\"" + + " }" + + " }" + + "}" + + "}"; + + assertThrows(DeserializeException.class, () -> CodecV1.getMapper().readValue(json, AddressSpace.class)); + } + + @Test + public void testSerializeAddressSpaceList() throws IOException { + AddressSpace a1 = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .setPlan("myplan") + .setType("standard") + .setStatus(new AddressSpaceStatus(true).appendMessage("hello")) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .build())) + .build(); + + AddressSpace a2 = new AddressSpace.Builder() + .setName("mysecondspace") + .setNamespace("myothernamespace") + .setPlan("myotherplan") + .setType("brokered") + .setStatus(new AddressSpaceStatus(false)) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("bestendpoint") + .setService("mqtt") + .setCertSpec(new CertSpec.Builder().setProvider("myprovider").setSecretName("mysecret").build()) + .build())) + .build(); + + AddressSpaceList list = new AddressSpaceList(); + list.add(a1); + list.add(a2); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + + AddressSpaceList deserialized = CodecV1.getMapper().readValue(serialized, AddressSpaceList.class); + + assertAddressSpace(deserialized, a1); + assertAddressSpace(deserialized, a2); + } + + private void assertAddressSpace(AddressSpaceList deserialized, AddressSpace expected) { + AddressSpace found = null; + for (AddressSpace addressSpace : deserialized) { + if (addressSpace.getName().equals(expected.getName())) { + found = addressSpace; + break; + } + + } + assertNotNull(found); + + assertThat(found.getName(), is(expected.getName())); + assertThat(found.getNamespace(), is(expected.getNamespace())); + assertThat(found.getType(), is(expected.getType())); + assertThat(found.getPlan(), is(expected.getPlan())); + assertThat(found.getStatus().isReady(), is(expected.getStatus().isReady())); + assertThat(found.getStatus().getMessages(), is(expected.getStatus().getMessages())); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java new file mode 100644 index 0000000000..027e1e35ac --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.admin.model.v1; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.address.model.InfraConfigDeserializer; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfraConfigDeserializerTest { + + private final InfraConfigDeserializer deserializer = json -> new ObjectMapper().readValue(json, StandardInfraConfig.class); + + + @Test + public void deserializeNetworkPolicy() throws Exception { + + + String str = "{\n" + + " \"spec\": {\n" + + " \"networkPolicy\": {\n" + + " \"ingress\": [\n" + + " {\n" + + " \"from\": [\n" + + " {\n" + + " \"podSelector\": {\n" + + " \"my\": \"label\"\n" + + " }\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + + InfraConfig infraConfig = deserializer.fromJson(str); + + assertTrue(infraConfig instanceof StandardInfraConfig); + + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java new file mode 100644 index 0000000000..5857f5cbdc --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java @@ -0,0 +1,224 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.user.model.v1; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +public class UserModelTest { + @Test + public void testSerializeUserPassword() throws IOException { + User user = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + ObjectMapper mapper = new ObjectMapper(); + byte [] serialized = mapper.writeValueAsBytes(user); + + User deserialized = mapper.readValue(serialized, User.class); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + + UserList list = new UserList(); + list.getItems().add(user); + + serialized = mapper.writeValueAsBytes(list); + UserList deserializedList = mapper.readValue(serialized, UserList.class); + + assertEquals(1, deserializedList.getItems().size()); + + deserialized = deserializedList.getItems().get(0); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + } + + @Test + public void testSerializeUserFederated() throws IOException { + User user = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.federated) + .withProvider("openshift") + .withFederatedUserid("uuid") + .withFederatedUsername("user1") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + ObjectMapper mapper = new ObjectMapper(); + byte [] serialized = mapper.writeValueAsBytes(user); + + User deserialized = mapper.readValue(serialized, User.class); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + + UserList list = new UserList(); + list.getItems().add(user); + + serialized = mapper.writeValueAsBytes(list); + UserList deserializedList = mapper.readValue(serialized, UserList.class); + + assertEquals(1, deserializedList.getItems().size()); + + deserialized = deserializedList.getItems().get(0); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + } + + @Test + public void testValidation() { + createAndValidate("myspace.user1", "user1", true); + createAndValidate("myspace.usEr1", "user1", false); + createAndValidate("myspace.user1", "usEr1", false); + createAndValidate("myspace.user1", "usEr1", false); + createAndValidate("myspaceuser1", "user1", false); + + createAndValidate("myspace.user1_", "user1", false); + createAndValidate("myspace_.user1", "user1", false); + createAndValidate("_myspace.user1", "user1", false); + createAndValidate("myspace._user1", "user1", false); + createAndValidate("myspace.user1", "user1_", false); + createAndValidate("myspace.user_1", "user1", false); + createAndValidate("myspace.user1", "user_1", true); + + createAndValidate("myspace.user1@", "user1", false); + createAndValidate("myspace@.user1", "user1", false); + createAndValidate("@myspace.user1", "user1", false); + createAndValidate("myspace.@user1", "user1", false); + createAndValidate("myspace.user1", "user1@", false); + createAndValidate("myspace.user@1", "user1", true); + createAndValidate("myspace.user1", "user@1", true); + + createAndValidate("myspace.user1@example.com", "user1@example.com", true); + + createAndValidate("myspace.user1-", "user1", false); + createAndValidate("myspace-.user1", "user1", false); + createAndValidate("-myspace.user1", "user1", false); + createAndValidate("myspace.-user1", "user1", false); + createAndValidate("myspace.user1", "user1-", false); + createAndValidate("myspace.user1", "-user1-", false); + createAndValidate("myspace.user1-foo-bar", "user1-foo-bar", true); + UUID uuid = UUID.randomUUID(); + createAndValidate("myspace." + uuid.toString(), uuid.toString(), true); + createAndValidate("a.ab", "ab", true); + createAndValidate("aa.b", "b", true); + createAndValidate("a.b", "b", true); + } + + private void createAndValidate(String name, String username, boolean shouldValidate) { + User u1 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(name) + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername(username) + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.federated) + .withProvider("openshift") + .withFederatedUserid("uuid") + .withFederatedUsername("user1") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + try { + u1.validate(); + assertTrue(shouldValidate); + } catch (UserValidationFailedException e) { + // e.printStackTrace(); + assertFalse(shouldValidate); + } + } + + private void assertAuthorization(User deserialized, List addresses, List operations) { + for (UserAuthorization authorization : deserialized.getSpec().getAuthorization()) { + if (authorization.getOperations().equals(operations) && authorization.getAddresses().equals(addresses)) { + return; + } + } + fail("Unable to find matching authorization"); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java new file mode 100644 index 0000000000..293fa8a248 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java @@ -0,0 +1,348 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.api.server; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.auth.AuthApi; +import io.enmasse.api.auth.SubjectAccessReview; +import io.enmasse.api.auth.TokenReview; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.metrics.api.Metrics; +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.*; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpClientRequest; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.time.Clock; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(VertxExtension.class) +public class HTTPServerTest { + + private Vertx vertx; + private TestAddressSpaceApi instanceApi; + private AddressSpace addressSpace; + + @BeforeEach + public void setup(VertxTestContext context) throws InterruptedException { + vertx = Vertx.vertx(); + instanceApi = new TestAddressSpaceApi(); + String addressSpaceName = "myinstance"; + addressSpace = createAddressSpace(addressSpaceName); + instanceApi.createAddressSpace(addressSpace); + + AuthApi authApi = mock(AuthApi.class); + when(authApi.getNamespace()).thenReturn("controller"); + when(authApi.performTokenReview(eq("mytoken"))).thenReturn(new TokenReview("foo", "myid", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + + UserApi userApi = mock(UserApi.class); + UserList users = new UserList(); + users.getItems().add(new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myinstance.user1") + .withNamespace("myinstance") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("admin") + .build()) + .withAuthorization(Arrays.asList(new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build()); + when(userApi.listUsers(any())).thenReturn(users); + + ApiServerOptions options = new ApiServerOptions(); + options.setVersion("1.0"); + options.setCertDir("/doesnotexist"); + vertx.deployVerticle(new HTTPServer(instanceApi, new TestSchemaProvider(), authApi, userApi, new Metrics(), options, null, null, Clock.systemUTC()), context.succeeding(arg -> context.completeNow())); + } + + @AfterEach + public void teardown(VertxTestContext context) { + vertx.close(context.succeeding(arg -> context.completeNow())); + } + + private AddressSpace createAddressSpace(String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(name) + .setType("type1") + .setPlan("myplan") + .setStatus(new io.enmasse.address.model.AddressSpaceStatus(false)) + .appendEndpoint(new EndpointSpec.Builder() + .setName("foo") + .setService("messaging") + .build()) + .build(); + } + + @Test + public void testAddressingApi(VertxTestContext context) throws InterruptedException { + instanceApi.withAddressSpace(addressSpace).createAddress( + new Address.Builder() + .setAddressSpace("myinstance") + .setName("myinstance.addr1") + .setAddress("addR1") + .setNamespace("ns") + .setType("queue") + .setPlan("myplan") + .build()); + + HttpClient client = vertx.createHttpClient(); + try { + { + HttpClientRequest r1 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses", response -> { + context.verify(() -> assertEquals(200, response.statusCode())); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> { + assertTrue(data.containsKey("items")); + assertEquals("myinstance.addr1", data.getJsonArray("items").getJsonObject(0).getJsonObject("metadata").getString("name")); + }); + context.completeNow(); + }); + }); + putAuthzToken(r1); + r1.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + { + HttpClientRequest r2 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addresses/myinstance.addr1", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> { + assertTrue(data.containsKey("metadata")); + assertEquals("myinstance.addr1", data.getJsonObject("metadata").getString("name")); + }); + context.completeNow(); + }); + }); + putAuthzToken(r2); + r2.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + { + HttpClientRequest r3 = client.post(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses", response -> { + response.bodyHandler(buffer -> { + context.verify(() -> assertEquals(201, response.statusCode())); + context.completeNow(); + }); + }); + r3.putHeader("Content-Type", "application/json"); + putAuthzToken(r3); + r3.end("{\"apiVersion\":\"enmasse.io/v1alpha1\",\"kind\":\"AddressList\",\"items\":[{\"metadata\":{\"name\":\"a4\"},\"spec\":{\"address\":\"a4\",\"type\":\"queue\",\"plan\":\"plan1\"}}]}"); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + { + HttpClientRequest r4 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses?address=addR1", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + System.out.println(data.toString()); + context.verify(() -> { + assertTrue(data.containsKey("metadata")); + assertEquals("addR1", data.getJsonObject("spec").getString("address")); + }); + context.completeNow(); + }); + }); + putAuthzToken(r4); + r4.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + } finally { + client.close(); + } + } + + private static HttpClientRequest putAuthzToken(HttpClientRequest request) { + request.putHeader("Authorization", "Bearer mytoken"); + return request; + } + + @Test + public void testApiResources(VertxTestContext context) throws InterruptedException { + HttpClient client = vertx.createHttpClient(); + try { + { + HttpClientRequest rootReq = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1", response -> { + context.verify(() -> assertEquals(200, response.statusCode())); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> assertTrue(data.containsKey("resources"))); + JsonArray resources = data.getJsonArray("resources"); + context.verify(() -> assertEquals(3, resources.size())); + context.completeNow(); + }); + }); + putAuthzToken(rootReq); + rootReq.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + { + HttpClientRequest rootReq = client.get(8080, "localhost", "/apis/user.enmasse.io/v1alpha1", response -> { + context.verify(() -> assertEquals(200, response.statusCode())); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> assertTrue(data.containsKey("resources"))); + JsonArray resources = data.getJsonArray("resources"); + context.verify(() -> assertEquals(1, resources.size())); + context.completeNow(); + }); + }); + putAuthzToken(rootReq); + rootReq.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + } finally { + client.close(); + } + } + + @Test + public void testSchemaApi(VertxTestContext context) throws InterruptedException { + HttpClient client = vertx.createHttpClient(); + try { + { + HttpClientRequest request = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/myinstance/addressspaceschemas", response -> { + context.verify(() -> assertEquals(200, response.statusCode())); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + System.out.println(data.toString()); + context.verify(() -> { + assertTrue(data.containsKey("items")); + assertEquals(1, data.getJsonArray("items").size()); + }); + context.completeNow(); + }); + }); + putAuthzToken(request); + request.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + } finally { + client.close(); + } + } + + @Test + public void testUserApi(VertxTestContext context) throws Exception { + HttpClient client = vertx.createHttpClient(); + try { + { + HttpClientRequest r1 = client.get(8080, "localhost", "/apis/user.enmasse.io/v1alpha1/namespaces/ns/messagingusers", response -> { + context.verify(() -> assertEquals(200, response.statusCode())); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> { + assertTrue(data.containsKey("items")); + assertEquals("myinstance.user1", data.getJsonArray("items").getJsonObject(0).getJsonObject("metadata").getString("name")); + }); + context.completeNow(); + }); + }); + putAuthzToken(r1); + r1.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } + } finally { + client.close(); + } + } + + /* + @Test + public void testInstanceApi() throws InterruptedException { + Instance instance = new Instance.Builder(AddressSpaceId.withId("myinstance")) + .messagingHost(Optional.of("messaging.example.com")) + .build(); + addressSpaceApi.createAddressSpace(instance); + + HttpClient client = vertx.createHttpClient(); + try { + { + final CountDownLatch latch = new CountDownLatch(1); + client.getNow(8080, "localhost", "/v3/addressspace", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + assertTrue(data.containsKey("kind")); + assertThat(data.getString("kind"), is("InstanceList")); + assertTrue(data.containsKey("items")); + JsonArray items = data.getJsonArray("items"); + assertThat(items.size(), is(1)); + assertThat(items.getJsonObject(0).getJsonObject("spec").getString("messagingHost"), is("messaging.example.com")); + latch.countDown(); + }); + }); + assertTrue(latch.await(1, TimeUnit.MINUTES)); + } + + { + final CountDownLatch latch = new CountDownLatch(1); + client.getNow(8080, "localhost", "/v3/addressspace/myinstance", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + assertTrue(data.containsKey("metadata")); + assertThat(data.getJsonObject("metadata").getString("name"), is("myinstance")); + assertThat(data.getString("kind"), is("Instance")); + assertThat(data.getJsonObject("spec").getString("messagingHost"), is("messaging.example.com")); + latch.countDown(); + }); + }); + assertTrue(latch.await(1, TimeUnit.MINUTES)); + } + } finally { + client.close(); + } + } + */ + + @Test + public void testOpenApiSpec(VertxTestContext context) throws InterruptedException { + HttpClientOptions options = new HttpClientOptions(); + HttpClient client = vertx.createHttpClient(options); + try { + HttpClientRequest request = client.get(8080, "localhost", "/swagger.json", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> assertTrue(data.containsKey("paths"))); + context.completeNow(); + }); + }); + putAuthzToken(request); + request.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } finally { + client.close(); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java new file mode 100644 index 0000000000..954f98710c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java @@ -0,0 +1,207 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.api.v1; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.AddressApi; +import io.enmasse.k8s.api.AddressSpaceApi; +import org.apache.http.auth.BasicUserPrincipal; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExpectedExceptionSupport; +import org.junit.rules.ExpectedException; +import org.mockito.internal.util.collections.Sets; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.SecurityContext; +import java.util.*; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +@ExtendWith(ExpectedExceptionSupport.class) +public class AddressApiHelperTest { + + @Rule + public final ExpectedException expectedException = ExpectedException.none(); + + private AddressApiHelper helper; + private AddressApi addressApi; + private SecurityContext securityContext; + + @Before + public void setup() { + AddressSpace addressSpace = mock(AddressSpace.class); + when(addressSpace.getType()).thenReturn("type1"); + AddressSpaceApi addressSpaceApi = mock(AddressSpaceApi.class); + addressApi = mock(AddressApi.class); + securityContext = mock(SecurityContext.class); + when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("me")); + when(securityContext.isUserInRole(any())).thenReturn(true); + when(addressSpaceApi.getAddressSpaceWithName(any(), eq("test"))).thenReturn(Optional.of(addressSpace)); + when(addressSpaceApi.withAddressSpace(eq(addressSpace))).thenReturn(addressApi); + helper = new AddressApiHelper(addressSpaceApi, new TestSchemaProvider()); + } + + @Test + public void testCreateAddressResourceNameAlreadyExists() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.singleton(createAddress("q1", "q1"))); + expectedException.expect(BadRequestException.class); + expectedException.expectMessage("Address 'q1' already exists with resource name 'q1'"); + + Address invalidAddress = createAddress("someOtherName", "q1"); + helper.createAddress("test", invalidAddress); + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testCreateAddress() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr = createAddress("someOtherName", "q1"); + helper.createAddress("test", addr); + verify(addressApi).createAddress(eq(addr)); + } + + @Test + public void testCreateAddresses() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr1 = createAddress("test.q1", "q1"); + Address addr2 = createAddress("test.q2", "q2"); + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + verify(addressApi).createAddress(eq(addr1)); + verify(addressApi).createAddress(eq(addr2)); + } + + @Test + public void testCreateAddressesResourceNameAlreadyExists() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.singleton(createAddress("test1.q1", "q1"))); + + Address addr1 = createAddress("test.q1", "q1"); + Address addr2 = createAddress("test.q2", "q2"); + try { + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + fail("Exception not thrown"); + } catch (BadRequestException e) { + // PASS + } + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testCreateAddressesResourceNameDuplicates() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr1 = createAddress("dup", "q1"); + Address addr2 = createAddress("dup", "q2"); + Address addr3 = createAddress("test.q3", "q3"); + try { + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + fail("Exception not thrown"); + } catch (BadRequestException e) { + // PASS + assertEquals("Address resource names must be unique. Duplicate resource names: [dup]", e.getMessage()); + } + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testReplaceAddress() throws Exception { + when(addressApi.replaceAddress(any())).thenReturn(true); + + helper.replaceAddress("test", createAddress("q1")); + verify(addressApi).replaceAddress(eq(createAddress("q1"))); + } + + @Test + public void testReplaceAddressNotFound() throws Exception { + when(addressApi.replaceAddress(any())).thenReturn(false); + expectedException.expect(NotFoundException.class); + expectedException.expectMessage("Address q1 not found"); + + helper.replaceAddress("test", createAddress("q1")); + verify(addressApi, never()).replaceAddress(any(Address.class)); + } + + @Test + public void testReplaceAddressWithInvalidAddress() throws Exception { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("q1", "q1")); + addresses.add(createAddress("q2", "q2")); + when(addressApi.listAddresses(any())).thenReturn(addresses); + when(addressApi.replaceAddress(any())).thenReturn(true); + expectedException.expect(BadRequestException.class); + expectedException.expectMessage("Address 'q2' already exists with resource name 'q2'"); + + Address invalidAddress = createAddress("q1", "q2"); + helper.replaceAddress("test", invalidAddress); + verify(addressApi, never()).replaceAddress(any(Address.class)); + } + + @Test + public void testDeleteAddress() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.of(address)); + when(addressApi.deleteAddress(same(address))).thenReturn(true); + assertNotNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDeleteAddressNotFound() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.empty()); + assertNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDeleteAddressReturningFalse() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.of(address)); + when(addressApi.deleteAddress(same(address))).thenReturn(false); + assertNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDuplicateAddresses() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Sets.newSet(createAddress("q1"), createAddress("q2"))); + + try { + helper.createAddress("test", createAddress("q3", "q1")); + fail("Expected exception for duplicate address"); + } catch (BadRequestException e) { + assertThat(e.getMessage(), is("Address 'q1' already exists with resource name 'q1'")); + } + } + + @Test + public void testParseLabelSelector() throws Exception { + Map labels = AddressApiHelper.parseLabelSelector("key=value"); + assertThat(labels.size(), is(1)); + assertThat(labels.get("key"), is("value")); + + labels = AddressApiHelper.parseLabelSelector("key1=value1,key2=value2,key3=value3"); + assertThat(labels.size(), is(3)); + assertThat(labels.get("key1"), is("value1")); + assertThat(labels.get("key2"), is("value2")); + assertThat(labels.get("key3"), is("value3")); + } + + private Address createAddress(String name, String address) { + return new Address.Builder().setName(name).setNamespace("ns").setAddress(address).setAddressSpace("test").setType("queue").setPlan("plan1").build(); + } + + private Address createAddress(String address) { + return createAddress(address, address); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java new file mode 100644 index 0000000000..0e2e7453e0 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java @@ -0,0 +1,213 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceList; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.k8s.util.TimeUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpAddressSpaceServiceTest { + private HttpAddressSpaceService addressSpaceService; + private TestAddressSpaceApi addressSpaceApi; + private AddressSpace a1; + private AddressSpace a2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @BeforeEach + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + addressSpaceService = new HttpAddressSpaceService(addressSpaceApi, new TestSchemaProvider(), Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + a1 = new AddressSpace.Builder() + .setName("a1") + .setNamespace("myspace") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(123))) + .setEndpointList(Arrays.asList( + new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .build(), + new EndpointSpec.Builder() + .setName("mqtt") + .setService("mqtt") + .build())) + .build(); + + a2 = new AddressSpace.Builder() + .setName("a2") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(12))) + .setNamespace("othernamespace") + .build(); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null, null)); + assertThat(response.getStatus(), is(200)); + AddressSpaceList data = (AddressSpaceList) response.getEntity(); + + assertThat(data.size(), is(2)); + assertThat(data, hasItem(a1)); + assertThat(data, hasItem(a2)); + } + + @Test + public void testListTableFormat() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null, null)); + assertThat(response.getStatus(), is(200)); + Table data = (Table) response.getEntity(); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().size(), is(2)); + } + + @Test + public void testListException() { + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null, null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGet() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.getAddressSpace(securityContext, null, null, "a1")); + assertThat(response.getStatus(), is(200)); + AddressSpace data = ((AddressSpace) response.getEntity()); + + assertThat(data, is(a1)); + assertThat(data.getEndpoints().size(), is(a1.getEndpoints().size())); + } + + @Test + public void testGetTableFormat() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.getAddressSpace(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null, "a1")); + assertThat(response.getStatus(), is(200)); + Table data = ((Table) response.getEntity()); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().get(0).getObject().getMetadata().getName(), is(a1.getName())); + } + + @Test + public void testPut() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).putAnnotation("foo", "bar").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(200)); + + assertFalse(addressSpaceApi.listAddressSpaces(null).isEmpty()); + assertThat(addressSpaceApi.listAddressSpaces(null).iterator().next().getAnnotation("foo"), is("bar")); + } + + @Test + public void testPutChangeType() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).setType("type2").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutChangePlan() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).setPlan("otherplan").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonMatchingAddressSpaceName() { + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, "xxxxxx", a1)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonExistingAddressSpace() { + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1.getName(), a1)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDelete() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null, "a1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status) response.getEntity()).getStatusCode(), is(200)); + + assertThat(addressSpaceApi.listAddressSpaces(null), hasItem(a2)); + assertThat(addressSpaceApi.listAddressSpaces(null).size(), is(1)); + } + + @Test + public void testDeleteException() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null, "a1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testDeleteNotFound() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null, "doesnotexist")); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDeleteAll() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + + Response response = invoke(() -> addressSpaceService.deleteAddressSpaces(securityContext, "myspace")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status) response.getEntity()).getStatusCode(), is(200)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java new file mode 100644 index 0000000000..bfde0678db --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceList; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.k8s.util.TimeUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpClusterAddressSpaceServiceTest { + private HttpClusterAddressSpaceService addressSpaceService; + private TestAddressSpaceApi addressSpaceApi; + private AddressSpace a1; + private AddressSpace a2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @BeforeEach + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + addressSpaceService = new HttpClusterAddressSpaceService(addressSpaceApi, Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + a1 = new AddressSpace.Builder() + .setName("a1") + .setNamespace("myspace") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(123))) + .setEndpointList(Arrays.asList( + new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .build(), + new EndpointSpec.Builder() + .setName("mqtt") + .setService("mqtt") + .build())) + .build(); + + a2 = new AddressSpace.Builder() + .setName("a2") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(12))) + .setNamespace("othernamespace") + .build(); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null)); + assertThat(response.getStatus(), is(200)); + AddressSpaceList data = (AddressSpaceList) response.getEntity(); + + assertThat(data.size(), is(2)); + assertThat(data, hasItem(a1)); + assertThat(data, hasItem(a2)); + } + + @Test + public void testListTableFormat() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null)); + assertThat(response.getStatus(), is(200)); + Table data = (Table) response.getEntity(); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().size(), is(2)); + } + + @Test + public void testListException() { + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null)); + assertThat(response.getStatus(), is(500)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java new file mode 100644 index 0000000000..0505b4703d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java @@ -0,0 +1,268 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressList; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.v1.Either; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.TestAddressApi; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Set; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpNestedAddressServiceTest { + private HttpNestedAddressService addressService; + private TestAddressSpaceApi addressSpaceApi; + private TestAddressApi addressApi; + private Address q1; + private Address a1; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @BeforeEach + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + this.addressService = new HttpNestedAddressService(addressSpaceApi, new TestSchemaProvider(), Clock.fixed(Instant.ofEpochSecond(1234), ZoneId.of("UTC"))); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .build(); + + addressSpaceApi.createAddressSpace(addressSpace); + addressApi = (TestAddressApi) addressSpaceApi.withAddressSpace(addressSpace); + q1 = new Address.Builder() + .setName("q1") + .setAddress("Q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .build(); + a1 = new Address.Builder() + .setName("a1") + .setAddress("A1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("anycast") + .build(); + addressApi.createAddress(q1); + addressApi.createAddress(a1); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", null, null)); + + assertThat(response.getStatus(), is(200)); + AddressList list = (AddressList) response.getEntity(); + + assertThat(list.size(), is(2)); + assertThat(list, hasItem(q1)); + assertThat(list, hasItem(a1)); + } + + @Test + public void testListTableFormat() { + Response response = invoke(() -> addressService.getAddressList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns", "myspace", null, null)); + + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(9)); + assertThat(table.getRows().size(), is(2)); + } + + @Test + public void testGetByAddress() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", "A1", null)); + + assertThat(response.getStatus(), is(200)); + Address address = (Address) response.getEntity(); + + assertThat(address, is(a1)); + } + + @Test + public void testGetByAddressNotFound() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", "b1", null)); + + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testListException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", null, null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGet() { + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(200)); + Address address = (Address) response.getEntity(); + + assertThat(address, is(q1)); + } + + @Test + public void testGetTableFormat() { + Response response = invoke(() -> addressService.getAddress(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(9)); + assertThat(table.getRows().get(0).getObject().getMetadata().getName(), is(q1.getName())); + } + + @Test + public void testGetException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGetUnknown() { + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "doesnotexist")); + assertThat(response.getStatus(), is(404)); + } + + + @Test + public void testCreate() { + Address a2 = new Address.Builder() + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.createAddress(securityContext, new ResteasyUriInfo("http://localhost:8443/", null, "/"), "ns", "myspace", Either.createLeft(a2))); + assertThat(response.getStatus(), is(201)); + + Address a2ns = new Address.Builder(a2).setNamespace("ns").build(); + assertThat(addressApi.listAddresses("ns"), hasItem(a2ns)); + } + + @Test + public void testCreateException() { + addressApi.throwException = true; + Address a2 = new Address.Builder() + .setAddress("a2") + .setPlan("plan1") + .setAddressSpace("myspace") + .setType("anycast") + .build(); + Response response = invoke(() -> addressService.createAddress(securityContext, null, "ns", "myspace", Either.createLeft(a2))); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPut() { + Set
addresses = addressApi.listAddresses("ns"); + assertThat(addresses.isEmpty(), is(false)); + Address address = addresses.iterator().next(); + Address a1 = new Address.Builder(address).setPlan("plan1").build(); + + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", a1.getName(), a1)); + assertThat(response.getStatus(), is(200)); + + Address a2ns = new Address.Builder(a1).setNamespace("ns").build(); + assertThat(addressApi.listAddresses("ns"), hasItem(a2ns)); + } + + @Test + public void testPutNonMatchingAddressName() { + Address a2 = new Address.Builder() + .setName("a2") + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", "xxxxxxx", a2)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonExistingAddress() { + Address a2 = new Address.Builder() + .setName("a2") + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", a2.getName(), a2)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDelete() { + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "a1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status) response.getEntity()).getStatusCode(), is(200)); + + assertThat(addressApi.listAddresses("ns"), hasItem(q1)); + assertThat(addressApi.listAddresses("ns").size(), is(1)); + } + + @Test + public void testDeleteException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "a1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testDeleteNotFound() { + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "notFound")); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void deleteAllAddresses() { + Response response = invoke(() -> addressService.deleteAddresses(securityContext, "unknown")); + assertThat(response.getStatus(), is(200)); + assertThat(addressApi.listAddresses("ns").size(), is(2)); + + response = invoke(() -> addressService.deleteAddresses(securityContext, "ns")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status) response.getEntity()).getStatusCode(), is(200)); + assertThat(addressApi.listAddresses("ns").size(), is(0)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java new file mode 100644 index 0000000000..78c420cd91 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java @@ -0,0 +1,360 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.user.model.v1.*; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; + +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpUserServiceTest { + private HttpUserService userService; + private TestAddressSpaceApi addressSpaceApi; + private TestUserApi userApi; + private User u1; + private User u2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @BeforeEach + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + userApi = new TestUserApi(); + this.userService = new HttpUserService(addressSpaceApi, userApi, Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + + + addressSpaceApi.createAddressSpace(new AddressSpace.Builder() + .setName("myspace") + .setNamespace("ns1") + .putAnnotation(AnnotationKeys.REALM_NAME, "r1") + .setType("type1") + .setPlan("myplan") + .build()); + + addressSpaceApi.createAddressSpace(new AddressSpace.Builder() + .setName("otherspace") + .setNamespace("ns2") + .putAnnotation(AnnotationKeys.REALM_NAME, "r2") + .setType("type1") + .setPlan("myplan") + .build()); + u1 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + u2 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("otherspace.user2") + .withNamespace("ns2") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user2") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("pswd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withOperations(Arrays.asList(Operation.manage)) + .build())) + .build()) + .build(); + + userApi.createUser("r1", u1); + userApi.createUser("r2", u2); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + Response response = invoke(() -> userService.getUserList(securityContext, null, "ns1", null)); + + assertThat(response.getStatus(), is(200)); + UserList list = (UserList) response.getEntity(); + + assertThat(list.getItems().size(), is(1)); + assertThat(list.getItems(), hasItem(u1)); + } + + @Test + public void testListTable() { + Response response = invoke(() -> userService.getUserList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns1", null)); + + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(4)); + assertThat(table.getRows().size(), is(1)); + } + + @Test + public void testGetByUser() { + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user1")); + + assertThat(response.getStatus(), is(200)); + User user = (User) response.getEntity(); + + assertThat(user, is(u1)); + } + + @Test + public void testGetByUserTable() { + Response response = invoke(() -> userService.getUser(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns1", "myspace.user1")); + + Table table = (Table) response.getEntity(); + + assertThat(response.getStatus(), is(200)); + assertThat(table.getColumnDefinitions().size(), is(4)); + assertThat(table.getRows().get(0).getObject().getMetadata().getName(), is(u1.getMetadata().getName())); + } + + @Test + public void testGetByUserNotFound() { + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user2")); + + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testListException() { + userApi.throwException = true; + Response response = invoke(() -> userService.getUserList(securityContext, null, "ns1", null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGetException() { + userApi.throwException = true; + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testCreate() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.createUser(securityContext, new ResteasyUriInfo("http://localhost:8443/", null, "/"), "ns1", u3)); + assertThat(response.getStatus(), is(201)); + + assertThat(userApi.listUsers("ns1").getItems(), hasItem(u3)); + } + + @Test + public void testCreateException() { + userApi.throwException = true; + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.createUser(securityContext, null, "ns1", u3)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPutException() { + userApi.throwException = true; + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPutNotMatchingName() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNotExists() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user3", u3)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testPut() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue2", "topic2")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(200)); + } + + @Test + public void testDelete() { + Response response = invoke(() -> userService.deleteUser(securityContext, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status) response.getEntity()).getStatusCode(), is(200)); + + assertTrue(userApi.listUsers("ns1").getItems().isEmpty()); + assertFalse(userApi.listUsers("ns2").getItems().isEmpty()); + } + + @Test + public void testDeleteException() { + userApi.throwException = true; + Response response = invoke(() -> userService.deleteUser(securityContext, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void deleteAllUsers() { + Response response = invoke(() -> userService.deleteUsers(securityContext, "unknown")); + assertThat(response.getStatus(), is(200)); + assertThat(userApi.listUsers("ns1").getItems().size(), is(1)); + + response = invoke(() -> userService.deleteUsers(securityContext, "ns1")); + assertThat(response.getStatus(), is(200)); + assertThat(userApi.listUsers("ns1").getItems().size(), is(0)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java new file mode 100644 index 0000000000..ce019eb0e8 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java @@ -0,0 +1,106 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.User; +import io.enmasse.user.model.v1.UserList; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class TestUserApi implements UserApi { + private final Map> userMap = new HashMap<>(); + public boolean throwException = false; + + @Override + public Optional getUserWithName(String realm, String name) { + if (throwException) { + throw new RuntimeException("exception"); + } + return Optional.ofNullable(userMap.get(realm).get(name)); + } + + @Override + public void createUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + String name = user.getSpec().getUsername(); + userMap.computeIfAbsent(realm, k -> new HashMap<>()).put(name, user); + + } + + @Override + public boolean replaceUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + + String name = user.getSpec().getUsername(); + Map users = userMap.computeIfAbsent(realm, k -> new HashMap<>()); + if (!users.containsKey(name)) { + return false; + } + users.put(name, user); + return true; + } + + @Override + public void deleteUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + Map m = userMap.get(realm); + if (m != null) { + m.remove(user.getSpec().getUsername()); + } + } + + @Override + public boolean realmExists(String realm) { + return userMap.containsKey(realm); + } + + @Override + public UserList listUsers(String namespace) { + if (throwException) { + throw new RuntimeException("exception"); + } + UserList list = new UserList(); + for (Map users : userMap.values()) { + for (User user : users.values()) { + if (user.getMetadata().getNamespace().equals(namespace)) { + list.getItems().add(user); + } + } + } + return list; + } + + @Override + public UserList listUsersWithLabels(String namespace, Map labels) { + if (throwException) { + throw new RuntimeException("exception"); + } + return listUsers(namespace); + } + + @Override + public void deleteUsers(String namespace) { + if (throwException) { + throw new RuntimeException("exception"); + } + for (Map users : userMap.values()) { + for (User user : new ArrayList<>(users.values())) { + if (user.getMetadata().getNamespace().equals(namespace)) { + users.remove(user.getSpec().getUsername()); + } + } + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java new file mode 100644 index 0000000000..259fe0097e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java @@ -0,0 +1,467 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.artemis.sasl_delegation; + +import io.vertx.core.AbstractVerticle; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.net.NetSocket; +import io.vertx.proton.ProtonConnection; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonServerOptions; +import io.vertx.proton.sasl.ProtonSaslAuthenticator; +import io.vertx.proton.sasl.impl.ProtonSaslPlainImpl; +import org.apache.activemq.artemis.core.security.Role; +import org.apache.activemq.artemis.core.settings.HierarchicalRepository; +import org.apache.activemq.artemis.core.settings.impl.HierarchicalObjectRepository; +import org.apache.activemq.artemis.spi.core.security.jaas.CertificateCallback; +import org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal; +import org.apache.activemq.artemis.spi.core.security.jaas.UserPrincipal; +import org.apache.qpid.proton.amqp.Symbol; +import org.apache.qpid.proton.engine.Sasl; +import org.apache.qpid.proton.engine.Transport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.LoginException; +import javax.security.cert.CertificateException; +import javax.security.cert.X509Certificate; +import java.nio.charset.StandardCharsets; +import java.security.Principal; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +public class SaslDelegatingLoginTest { + + private SaslDelegatingLogin loginModule; + private Map options = new HashMap<>(); + private Map validLogins = new HashMap<>(); + private Map> groups = new HashMap<>(); + private int port; + private AuthServer authServer; + private Vertx vertx; + private String verticleId; + private String mechName; + private SaslGroupBasedSecuritySettingsPlugin securityPlugin = new SaslGroupBasedSecuritySettingsPlugin(); + + @BeforeEach + public void setup() throws ExecutionException, InterruptedException { + options.clear(); + loginModule = new SaslDelegatingLogin(); + + Map initMap = new HashMap<>(); + initMap.put("name", "test"); + initMap.put("useGroupsFromSaslDelegation", "true"); + securityPlugin.init(initMap); + HierarchicalRepository> repo = new HierarchicalObjectRepository<>(); + repo.setDefault(Collections.emptySet()); + securityPlugin.setSecurityRepository(repo); + + CompletableFuture portFuture = new CompletableFuture<>(); + mechName = ProtonSaslPlainImpl.MECH_NAME; + authServer = new AuthServer(portFuture); + vertx = Vertx.vertx(); + CompletableFuture idFuture = new CompletableFuture<>(); + vertx.deployVerticle(authServer, result -> { + if (result.succeeded()) { + idFuture.complete(result.result()); + } else { + idFuture.completeExceptionally(result.cause()); + } + }); + verticleId = idFuture.get(); + port = portFuture.get(); + options.put("hostname", "127.0.0.1"); + options.put("port", port); + options.put("security_settings", "test"); + options.put("default_roles_authenticated", "all"); + } + + @AfterEach + public void tearDown() { + vertx.close(); + } + + // successful credentials login with roles + @Test + public void testSuccessfulCredentialLogin() throws Exception { + Subject subject = new Subject(); + validLogins.put("user", "password"); + groups.put("user", Arrays.asList("send_a", "recv_b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + assertTrue(loginModule.login(), "Login unexpectedly failed"); + assertEquals(0, subject.getPrincipals().size(), "No principals should be added until after the commit"); + assertTrue(loginModule.commit(), "Commit unexpectedly failed"); + assertEquals(Collections.singleton("user"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected user principal names"); + assertEquals(new HashSet<>(Arrays.asList("send_a", "recv_b", "all")), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected role principal names"); + } + + // unsuccessful credentials login + @Test + public void testUnsuccessfulCredentialLogin() throws Exception { + Subject subject = new Subject(); + validLogins.put("user", "password2"); + groups.put("user", Arrays.asList("a", "b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + assertFalse(loginModule.login(), "Login unexpectedly succeeded"); + assertEquals(0, subject.getPrincipals().size(), "No principals should be added until after the commit"); + loginModule.commit(); + assertEquals(Collections.emptySet(), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected user principal names"); + assertEquals(Collections.emptySet(), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected role principal names"); + + } + + // no matching sasl mechanism + @Test + public void testUnsuccessfulCredentialLoginWithBadMechanism() throws Exception { + mechName = "WIBBLE"; + Subject subject = new Subject(); + validLogins.put("user", "password"); + groups.put("user", Arrays.asList("a", "b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + try { + loginModule.login(); + fail("Login should not succeed if there are no matching mechanisms"); + } catch (LoginException e) { + // pass + } + } + + // successful cert login + @Test + public void testSuccessfulCertLogin() throws Exception { + + options.put("valid_cert_users", "foo:a,b;bar:c"); + + Subject subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_FOO)), Collections.emptyMap(), options); + assertTrue(loginModule.login(), "Login unexpectedly failed"); + assertEquals(0, subject.getPrincipals().size(), "No principals should be added until after the commit"); + assertTrue(loginModule.commit(), "Commit unexpectedly failed"); + assertEquals(Collections.singleton("foo"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected user principal names"); + assertEquals(new HashSet<>(Arrays.asList("a", "b")), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected role principal names"); + + subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_BAR)), Collections.emptyMap(), options); + assertTrue(loginModule.login(), "Login unexpectedly failed"); + assertEquals(0, subject.getPrincipals().size(), "No principals should be added until after the commit"); + assertTrue(loginModule.commit(), "Commit unexpectedly failed"); + assertEquals(Collections.singleton("bar"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected user principal names"); + assertEquals(Collections.singleton("c"), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected role principal names"); + + } + + // unsuccessful cert login + @Test + public void testUnsuccessfulCertLogin() throws Exception { + + Map options = new HashMap<>(); + options.put("valid_cert_users", "foo:a,b;bar:c"); + + Subject subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_BANANA)), Collections.emptyMap(), options); + assertFalse(loginModule.login(), "Login unexpectedly succeeded"); + assertEquals(0, subject.getPrincipals().size(), "No principals should be added until after the commit"); + loginModule.commit(); + assertEquals(Collections.emptySet(), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected user principal names"); + assertEquals(Collections.emptySet(), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet()), "Unexpected role principal names"); + + } + + + private CallbackHandler createCallbackHandler(String user, char[] password, X509Certificate... certificates) { + return callbacks -> { + for (Callback callback : callbacks) { + if (callback instanceof NameCallback && user != null) { + ((NameCallback) callback).setName(user); + } else if (callback instanceof PasswordCallback && password != null) { + ((PasswordCallback) callback).setPassword(password); + } else if (callback instanceof CertificateCallback && (certificates.length != 0)) { + ((CertificateCallback) callback).setCertificates(certificates); + } + } + }; + } + + private X509Certificate generateCertificate(String cert) throws CertificateException { + return X509Certificate.getInstance(cert.getBytes(StandardCharsets.US_ASCII)); + } + + private static final Symbol ADDRESS_AUTHZ_CAPABILITY = Symbol.valueOf("ADDRESS-AUTHZ"); + private static final Symbol ADDRESS_AUTHZ_PROPERTY = Symbol.valueOf("address-authz"); + + private final class AuthServer extends AbstractVerticle { + + + private ProtonServer server; + private final CompletableFuture portFuture; + private final SaslAuthenticator saslAuthenticator; + + private AuthServer(CompletableFuture portFuture) { + this.portFuture = portFuture; + saslAuthenticator = new SaslAuthenticator(); + } + + private void connectHandler(ProtonConnection connection) { + String containerId = "auth-server"; + connection.setContainer(containerId); + connection.openHandler(conn -> { + Map props = new HashMap<>(); + Map claims = new HashMap<>(); + claims.put("sub", saslAuthenticator.getUser()); + claims.put("preferred_username", saslAuthenticator.getUser()); + props.put(Symbol.valueOf("authenticated-identity"), claims); + if (connection.getRemoteDesiredCapabilities() != null && Arrays.asList(connection.getRemoteDesiredCapabilities()).contains(ADDRESS_AUTHZ_CAPABILITY)) { + connection.setOfferedCapabilities(new Symbol[]{ADDRESS_AUTHZ_CAPABILITY}); + if (groups.containsKey(saslAuthenticator.getUser())) { + props.put(ADDRESS_AUTHZ_PROPERTY, getPermissionsFromGroups(groups.get(saslAuthenticator.getUser()))); + } + } + + if (groups.containsKey(saslAuthenticator.getUser())) { + props.put(Symbol.valueOf("groups"), groups.get(saslAuthenticator.getUser())); + } + connection.setProperties(props); + connection.open(); + connection.close(); + }).closeHandler(conn -> { + connection.close(); + connection.disconnect(); + }).disconnectHandler(protonConnection -> { + connection.disconnect(); + }); + + } + + Map getPermissionsFromGroups(List groups) { + Map> authMap = new HashMap<>(); + for (String group : groups) { + String[] parts = group.split("_", 2); + if (parts[0] != null) { + Set permissions = authMap.computeIfAbsent(parts[1], a -> new HashSet<>()); + permissions.add(parts[0]); + } + } + return authMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toArray(new String[e.getValue().size()]))); + } + + + @Override + public void start() { + ProtonServerOptions options = new ProtonServerOptions(); + + server = ProtonServer.create(vertx, options); + server.saslAuthenticatorFactory(() -> saslAuthenticator); + server.connectHandler(this::connectHandler); + + server.listen(0, "127.0.0.1", event -> { + if (event.failed()) { + portFuture.completeExceptionally(event.cause()); + } else { + portFuture.complete(server.actualPort()); + } + }); + } + + @Override + public void stop() { + if (server != null) { + server.close(); + } + } + + } + + private static final String CERT_FOO = "-----BEGIN CERTIFICATE-----\n" + + "MIIFDjCCAvagAwIBAgIJAJjPI7TtVOCpMA0GCSqGSIb3DQEBBQUAMA4xDDAKBgNV\n" + + "BAMTA2ZvbzAeFw0xNzEwMTIwODU4NTNaFw0xODEwMTIwODU4NTNaMA4xDDAKBgNV\n" + + "BAMTA2ZvbzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALsasR9eE/77\n" + + "qmt1Gjz+/wJzu3V9pgde1iBuwoXHKGZyayMHLucnKXVF3o7DEk0R/1m3hKh5QoNV\n" + + "BHgiUzfjxKFxk85F00G/B1FkDXGjxqUz84hsSnOZS7917AdVHQ4FNfbUIeWgkRe3\n" + + "EqK/C3QiyVPr0Uou9jU+YLxOItB22KXVKO3gtBaZfaj8MpzPi8XOxesfpTB+1Fws\n" + + "336aYeeDxH78t05EnwqEd+bX7BPs+0DsReARKVi1v9YNRUX2AAQDBGqLKz39Eg0M\n" + + "0BaiRLv7O4i0DEJlGYC05P8L5Nb8JwZ8XQV0jlZrqNiqSqL2Glt+m4LkBLFwDfZz\n" + + "Q95FVeSSD4AlUB1eHnv41lT3SDOvLV8e6c222MDuC0V7eKDdCWVNlzQpwMyZKeBR\n" + + "HOl5IRjVAi2+JEE7YyzgIn68ZY2YLOBzoUKawPeThak6hJEzDaXzpUVJtKH9LnIW\n" + + "Yyt+K+c9/Sm4Cs95tCALA005r4GSypcTIdAdOpO9UcS4ObeKRhdCFHgkNitkw4i0\n" + + "X2i80y7lzoEV64ZbzMpqq0jWN2LzkHNU5zl5AoL7s8pFMSoQruOEOhIq3yHlDJ9W\n" + + "0cGgzz2XvTQgXtCi4H/pVSXo7ojLffGW5CP4+k8iFAO4uIsqAUKRG2kCSNv3KTMj\n" + + "f6d00flOm6S2+zIBCSz8UF8RmUknf6Y/AgMBAAGjbzBtMB0GA1UdDgQWBBTlJ705\n" + + "R48NTZMfuQyn9D4TeEeDvjA+BgNVHSMENzA1gBTlJ705R48NTZMfuQyn9D4TeEeD\n" + + "vqESpBAwDjEMMAoGA1UEAxMDZm9vggkAmM8jtO1U4KkwDAYDVR0TBAUwAwEB/zAN\n" + + "BgkqhkiG9w0BAQUFAAOCAgEAB0Xamx2uhf7kixCyS2RVGubxTjgu0r+jz9fk6iPW\n" + + "PzzAAb364NkgtWqOg4yOD88VjtRy1meNhOYs/lZ4Eo7STBpsb+zNF1fB9Yg9cNqy\n" + + "A3W6Wjuon7pMWXZDmXFlehPSibbO2tnaiBuBe5j6EL5BWrtHHWlvALUrIG9aB9sI\n" + + "oWRg2WK9GJcKQ90huM8z7ZeA8h0tjEhB5UXc9eAtNmsXnIQ1aWq2mb3/Fg9ALrkl\n" + + "9cHXkdGRty1INXi0b3NSa2lK7m0Rt1iWRlIv5Q9DNAGADx6azrWdbSm/DppOQCrm\n" + + "0KgdzpESIt/ZcibWYVkCOkY3KAl3MmgFc/ezOmYhuBMPzxxi+2omt+B1AFaubsRc\n" + + "65FBKjIzLEB+SuNAgfrk1kdttqMNT3JyY7hYLoMM/wryAZ7pxMCJ4ylJ85LTuoFM\n" + + "l9EPPXJI7cnplgsifDwAI0VfCu7VNIYKMUSk5UhJdJIQMPajThjg4EyXtoETcOZR\n" + + "TIN0PGC2W5n7CFO5WLNsQcWi0Rwq/RVy1y6EDYsZBqwvjUTWw9CkLXtJo1Naizb3\n" + + "qS7WskaD+kciXQ/t/aAXCd1zBZU85tjbaiMzAln8LG5jHChGi3lfNR/V24KxmNyY\n" + + "9KoXswCfB65shysC8t9FaJ4DFtcZxxY5jj9DNuzTiIYvdkpHZG+MYjesQDrxX/cp\n" + + "W0s=\n" + + "-----END CERTIFICATE-----\n"; + + private static final String CERT_BAR = "-----BEGIN CERTIFICATE-----\n" + + "MIIFDjCCAvagAwIBAgIJAIoMqv3u2Y9OMA0GCSqGSIb3DQEBBQUAMA4xDDAKBgNV\n" + + "BAMTA2JhcjAeFw0xNzEwMTIwODU5MTNaFw0xODEwMTIwODU5MTNaMA4xDDAKBgNV\n" + + "BAMTA2JhcjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKjew9A5JoJ/\n" + + "PC7fQsUokG9jE+PVwpiXIFXF3dR8pARnMyjq8YXIV66wFKmcRQlM0WvOYBbxVfFT\n" + + "vjo3ASNsoaAt6HEDeCI6BwfJjXnnw3ko7o5TSPVmgS39G9vjGqZEGmbmM/Elrnc/\n" + + "VML5+wGw9g8I6YKFRfs70QxL7BDlO4YSbEki7lppyYSWGMGW7YrByCpgZaO21e5V\n" + + "CyTlREAKbcnchqtIheDjra2syna5G3L7OYGI4k/Y1D1VyShooV2FsJFB6M4TYaGO\n" + + "/T5ewEStMU+E2O79iHWsVUj/Z2gnlnbzPvk6Sy/wWAUP14B3WUPHyzBynRAwYA7u\n" + + "zHodcMLcpcHjBRZGnqEvuSB2muycRrLDtgIlvKxVZ6Da1Y75YGdgRGdxedeuhQky\n" + + "TTiGwctq6FVHH9uV4MTdVNe5eE6pzkuuSBX+X8Hv3LsbqKW0wMvyyZZtTlD19tTe\n" + + "QhJsacpIbCvm/QP+JMOKZtIMaSRdRCj11EtA5bbHJKvHilt1rpufXL9OHnqSr3lp\n" + + "vUiNWq9sKqvxkRvZbKVUVRrjDMA8oOmhMc0llAHunC1m84fwI/SHZ6l6ceqAmWWc\n" + + "JlSLT6vsrfzavibJjVJnXwIsr3Jy3itjpudvFbEz7mB30i9YCjr8OXZr7/x1KYU8\n" + + "SePtV5ZYF3COFE9PomWHwq76VBgtcrKbAgMBAAGjbzBtMB0GA1UdDgQWBBSHMfZS\n" + + "fov+3UCqlB+9oKmDr32SiDA+BgNVHSMENzA1gBSHMfZSfov+3UCqlB+9oKmDr32S\n" + + "iKESpBAwDjEMMAoGA1UEAxMDYmFyggkAigyq/e7Zj04wDAYDVR0TBAUwAwEB/zAN\n" + + "BgkqhkiG9w0BAQUFAAOCAgEAPBq/1p7l0u3vyBAjnmuBPvMEg7UaaNxcrDbl1gf0\n" + + "DpxprCJifZWYp4vsPdCE7zLXyJNfR1Cn0BKJ1hoAGU53Q689KSqRMgRb/lyU1y7s\n" + + "m7nphXR39kTN06YPkQpPs4WGKQc79FIeIxxWBYJzi3wkK2nBAyRXswbtDfVS46j1\n" + + "+kCYENiXFoIQboE4HjZ0G3Wh0Ct8au4oTFiTZ1XyxeKri7TykOwvJRIh3m6nByQi\n" + + "UPYthIWcrcZDk6c0kTOFapS0ufQ7AeynFHiveIT4CL75jdME9Ll/3Re/EgHkOJ/1\n" + + "dElESlcnjdkRzHyHCdXWnDs0gfWj1F56GGUFh0HhrIABl0Uzd/ukCHDzUOLTGRQg\n" + + "eJ3eFLMgjY3oDpbFgEupBRP266e/XbnmzXhDMdguL7+Pp9gka5tA7a67SL05FG0Z\n" + + "nWU5XXLLr+jxh7hIIdpVe+TZxdVMD0znn68MxOz8liJcGmdO+9Gnwg3FLZR0e02L\n" + + "iehS0b/oddF5xMUyDdwt/dIyU1gOc1ozLld1U7RTZIKa2Y0M65vD/sMjfsWku1Kf\n" + + "xaFEMI94vAWa9WyzveDrvFCyQNfqgmdiyh7t81TTMbFMvaGY+VUUT5UsKZX5FPFS\n" + + "AiYa8rwmnlKLVoNC6s9WSrlaPXfpWvucT4YE3L7RJ/WuP8t2oXgLtR/ATjhTnveg\n" + + "d4s=\n" + + "-----END CERTIFICATE-----\n"; + + private static final String CERT_BANANA = "-----BEGIN CERTIFICATE-----\n" + + "MIIFFzCCAv+gAwIBAgIJAOk9W2pKKYDVMA0GCSqGSIb3DQEBBQUAMBExDzANBgNV\n" + + "BAMTBmJhbmFuYTAeFw0xNzEwMTIwODU5MzBaFw0xODEwMTIwODU5MzBaMBExDzAN\n" + + "BgNVBAMTBmJhbmFuYTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJ5L\n" + + "SDzBElCjuFf7jXYaOLDPL3ifeuM01k56oHdBjwmRBPLc/c0Tz5609Q9ODn5PglnZ\n" + + "zhpGayGh/XfJ5iQtP20xKd5zkP/+RHKI9SU/r682nmkLW7KDWfizKP7pmUuHkXz7\n" + + "VxtBTLtQLdEfquKUlPibxKfbGARmRaLv6i1o9nh2z4QotFB++ionlUicmGKbC6aR\n" + + "boCaEydDYP/vvftwcKucfRRKrxJqQ4dlBQ3wwTaJ5eqjXTHTHn0d5gg36xAcUxwr\n" + + "azc7TMeRd3QYhB7hOaJSh5H24X9khrzWSawho6eKk4QrvlXvzGV9Q2QDpsi4jYv5\n" + + "K/+jHgCukLsLW2aRRkFbKbCE4ghuVyOmfedUSj06/obVg+W3XW3dndwRHmc21M5q\n" + + "ECpZqBsitNWj7vaunCgIgBzJjL1IdcMA4gaEt8M0sslPyOrZUNMj1LL+izoN7K7G\n" + + "aD/RqepNEBU5OKVNmZgFyXgZWADIrpPQxGVgrEY0j9Tagw5GgeHvdJNNIeGcVbci\n" + + "/8osHlH4us2/lphUXPrwIAgh4dVIygKhkH6aSRbrq84urqJ57Zghnz9XPDosgdRY\n" + + "l0fMvReMX9J9Tjk3mWfTYlmul19I4LTrWRS1kHlS6KjUweQ/QaMqo1kPD4Kae0SA\n" + + "lLAeDq4Jntj/b1v29kIkhNdCbm1jMUIKhgLaL9l3AgMBAAGjcjBwMB0GA1UdDgQW\n" + + "BBRBDIZnqyn/lKPhosxwYC6eRnSy7DBBBgNVHSMEOjA4gBRBDIZnqyn/lKPhosxw\n" + + "YC6eRnSy7KEVpBMwETEPMA0GA1UEAxMGYmFuYW5hggkA6T1bakopgNUwDAYDVR0T\n" + + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEAMABQyp8wXQnO16+2hSFY2EdO0UGi\n" + + "A/1O6NwiVTMt9A6Ltjk5nQ5t4cgonaHBiMa25HeQ6BJ2iAKGvmPr9R5S9XIjD2BI\n" + + "3ov02bglUCD40EJE1krFJOj3elCBjN6991OOzvWOK38FTlpJTXI9FzTxIqIcjlGJ\n" + + "SB4dbpnJH7Nat3T73n0MrHguGx7SQ+3MS5wvy3ZWO5Eg7Pu1pATfHgQHUwf+uv1T\n" + + "FDD8Ulct/hAGuNvRlRv1nkzplXCM9nY9aW3316Rg1HV/P5aBKaW23Sa6pJlIDEwa\n" + + "whNw8pQlTtahgM36K7AZbGSDBrkIN5+cJd93Orbu4dg2RCVPxLi2/yvNP0t4lBrW\n" + + "5e/5Ye/kLt23Z6Tv/d3BhbM3RwgUVmsTbdjUDChed5u7lwWf77LXW7ptEbDC3Vlk\n" + + "TOeCRsgFzV7OzXEsSlpqXTsR6+Q8a9ffg5vaaaWcwqUQIBfPdFFLmYvDpcJQXOc6\n" + + "rnKe6CnAfpE17tczCQ0TBHp4MkPyuO9WfoCb0+5Lw+O4Ny59NKLKV1zFHSELzaKt\n" + + "4msENSPdy+6YxKMJUlWMe+Z26aj8FCGuFoC17kzXlw9QP/aYPBhh2E0diOpgfs1R\n" + + "0XZg9N4M+d9oJFjK43wdDjUcPdjpfqbrc5IzBY01j7V/r+zFTn+yuLIc8B4MF6Dn\n" + + "DQkhI+BdvtzGTwE=\n" + + "-----END CERTIFICATE-----\n"; + + private class SaslAuthenticator implements ProtonSaslAuthenticator { + + private Sasl sasl; + private String user; + private boolean succeeded; + + private SaslAuthenticator() { + } + + @Override + public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) { + sasl = transport.sasl(); + sasl.server(); + sasl.allowSkip(false); + + sasl.setMechanisms(mechName); + + } + + @Override + public void process(Handler completionHandler) { + String[] remoteMechanisms = sasl.getRemoteMechanisms(); + + if (remoteMechanisms.length > 0) { + byte[] response; + if (sasl.pending() > 0) { + response = new byte[sasl.pending()]; + sasl.recv(response, 0, response.length); + } else { + response = new byte[0]; + } + + int authzidNullPosition = findNullPosition(response, 0); + if (authzidNullPosition < 0) { + throw new IllegalArgumentException("Invalid PLAIN encoding, authzid null terminator not found"); + } + + int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); + if (authcidNullPosition < 0) { + throw new IllegalArgumentException("Invalid PLAIN encoding, authcid null terminator not found"); + } + + String username = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, StandardCharsets.UTF_8); + int passwordLen = response.length - authcidNullPosition - 1; + String password = new String(response, authcidNullPosition + 1, passwordLen, StandardCharsets.UTF_8); + + if (validLogins.containsKey(username)) { + if (password.equals(validLogins.get(username))) { + this.user = username; + succeeded = true; + sasl.done(Sasl.SaslOutcome.PN_SASL_OK); + } else { + sasl.done(Sasl.SaslOutcome.PN_SASL_AUTH); + } + } else { + sasl.done(Sasl.SaslOutcome.PN_SASL_AUTH); + } + completionHandler.handle(true); + } else { + completionHandler.handle(false); + } + } + + private int findNullPosition(byte[] response, int startPosition) { + int position = startPosition; + while (position < response.length) { + if (response[position] == (byte) 0) { + return position; + } + position++; + } + return -1; + } + + @Override + public boolean succeeded() { + return succeeded; + } + + public String getUser() { + return user; + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java new file mode 100644 index 0000000000..69bf795d6d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Host; +import io.enmasse.amqp.Artemis; +import io.enmasse.amqp.PubSubBroker; +import io.vertx.core.Vertx; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +@ExtendWith(VertxExtension.class) +public class QueueDrainerTest { + private QueueDrainer client; + private PubSubBroker fromServer; + private PubSubBroker toServer; + private TestManagementServer localBroker; + private Host from; + private Host to; + private Vertx vertx; + + + @BeforeEach + public void setup(VertxTestContext context) throws Exception { + vertx = Vertx.vertx(); + fromServer = new PubSubBroker("fromServer"); + toServer = new PubSubBroker("toServer"); + vertx.deployVerticle(fromServer, ar -> { + if (ar.succeeded()) { + context.completeNow(); + } else { + context.failNow(ar.cause()); + } + }); + + vertx.deployVerticle(toServer, ar -> { + if (ar.succeeded()) { + context.completeNow(); + } else { + context.failNow(ar.cause()); + } + }); + context.awaitCompletion(30, TimeUnit.SECONDS); + from = TestUtil.createHost("127.0.0.1", fromServer.port()); + to = TestUtil.createHost("127.0.0.1", toServer.port()); + localBroker = new TestManagementServer(); + + client = new QueueDrainer(Vertx.vertx(), from, (vertx, clientOptions, endpoint) -> new Artemis(localBroker), new ProtonClientOptions(), Optional.empty()); + } + + @Test + public void testDrain() throws Exception { + sendMessages(fromServer, "myqueue", "testfrom", 100); + sendMessages(fromServer, "queue2", "q2from", 10); + sendMessages(toServer, "myqueue", "testto", 100); + sendMessages(toServer, "queue2", "q2to", 1); + + System.out.println("Starting drain"); + + localBroker.setHandler(message -> { + Map props = message.getApplicationProperties().getValue(); + Message response = Proton.message(); + String resourceName = (String) props.get("_AMQ_ResourceName"); + if ("broker".equals(resourceName) && + "getQueueNames".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[[\"myqueue\"],[\"queue2\"]]")); + } else if ("queue.myqueue".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("myqueue") + "]")); + } else if ("queue.queue2".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("queue2") + "]")); + } else { + response.setBody(new AmqpValue("[]")); + } + return response; + }); + + client.drainMessages(to.amqpEndpoint(), ""); + assertThat(toServer.numMessages("myqueue"), is(200)); + assertThat(toServer.numMessages("queue2"), is(11)); + + assertReceive(toServer, "myqueue", "testto", 100); + assertReceive(toServer, "myqueue", "testfrom", 100); + assertReceive(toServer, "queue2", "q2to", 1); + assertReceive(toServer, "queue2", "q2from", 10); + + System.out.println("Checking shutdown"); + } + + private static void sendMessages(PubSubBroker broker, String address, String prefix, int numMessages) throws IOException, InterruptedException { + List messages = IntStream.range(0, numMessages) + .mapToObj(i -> prefix + i) + .collect(Collectors.toList()); + broker.sendMessages(address, messages); + } + + private static void assertReceive(PubSubBroker broker, String address, String prefix, int numMessages) throws IOException, InterruptedException { + List messages = broker.recvMessages(address, numMessages); + for (int i = 0; i < numMessages; i++) { + String actualBody = messages.get(i); + String expectedBody = prefix + i; + assertThat(actualBody, is(expectedBody)); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java new file mode 100644 index 0000000000..12a4fd64b8 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package enmasse.broker.prestop; + +import io.enmasse.amqp.SyncRequestClient; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.message.Message; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +class TestManagementServer implements SyncRequestClient { + + private Handler handler; + + @Override + public void connect(String host, int port, ProtonClientOptions clientOptions, String address, CompletableFuture connectedPromise) { + + } + + @Override + public String getRemoteContainer() { + return null; + } + + @Override + public String getReplyTo() { + return "tome"; + } + + @Override + public void close() { + + } + + public void setHandler(Handler handler) { + this.handler = handler; + } + + @Override + public Message request(Message message, long timeout, TimeUnit timeUnit) { + return handler.handle(message); + } + + public interface Handler { + Message handle(Message message); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java new file mode 100644 index 0000000000..d09111803a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java @@ -0,0 +1,88 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Endpoint; +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonClient; +import io.vertx.proton.ProtonConnection; +import io.vertx.proton.ProtonLinkOptions; +import io.vertx.proton.ProtonReceiver; +import org.apache.qpid.proton.amqp.Symbol; +import org.apache.qpid.proton.amqp.messaging.Source; +import org.apache.qpid.proton.amqp.messaging.TerminusDurability; +import org.apache.qpid.proton.message.Message; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +public class TestSubscriber implements AutoCloseable { + private final Vertx vertx = Vertx.vertx(); + private volatile ProtonConnection connection; + + private final BlockingQueue received = new LinkedBlockingQueue<>(); + + public void subscribe(Endpoint endpoint, String address) throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + String containerId = "test-subscriber"; + ProtonClient client = ProtonClient.create(vertx); + client.connect(endpoint.hostname(), endpoint.port(), connection -> { + if (connection.succeeded()) { + ProtonConnection conn = connection.result(); + conn.setContainer(containerId); + conn.closeHandler(res -> { + System.out.println("CLIENT cONN cLOSED"); + }); + this.connection = conn; + System.out.println("Connected: " + connection.result().getRemoteContainer()); + Source source = new Source(); + source.setAddress(address); + source.setCapabilities(Symbol.getSymbol("topic")); + source.setDurable(TerminusDurability.UNSETTLED_STATE); + ProtonReceiver receiver = conn.createReceiver(address, new ProtonLinkOptions().setLinkName(containerId)); + receiver.setSource(source); + receiver.openHandler(res -> { + if (res.succeeded()) { + System.out.println("Opened receiver"); + latch.countDown(); + } else { + System.out.println("Failed opening received: " + res.cause().getMessage()); + } + }); + receiver.closeHandler(res -> { + System.out.println("CLIENT CLOSED"); + conn.close(); + }); + receiver.handler((delivery, message) -> { + System.out.println("GOT MESSAGE"); + received.add(message); + }); + receiver.open(); + conn.open(); + } else { + System.out.println("Connection failed: " + connection.cause().getMessage()); + } + }); + latch.await(1, TimeUnit.MINUTES); + } + + public void unsubscribe() { + vertx.runOnContext(v -> connection.close()); + } + + @Override + public void close() throws Exception { + unsubscribe(); + vertx.close(); + } + + + public Message receiveMessage(long timeout, TimeUnit timeUnit) throws InterruptedException { + return received.poll(timeout, timeUnit); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java new file mode 100644 index 0000000000..bf4a226aa1 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java @@ -0,0 +1,118 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Endpoint; +import enmasse.discovery.Host; +import io.enmasse.amqp.Artemis; +import io.enmasse.amqp.PubSubBroker; +import io.vertx.core.Vertx; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +@ExtendWith(VertxExtension.class) +public class TopicMigratorTest { + private Host from; + private Host to; + private PubSubBroker fromServer; + private PubSubBroker toServer; + private TestSubscriber subscriber; + private TestPublisher publisher; + private TestManagementServer localBroker; + private Vertx vertx; + + @BeforeEach + public void setup(VertxTestContext context) throws Exception { + vertx = Vertx.vertx(); + subscriber = new TestSubscriber(); + publisher = new TestPublisher(); + fromServer = new PubSubBroker("fromServer"); + toServer = new PubSubBroker("toServer"); + vertx.deployVerticle(fromServer, ar -> { + if (ar.succeeded()) { + context.completeNow(); + } else { + context.failNow(ar.cause()); + } + }); + + vertx.deployVerticle(toServer, ar -> { + if (ar.succeeded()) { + context.completeNow(); + } else { + context.failNow(ar.cause()); + } + }); + context.awaitCompletion(30, TimeUnit.SECONDS); + localBroker = new TestManagementServer(); + from = TestUtil.createHost("127.0.0.1", fromServer.port()); + to = TestUtil.createHost("127.0.0.1", toServer.port()); + } + + @AfterEach + public void teardown() throws Exception { + subscriber.close(); + publisher.close(); + vertx.close(); + } + + @Test + @Disabled + public void testMigrator() throws Exception { + System.out.println("Attempting to subscribe"); + subscriber.subscribe(from.amqpEndpoint(), "mytopic"); + subscriber.unsubscribe(); + + System.out.println("Publishing message"); + publisher.publish(from.amqpEndpoint(), "mytopic", "hello, world"); + + System.out.println("Done publishing"); + TopicMigrator migrator = new TopicMigrator(Vertx.vertx(), from, new Endpoint("messaging.example.com", 5672), (vertx, clientOptions, endpoint) -> new Artemis(localBroker), new ProtonClientOptions()); + + localBroker.setHandler(message -> { + Map props = message.getApplicationProperties().getValue(); + Message response = Proton.message(); + String resourceName = (String) props.get("_AMQ_ResourceName"); + if ("broker".equals(resourceName) && + "getQueueNames".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[[\"mytopic\"]]")); + } else if ("queue.mytopic".equals(resourceName) && + "getAddress".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[\"mytopic\"]")); + } else if ("queue.mytopic".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("mytopic") + "]")); + } else { + System.out.println("Props: " + props); + response.setBody(new AmqpValue("[]")); + } + return response; + }); + + System.out.println("Starting migrator"); + migrator.migrate(Collections.singleton(to)); + + subscriber.subscribe(to.amqpEndpoint(), "mytopic"); + Message message = subscriber.receiveMessage(1, TimeUnit.MINUTES); + assertThat(((AmqpValue) message.getBody()).getValue(), is("hello, world")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java new file mode 100644 index 0000000000..fdd8ec0f7f --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package enmasse.discovery; + +import io.fabric8.kubernetes.api.model.ContainerBuilder; +import io.fabric8.kubernetes.api.model.ContainerPortBuilder; +import io.fabric8.kubernetes.api.model.PodBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; + +public class DiscoveryTest { + + @Test + public void testDiscovery() throws Exception { + Map expectedLabelFilter = Collections.singletonMap("my", "key"); + Map expectedAnnotationFilter = Collections.singletonMap("my", "annotation"); + CompletableFuture> changedHosts = new CompletableFuture<>(); + KubernetesClient kubeClient = mock(KubernetesClient.class); + + System.out.println("Deploying server verticle"); + DiscoveryClient client = new DiscoveryClient(kubeClient, expectedLabelFilter, expectedAnnotationFilter, null); + client.addListener(changedHosts::complete); + + System.out.println("Waiting for subscriber to be created"); + client.resourcesUpdated(Collections.singletonList(createPod("False", "Pending"))); + + System.out.println("Sending second response"); + client.resourcesUpdated(Collections.singletonList(createPod("False", "Running"))); + try { + changedHosts.get(10, TimeUnit.SECONDS); + fail("Ready must be true before returning host"); + } catch (TimeoutException ignored) { + } + + System.out.println("Sending third response"); + client.resourcesUpdated(Collections.singletonList(createPod("True", "Running"))); + try { + Set actual = changedHosts.get(2, TimeUnit.MINUTES); + assertEquals(actual.size(), 1); + Host actualHost = actual.iterator().next(); + assertEquals(actualHost.getHostname(), "10.0.0.1"); + } catch (Exception e) { + fail("Unexpected exception" + e.getMessage()); + e.printStackTrace(); + } + } + + public enmasse.discovery.Pod createPod(String ready, String phase) { + return new enmasse.discovery.Pod(new PodBuilder() + .editOrNewMetadata() + .withName("mypod") + .withLabels(Collections.singletonMap("my", "key")) + .withAnnotations(Collections.singletonMap("my", "annotation")) + .endMetadata() + .editOrNewStatus() + .withPhase(phase) + .withPodIP("10.0.0.1") + .addNewCondition() + .withType("Ready") + .withStatus(ready) + .endCondition() + .endStatus() + .withNewSpec() + .addToContainers(new ContainerBuilder() + .withName("c") + .addToPorts(new ContainerPortBuilder() + .withName("http") + .withContainerPort(1234) + .build()) + .build()) + .endSpec() + .build()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java new file mode 100644 index 0000000000..96db400f96 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.admin.model.v1.AddressSpacePlan; +import io.enmasse.admin.model.v1.AddressSpacePlanList; +import io.enmasse.admin.model.v1.AdminCrd; +import io.enmasse.admin.model.v1.DoneableAddressSpacePlan; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; + + +@ExtendWith(ExternalResourceSupport.class) +public class AddressSpacePlanApiTest { + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + @Test + public void testNotifiesExisting() throws Exception { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + CustomResourceDefinition crd = AdminCrd.addressSpacePlans(); + AddressSpacePlanApi addressSpacePlanApi = new KubeAddressSpacePlanApi(client, client.getNamespace(), crd); + + client.customResources(crd, AddressSpacePlan.class, AddressSpacePlanList.class, DoneableAddressSpacePlan.class) + .createNew() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace(client.getNamespace()) + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("p1", "p2")) + .done(); + + CompletableFuture> promise = new CompletableFuture<>(); + try (Watch watch = addressSpacePlanApi.watchAddressSpacePlans(items -> { + if (!items.isEmpty()) { + promise.complete(items); + } + }, Duration.ofMinutes(1))) { + List list = promise.get(30, TimeUnit.SECONDS); + assertEquals(1, list.size()); + assertEquals("plan1", list.get(0).getMetadata().getName()); + } + } + + @Test + public void testNotifiesCreated() throws Exception { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + CustomResourceDefinition crd = AdminCrd.addressSpacePlans(); + AddressSpacePlanApi addressSpacePlanApi = new KubeAddressSpacePlanApi(client, client.getNamespace(), crd); + + CompletableFuture> promise = new CompletableFuture<>(); + try (Watch watch = addressSpacePlanApi.watchAddressSpacePlans(items -> { + if (!items.isEmpty()) { + promise.complete(items); + } + + }, Duration.ofSeconds(2))) { + client.customResources(crd, AddressSpacePlan.class, AddressSpacePlanList.class, DoneableAddressSpacePlan.class) + .createNew() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace(client.getNamespace()) + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("p1", "p2")) + .done(); + + List list = promise.get(30, TimeUnit.SECONDS); + assertEquals(1, list.size()); + assertEquals("plan1", list.get(0).getMetadata().getName()); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java new file mode 100644 index 0000000000..edd806fcf2 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.Address; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.util.Optional; +import java.util.UUID; + +import static org.junit.Assert.*; + +@ExtendWith(ExternalResourceSupport.class) +public class ConfigMapAddressApiTest { + private static final String ADDRESS = "myaddress"; + private static final String ADDRESS_TYPE = "mytype"; + private static final String ADDRESS_PLAN = "myplan"; + private static final String ADDRESS_SPACE_NAMESPACE = "myproject"; + private static final String ADDRESS_SPACE = "myspace"; + private static final String ADDRESS_NAME = String.format("%s.%s", ADDRESS_SPACE, ADDRESS); + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + private AddressApi api; + + @BeforeEach + public void setUp() { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + api = new ConfigMapAddressApi(client, UUID.randomUUID().toString()); + } + + @Test + public void create() { + Address address = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + api.createAddress(address); + Optional
readAddress = api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + assertTrue(readAddress.isPresent()); + Address read = readAddress.get(); + + assertEquals(ADDRESS, read.getAddress()); + assertEquals(ADDRESS_SPACE, read.getAddressSpace()); + assertEquals(ADDRESS_NAME, read.getName()); + assertEquals(ADDRESS_TYPE, read.getType()); + assertEquals(ADDRESS_PLAN, read.getPlan()); + } + + @Test + public void replace() { + Address adddress = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + final String annotationKey = "myannotation"; + String annotationValue = "value"; + Address update = new Address.Builder(adddress).putAnnotation(annotationKey, annotationValue).build(); + + api.createAddress(adddress); + assertTrue(api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).isPresent()); + + boolean replaced = api.replaceAddress(update); + assertTrue(replaced); + + Address read = api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).get(); + + assertEquals(ADDRESS_NAME, read.getName()); + assertEquals(annotationValue, read.getAnnotation(annotationKey)); + } + + @Test + public void replaceNotFound() { + Address address = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + boolean replaced = api.replaceAddress(address); + assertFalse(replaced); + } + + @Test + public void delete() { + Address space = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + api.createAddress(space); + + boolean deleted = api.deleteAddress(space); + assertTrue(deleted); + + assertFalse(api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).isPresent()); + + boolean deletedAgain = api.deleteAddress(space); + assertFalse(deletedAgain); + } + + private Address createAddress(String namespace, String name) { + return new Address.Builder() + .setName(name) + .setNamespace(namespace) + .setAddress(ADDRESS) + .setAddressSpace(ADDRESS_SPACE) + .setType(ADDRESS_TYPE) + .setPlan(ADDRESS_PLAN) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java new file mode 100644 index 0000000000..e5d5512425 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.AddressSpace; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + + +/** + * The mock server does not emulate behaviour with respect to resourceVersion. + */ +@ExtendWith(ExternalResourceSupport.class) +public class ConfigMapAddressSpaceApiTest { + private static final String ADDRESS_SPACE_NAME = "myspace"; + private static final String ADDRESS_SPACE_TYPE = "mytype"; + private static final String ADDRESS_SPACE_PLAN = "myplan"; + private static final String ADDRESS_SPACE_NAMESPACE = "myproject"; + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + private AddressSpaceApi api; + + @BeforeEach + public void setUp() { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + api = new ConfigMapAddressSpaceApi(client); + } + + @Test + public void create() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + api.createAddressSpace(space); + Optional readAddressSpace = api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + assertTrue(readAddressSpace.isPresent()); + AddressSpace read = readAddressSpace.get(); + + assertEquals(ADDRESS_SPACE_NAME, read.getName()); + assertEquals(ADDRESS_SPACE_TYPE, read.getType()); + assertEquals(ADDRESS_SPACE_PLAN, read.getPlan()); + } + + @Test + public void replace() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + final String annotationKey = "myannotation"; + String annotationValue = "value"; + AddressSpace update = new AddressSpace.Builder(space).putAnnotation(annotationKey, annotationValue).build(); + + api.createAddressSpace(space); + assertTrue(api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).isPresent()); + + boolean replaced = api.replaceAddressSpace(update); + assertTrue(replaced); + + AddressSpace read = api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).get(); + + assertEquals(ADDRESS_SPACE_NAME, read.getName()); + assertEquals(annotationValue, read.getAnnotation(annotationKey)); + } + + @Test + public void replaceNotFound() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + boolean replaced = api.replaceAddressSpace(space); + assertFalse(replaced); + } + + @Test + public void delete() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + api.createAddressSpace(space); + + boolean deleted = api.deleteAddressSpace(space); + assertTrue(deleted); + + assertFalse(api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).isPresent()); + + boolean deletedAgain = api.deleteAddressSpace(space); + assertFalse(deletedAgain); + } + + private AddressSpace createAddressSpace(String namespace, String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(namespace) + .setType(ADDRESS_SPACE_TYPE) + .setPlan(ADDRESS_SPACE_PLAN) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java new file mode 100644 index 0000000000..2d1e8dcb91 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java @@ -0,0 +1,89 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.fabric8.kubernetes.api.model.DoneableEvent; +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.EventList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; + +import static io.enmasse.k8s.api.EventLogger.Type.Warning; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class KubeEventLoggerTest { + + private enum TestReason implements EventLogger.Reason { + NONE + } + + private enum TestKind implements EventLogger.ObjectKind { + KIND + } + + @Test + public void testLogger() { + String ns = "myspace"; + String component = "me"; + Clock clock = Clock.fixed(Instant.ofEpochSecond(10), ZoneId.of("UTC")); + + String message = "it crashed"; + + KubernetesClient mockClient = mock(KubernetesClient.class); + MixedOperation> eventOperation = mock(MixedOperation.class); + Resource eventResource = mock(Resource.class); + + when(mockClient.events()).thenReturn(eventOperation); + when(eventOperation.inNamespace(any())).thenReturn(eventOperation); + when(eventOperation.withName(startsWith("me."))).thenReturn(eventResource); + when(eventResource.get()).thenReturn(null); + + EventLogger logger = new KubeEventLogger(mockClient, ns, clock, component); + logger.log(TestReason.NONE, "it crashed", Warning, TestKind.KIND, "myqueue"); + + ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); + verify(eventResource).create(eventArgumentCaptor.capture()); + Event newEvent = eventArgumentCaptor.getValue(); + assertNotNull(newEvent); + assertThat(newEvent.getMessage(), is(message)); + assertThat(newEvent.getReason(), is(TestReason.NONE.name())); + assertThat(newEvent.getType(), is(Warning.name())); + assertThat(newEvent.getFirstTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getLastTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getCount(), is(1)); + assertThat(newEvent.getInvolvedObject().getName(), is("myqueue")); + assertThat(newEvent.getInvolvedObject().getKind(), is(TestKind.KIND.name())); + + newEvent.setFirstTimestamp(Instant.ofEpochSecond(5).toString()); + when(eventResource.get()).thenReturn(newEvent); + logger.log(TestReason.NONE, "it crashed", Warning, TestKind.KIND, "myqueue"); + + eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); + verify(eventResource).create(eventArgumentCaptor.capture()); + newEvent = eventArgumentCaptor.getValue(); + assertNotNull(newEvent); + assertThat(newEvent.getMessage(), is(message)); + assertThat(newEvent.getReason(), is(TestReason.NONE.name())); + assertThat(newEvent.getType(), is(Warning.name())); + assertThat(newEvent.getFirstTimestamp(), is(Instant.ofEpochSecond(5).toString())); + assertThat(newEvent.getLastTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getCount(), is(2)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java new file mode 100644 index 0000000000..9b851c4e33 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java @@ -0,0 +1,146 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.AddressSpaceType; +import io.enmasse.address.model.Schema; +import io.enmasse.admin.model.v1.*; +import io.enmasse.config.AnnotationKeys; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +public class KubeSchemaApiTest { + + private AddressSpacePlanApi addressSpacePlanApi; + private AddressPlanApi addressPlanApi; + private StandardInfraConfigApi standardInfraConfigApi; + private BrokeredInfraConfigApi brokeredInfraConfigApi; + + @BeforeEach + public void setup() { + addressSpacePlanApi = mock(AddressSpacePlanApi.class); + addressPlanApi = mock(AddressPlanApi.class); + standardInfraConfigApi = mock(StandardInfraConfigApi.class); + brokeredInfraConfigApi = mock(BrokeredInfraConfigApi.class); + } + + @Test + public void testSchemaAssemble() { + KubeSchemaApi schemaApi = new KubeSchemaApi(addressSpacePlanApi, addressPlanApi, brokeredInfraConfigApi, standardInfraConfigApi, Clock.systemUTC(), false); + + List addressSpacePlans = Arrays.asList( + new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("spaceplan1") + .addToAnnotations(AnnotationKeys.DEFINED_BY, "infra1") + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("plan1", "plan2")) + .build(), + new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("spaceplan2") + .addToAnnotations(AnnotationKeys.DEFINED_BY, "infra1") + .build()) + .withAddressSpaceType("brokered") + .withAddressPlans(Arrays.asList( "plan3")) + .build()); + + List addressPlans = Arrays.asList( + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .build()) + .withAddressType("queue") + .build(), + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan2") + .build()) + .withAddressType("topic") + .build(), + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan3") + .build()) + .withAddressType("queue") + .build()); + + List standardInfraConfigs = Arrays.asList( + new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("infra1") + .build()) + .build()); + + List brokeredInfraConfigs = Arrays.asList( + new BrokeredInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("infra1") + .build()) + .build()); + + Schema schema = schemaApi.assembleSchema(addressSpacePlans, addressPlans, standardInfraConfigs, brokeredInfraConfigs); + + assertTrue(schema.findAddressSpaceType("standard").isPresent()); + assertTrue(schema.findAddressSpaceType("brokered").isPresent()); + + { + AddressSpaceType type = schema.findAddressSpaceType("standard").get(); + assertTrue(type.findAddressSpacePlan("spaceplan1").isPresent()); + assertFalse(type.findAddressSpacePlan("spaceplan2").isPresent()); + assertTrue(type.findAddressSpacePlan("spaceplan1").get().getAddressPlans().contains("plan1")); + assertTrue(type.findAddressSpacePlan("spaceplan1").get().getAddressPlans().contains("plan2")); + assertTrue(type.findInfraConfig("infra1").isPresent()); + } + { + AddressSpaceType type = schema.findAddressSpaceType("brokered").get(); + assertTrue(type.findAddressSpacePlan("spaceplan2").isPresent()); + assertFalse(type.findAddressSpacePlan("spaceplan1").isPresent()); + assertTrue(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan3")); + assertFalse(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan1")); + assertFalse(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan2")); + assertTrue(type.findInfraConfig("infra1").isPresent()); + } + } + + @Test + public void testWatchCreated() throws Exception { + AddressSpacePlanApi addressSpacePlanApi = mock(AddressSpacePlanApi.class); + AddressPlanApi addressPlanApi = mock(AddressPlanApi.class); + StandardInfraConfigApi standardInfraConfigApi = mock(StandardInfraConfigApi.class); + BrokeredInfraConfigApi brokeredInfraConfigApi = mock(BrokeredInfraConfigApi.class); + + Watch mockWatch = mock(Watch.class); + + when(addressSpacePlanApi.watchAddressSpacePlans(any(), any())).thenReturn(mockWatch); + when(addressPlanApi.watchAddressPlans(any(), any())).thenReturn(mockWatch); + when(brokeredInfraConfigApi.watchBrokeredInfraConfigs(any(), any())).thenReturn(mockWatch); + when(standardInfraConfigApi.watchStandardInfraConfigs(any(), any())).thenReturn(mockWatch); + + SchemaApi schemaApi = new KubeSchemaApi(addressSpacePlanApi, addressPlanApi, brokeredInfraConfigApi, standardInfraConfigApi, Clock.systemUTC(), true); + + schemaApi.watchSchema(items -> { }, Duration.ofSeconds(5)); + verify(addressSpacePlanApi).watchAddressSpacePlans(any(), eq(Duration.ofSeconds(5))); + verify(addressPlanApi).watchAddressPlans(any(), eq(Duration.ofSeconds(5))); + verify(standardInfraConfigApi).watchStandardInfraConfigs(any(), eq(Duration.ofSeconds(5))); + verify(brokeredInfraConfigApi).watchBrokeredInfraConfigs(any(), eq(Duration.ofSeconds(5))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java new file mode 100644 index 0000000000..6529395953 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +import static org.mockito.Mockito.*; + +public class ResourceCheckerTest { + ResourceChecker controller; + Watcher watcher; + + @BeforeEach + public void setup() { + watcher = mock(Watcher.class); + controller = new ResourceChecker<>(watcher, Duration.ofMillis(1)); + } + + @Test + public void testResourcesUpdated() throws Exception { + controller.doWork(); + verify(watcher, never()).onUpdate(any()); + + List items = Arrays.asList("hello", "there"); + controller.onInit(() -> items); + controller.onUpdate(); + controller.doWork(); + verify(watcher).onUpdate(eq(items)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java new file mode 100644 index 0000000000..90b857c4a3 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api.cache; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class EventCacheTest { + @Test + public void testAdd() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.add(map("k1")); + assertTrue(queue.hasSynced()); + assertFalse(queue.listKeys().contains("k1")); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().contains("k1")); + assertTrue(queue.list().contains(map("k1"))); + } + + @Test + public void testUpdate() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.update(map("k1")); + assertFalse(queue.listKeys().contains("k1")); + assertFalse(queue.list().contains(map("k1"))); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().contains("k1")); + assertTrue(queue.list().contains(map("k1"))); + } + + @Test + public void testRemove() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.add(map("k1")); + queue.delete(map("k1")); + assertTrue(queue.hasSynced()); + assertTrue(queue.listKeys().isEmpty()); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().isEmpty()); + assertTrue(queue.list().isEmpty()); + + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().isEmpty()); + assertTrue(queue.list().isEmpty()); + } + + @Test + public void testEmpty() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verifyZeroInteractions(mockProc); + assertFalse(queue.hasSynced()); + } + + @Test + public void testSync() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.replace(Arrays.asList(map("k1"), map("k2"), map("k3")), "33"); + assertFalse(queue.hasSynced()); + assertFalse(queue.list().isEmpty()); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(null); + assertTrue(queue.hasSynced()); + } + + public static ConfigMap map(String name) { + return new ConfigMapBuilder() + .editOrNewMetadata() + .withName(name) + .endMetadata() + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java new file mode 100644 index 0000000000..ad3c58a8a5 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api.cache; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ConfigMapList; +import io.fabric8.kubernetes.api.model.ConfigMapListBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Collections; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + +public class ReflectorTest { + Reflector reflector; + ListerWatcher testLister; + WorkQueue testStore; + Processor testProc; + + @BeforeEach + public void setup() { + testLister = mock(ListerWatcher.class); + testProc = mock(Processor.class); + testStore = new EventCache<>(new HasMetadataFieldExtractor<>()); + + Reflector.Config config = new Reflector.Config<>(); + config.setClock(Clock.fixed(Instant.now(), ZoneId.systemDefault())); + config.setListerWatcher(testLister); + config.setWorkQueue(testStore); + config.setExpectedType(ConfigMap.class); + config.setResyncInterval(Duration.ofSeconds(1)); + config.setProcessor(testProc); + reflector = new Reflector<>(config); + } + + @Test + public void testReflector() throws Exception { + when(testLister.list(any())).thenReturn(new ConfigMapListBuilder() + .editOrNewMetadata() + .withResourceVersion("3") + .endMetadata() + .addToItems(configMap("a1", "a2", "1")) + .addToItems(configMap("a1", "a3", "3")) + .addToItems(configMap("b1", "b2", "2")) + .build()); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(io.fabric8.kubernetes.client.Watcher.class); + + reflector.run(); + verify(testProc, times(1)).process(any()); + reflector.run(); + verify(testProc, times(1)).process(any()); + assertStoreSize(2); + verify(testLister).watch(captor.capture(), any()); + verify(testLister).list(any()); + + assertConfigMap("a1", "a3"); + assertConfigMap("b1", "b2"); + + io.fabric8.kubernetes.client.Watcher watcher = captor.getValue(); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.MODIFIED, configMap("a1", "a4", "5")); + reflector.run(); + assertStoreSize(2); + assertConfigMap("a1", "a4"); + assertConfigMap("b1", "b2"); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.ADDED, configMap("c1", "c4", "5")); + reflector.run(); + assertStoreSize(3); + assertConfigMap("a1", "a4"); + assertConfigMap("b1", "b2"); + assertConfigMap("c1", "c4"); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.DELETED, configMap("b1", "b2", "6")); + reflector.run(); + assertStoreSize(2); + assertConfigMap("a1", "a4"); + assertConfigMap("c1", "c4"); + + reflector.run(); + reflector.run(); + reflector.run(); + reflector.run(); + verify(testProc, times(4)).process(any()); + reflector.run(); + verify(testProc, times(4)).process(any()); + } + + public void assertStoreSize(int expectedSize) throws InterruptedException { + assertThat("Store contains " + testStore.listKeys(), testStore.listKeys().size(), is(expectedSize)); + } + + private void assertConfigMap(String name, String expectedValue) throws InterruptedException { + String actual = findValue(testStore.list(), name); + assertNotNull(actual); + assertThat(actual, is(expectedValue)); + } + + private static String findValue(List list, String name) { + String found = null; + for (ConfigMap map : list) { + if (map.getMetadata().getName().equals(name)) { + found = map.getData().get("data"); + break; + } + } + return found; + } + + private static ConfigMap configMap(String name, String data, String resourceVersion) { + return new ConfigMapBuilder() + .editOrNewMetadata() + .withName(name) + .withResourceVersion(resourceVersion) + .endMetadata() + .withData(Collections.singletonMap("data", data)) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java new file mode 100644 index 0000000000..a4c087b144 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java @@ -0,0 +1,177 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.keycloak.controller; + +import io.enmasse.address.model.*; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.User; +import io.enmasse.user.model.v1.UserList; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class KeycloakManagerTest { + + private KeycloakManager manager; + private Set realms; + private List updatedRealms; + private Map realmAdminUsers; + private KubeApi mockKubeApi; + + @BeforeEach + public void setup() { + realms = new HashSet<>(); + updatedRealms = new LinkedList<>(); + realmAdminUsers = new HashMap<>(); + mockKubeApi = mock(KubeApi.class); + when(mockKubeApi.findUserId(any())).thenReturn(""); + when(mockKubeApi.getIdentityProviderParams()).thenReturn(new KeycloakRealmParams("http://example.com", "id", "secret", Collections.singletonMap("hdr1", "value1"))); + + manager = new KeycloakManager(new KeycloakApi() { + @Override + public Set getRealmNames() { + return new HashSet<>(realms); + } + + @Override + public void createRealm(String namespace, String realmName, String consoleRedirectURI, KeycloakRealmParams params) { + realms.add(realmName); + } + + @Override + public void updateRealm(String realmName, KeycloakRealmParams updated) { + updatedRealms.add(realmName); + } + + @Override + public void deleteRealm(String realmName) { + realms.remove(realmName); + } + }, mockKubeApi, new UserApi() { + @Override + public Optional getUserWithName(String realm, String name) { + return Optional.empty(); + } + + @Override + public void createUser(String realm, User user) { + realmAdminUsers.put(realm, user.getSpec().getUsername()); + } + + @Override + public boolean replaceUser(String realm, User user) { + return false; + } + + @Override + public void deleteUser(String realm, User user) { + + } + + @Override + public boolean realmExists(String realm) { + return true; + } + + @Override + public UserList listUsers(String realm) { + return null; + } + + @Override + public UserList listUsersWithLabels(String realm, Map labels) { + return null; + } + + @Override + public void deleteUsers(String namespace) { + + } + }); + } + + @Test + public void testAddAddressSpace() throws Exception { + manager.onUpdate(Collections.singletonList(createAddressSpace("a1", AuthenticationServiceType.NONE))); + assertTrue(realms.isEmpty()); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE), createAddressSpace("a2", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a2")); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE), createAddressSpace("a2", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a2")); + assertTrue(realms.contains("a3")); + assertEquals(2, realms.size()); + + assertTrue(realmAdminUsers.get("a2").length() > 0); + assertTrue(realmAdminUsers.get("a3").length() > 0); + } + + @Test + public void testRemoveAddressSpace() throws Exception { + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD), createAddressSpace("a2", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + + assertTrue(realms.contains("a1")); + assertFalse(realms.contains("a2")); + assertTrue(realms.contains("a3")); + assertEquals(2, realms.size()); + } + + @Test + public void testAuthTypeChanged() throws Exception { + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a1")); + assertEquals(1, realms.size()); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE))); + assertFalse(realms.contains("a1")); + assertEquals(0, realms.size()); + } + + @Test + public void testUpdateRealm() throws Exception { + List spaces = Collections.singletonList(createAddressSpace("a1", AuthenticationServiceType.STANDARD)); + manager.onUpdate(spaces); + assertTrue(realms.contains("a1")); + assertTrue(updatedRealms.isEmpty()); + + manager.onUpdate(spaces); + assertTrue(updatedRealms.isEmpty()); + + when(mockKubeApi.getIdentityProviderParams()).thenReturn(new KeycloakRealmParams("http://example.com", "id", "secret2", Collections.singletonMap("hdr1", "value1"))); + + manager.onUpdate(spaces); + assertEquals(1, updatedRealms.size()); + } + + private AddressSpace createAddressSpace(String name, AuthenticationServiceType authType) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace("myns") + .setPlan("myplan") + .setType("standard") + .putAnnotation(AnnotationKeys.CREATED_BY, "developer") + .appendEndpoint(new EndpointSpec.Builder() + .setName("console") + .setService("console") + .build()) + .setStatus(new AddressSpaceStatus(true) + .appendEndpointStatus(new EndpointStatus.Builder() + .setName("console") + .setServiceHost("console.svc") + .setExternalPorts(Collections.singletonMap("http", 443)) + .setExternalHost("console.example.com") + .build())) + .setAuthenticationService(new AuthenticationService.Builder().setType(authType).build()).build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java new file mode 100644 index 0000000000..4c4e257c6d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.keycloak.controller; + +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.server.mock.KubernetesServer; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExternalResourceSupport; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ExtendWith(ExternalResourceSupport.class) +public class KeycloakRealmParamsTest { + @Rule + public KubernetesServer server = new KubernetesServer(true, true); + + private KubernetesClient client; + + @BeforeEach + public void setup() { + client = server.getClient(); + } + + @Test + public void testRequiredEnvironment() { + client.configMaps().createNew() + .editOrNewMetadata() + .withName("myconfig") + .endMetadata() + .addToData("identityProviderUrl", "https://localhost:8443/auth") + .addToData("identityProviderClientId", "myclient") + .addToData("identityProviderClientSecret", "mysecret") + .done(); + + KeycloakRealmParams params = KeycloakRealmParams.fromKube(client, "myconfig"); + assertEquals("https://localhost:8443/auth", params.getIdentityProviderUrl()); + assertEquals("myclient", params.getIdentityProviderClientId()); + assertEquals("mysecret", params.getIdentityProviderClientSecret()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java new file mode 100644 index 0000000000..baba4373bd --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.enmasse.keycloak.spi; + + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +public class AmqpServerTest { + + @Test + public void testEmptyGroupsGeneratesEmptyPermissions() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(Collections.emptySet()); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("foo")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("foo_bar")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("send")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + } + + @Test + public void testMultiplePermissionsForSameAddress() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(new HashSet<>(Arrays.asList("send_foo", "consume_foo"))); + assertNotNull(props); + assertEquals(1, props.size()); + assertNotNull(props.get("foo")); + assertEquals(2, props.get("foo").length); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("send"))); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("recv"))); + } + + + @Test + public void testMultiplePermissionsWithUrlEncoding() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(new HashSet<>(Arrays.asList("send_foo%2Fbar", "view_%66oo%2Fbar", "recv_foo"))); + assertNotNull(props); + assertEquals(2, props.size()); + assertNotNull(props.get("foo/bar")); + assertEquals(2, props.get("foo/bar").length); + assertTrue(Arrays.stream(props.get("foo/bar")).anyMatch(e -> e.equals("send"))); + assertEquals(2, props.get("foo/bar").length); + assertTrue(Arrays.stream(props.get("foo/bar")).anyMatch(e -> e.equals("view"))); + + assertNotNull(props.get("foo")); + assertEquals(1, props.get("foo").length); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("recv"))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java new file mode 100644 index 0000000000..a1bfcfe63e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.keycloak.Config; +import org.keycloak.models.*; +import org.keycloak.models.credential.PasswordUserCredentialModel; +import org.mockito.ArgumentMatcher; + +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PlainSaslServerMechanismTest { + private KeycloakSessionFactory keycloakSessionFactory; + private KeycloakSession keycloakSession; + private Config.Scope config; + + @BeforeEach + public void setup() { + keycloakSessionFactory = mock(KeycloakSessionFactory.class); + keycloakSession = mock(KeycloakSession.class); + when(keycloakSessionFactory.create()).thenReturn(keycloakSession); + KeycloakTransactionManager txnManager = mock(KeycloakTransactionManager.class); + when(keycloakSession.getTransactionManager()).thenReturn(txnManager); + RealmProvider realms = mock(RealmProvider.class); + when(keycloakSession.realms()).thenReturn(realms); + RealmModel realm = mock(RealmModel.class); + when(realms.getRealmByName(eq("realm"))).thenReturn(realm); + UserProvider userProvider = mock(UserProvider.class); + UserModel user = mock(UserModel.class); + when(userProvider.getUserByUsername(eq("user"), eq(realm))).thenReturn(user); + when(keycloakSession.userStorageManager()).thenReturn(userProvider); + UserCredentialManager userCredentialManager = mock(UserCredentialManager.class); + when(keycloakSession.userCredentialManager()).thenReturn(userCredentialManager); + when(userCredentialManager.isValid(eq(realm), eq(user), argThat(new PasswordCredentialMatcher("password")))).thenReturn(true); + + config = mock(Config.Scope.class); + } + + private byte[] createInitialResponse(final String user, final String password) { + byte[] userBytes = user.getBytes(StandardCharsets.UTF_8); + byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8); + byte[] response = new byte[2 + userBytes.length + passwordBytes.length]; + System.arraycopy(userBytes, 0, response, 1, userBytes.length); + System.arraycopy(passwordBytes, 0, response, 2 + userBytes.length, passwordBytes.length); + + return response; + } + + private static final class PasswordCredentialMatcher implements ArgumentMatcher { + + private final String password; + + private PasswordCredentialMatcher(final String password) { + this.password = password; + } + + @Override + public boolean matches(final PasswordUserCredentialModel item) { + return item.getValue().equals(password); + } + } + + // unknown realm + @Test + public void testUnknownRealm() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "unknownRealm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known realm, unknown user + @Test + public void testUnknownUser() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("unknown", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known user, wrong password + @Test + public void testWrongPassword() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "wrong")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known user, correct password + @Test + public void testCorrectPassword() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertTrue(instance.isAuthenticated()); + } + + // incorrect sasl format + @Test + public void testBadInitialResponse() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + assertThrows(IllegalArgumentException.class, () -> instance.processResponse("potato".getBytes(StandardCharsets.UTF_8))); + } + + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java new file mode 100644 index 0000000000..a723874e07 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.keycloak.credential.CredentialModel; +import org.mockito.ArgumentCaptor; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +public class ScramPasswordHashProviderTest { + private ScramPasswordHashProvider hashprovider; + private CredentialModel credentialModel; + + @BeforeEach + public void setup() { + hashprovider = new ScramPasswordHashProvider("scramsha1", 10000, "HmacSHA1", "SHA-1"); + credentialModel = mock(CredentialModel.class); + + ArgumentCaptor saltCaptor = ArgumentCaptor.forClass(byte[].class); + doAnswer(invocation -> { + when(credentialModel.getSalt()).thenReturn(saltCaptor.getValue()); + return null; + }).when(credentialModel).setSalt(saltCaptor.capture()); + + ArgumentCaptor passwordCaptor = ArgumentCaptor.forClass(String.class); + doAnswer(invocation -> { + when(credentialModel.getValue()).thenReturn(passwordCaptor.getValue()); + return null; + }).when(credentialModel).setValue(passwordCaptor.capture()); + + + ArgumentCaptor iterationsCaptor = ArgumentCaptor.forClass(Integer.class); + doAnswer(invocation -> { + when(credentialModel.getHashIterations()).thenReturn(iterationsCaptor.getValue()); + return null; + }).when(credentialModel).setHashIterations(iterationsCaptor.capture()); + } + + @Test + public void testProviderVerifiesCorrect() { + hashprovider.encode("testpassword", 25000, credentialModel); + assertTrue(hashprovider.verify("testpassword", credentialModel)); + } + + @Test + public void testProviderFailsIncorrect() { + hashprovider.encode("testpassword", 25000, credentialModel); + assertFalse(hashprovider.verify("wrongpassword", credentialModel)); + } + + @Test + public void testSameValueEncodedDifferently() { + Set encoded = new HashSet<>(); + for (int i = 0; i < 100; i++) { + hashprovider.encode("testpassword", 25000, credentialModel); + if (!encoded.add(credentialModel.getValue())) { + fail("Duplicate encoding of the password"); + } + } + + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java new file mode 100644 index 0000000000..49f6696d08 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.keycloak.Config; +import org.keycloak.common.VerificationException; +import org.keycloak.common.util.Time; +import org.keycloak.models.*; +import org.keycloak.representations.AccessToken; + +import java.net.URI; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class XOAUTH2SaslServerMechanismTest implements XOAUTH2SaslServerMechanism.TokenVerifier { + private KeycloakSession keycloakSession; + private Config.Scope config; + private boolean verifyToken; + private KeycloakSessionFactory keycloakSessionFactory; + + @BeforeEach + public void setup() { + keycloakSession = mock(KeycloakSession.class); + keycloakSessionFactory = mock(KeycloakSessionFactory.class); + when(keycloakSessionFactory.create()).thenReturn(keycloakSession); + KeycloakTransactionManager txnManager = mock(KeycloakTransactionManager.class); + when(keycloakSession.getTransactionManager()).thenReturn(txnManager); + RealmProvider realms = mock(RealmProvider.class); + when(keycloakSession.realms()).thenReturn(realms); + RealmModel realm = mock(RealmModel.class); + when(realm.getName()).thenReturn("realm"); + when(realms.getRealmByName(eq("realm"))).thenReturn(realm); + ClientModel clientModel = mock(ClientModel.class); + when(clientModel.isEnabled()).thenReturn(true); + when(realm.getClientByClientId("client")).thenReturn(clientModel); + UserProvider userProvider = mock(UserProvider.class); + UserModel user = mock(UserModel.class); + when(userProvider.getUserByUsername(eq("user"), eq(realm))).thenReturn(user); + when(keycloakSession.userStorageManager()).thenReturn(userProvider); + UserCredentialManager userCredentialManager = mock(UserCredentialManager.class); + when(keycloakSession.userCredentialManager()).thenReturn(userCredentialManager); + + UserSessionProvider userSessionProvider = mock(UserSessionProvider.class); + when(keycloakSession.sessions()).thenReturn(userSessionProvider); + UserSessionModel userSessionModel = mock(UserSessionModel.class); + when(userSessionProvider.getUserSessionWithPredicate(any(), any(), anyBoolean(), any())).thenReturn(userSessionModel); + when(userSessionModel.getStarted()).thenReturn(Time.currentTime()); + when(userSessionModel.getLastSessionRefresh()).thenReturn(Time.currentTime()); + when(realm.getSsoSessionMaxLifespan()).thenReturn(36000); + when(realm.getSsoSessionIdleTimeout()).thenReturn(36000); + when(userSessionModel.getUser()).thenReturn(user); + + config = mock(Config.Scope.class); + when(config.get(eq("baseUri"), anyString())).thenReturn("https://localhost:8443/auth"); + } + + private byte[] createInitialResponse(final String user, final String token) { + String initialResponseString="user="+user+"\1auth=Bearer "+token+"\1\1"; + return initialResponseString.getBytes(StandardCharsets.US_ASCII); + } + + // unknown realm + @Test + public void testUnknownRealm() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "unknownRealm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "token")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + + // Invalid token + @Test + public void testWrongPassword() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + this.verifyToken = false; + byte[] response = instance.processResponse(createInitialResponse("user", "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3N0xUZ3BvbFJmU1NqQkNEeTljU3VEeFpkM2hmMTEyN3R5ZzNweU52LVRBIn0.eyJqdGkiOiJmM2E3ZjFhNS0zZGM2LTQ1YjEtOWIyYi1hZjIzYmYxYTc5NTUiLCJleHAiOjE1MjAwODI2NTMsIm5iZiI6MCwiaWF0IjoxNTIwMDgyMzUzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvYW1xcCIsImF1ZCI6ImFtcXAiLCJzdWIiOiI4NjA2NDJiMy0wZmE1LTRiYjctOGI0YS0xZGNiOTdlZjhmZDgiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhbXFwIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiY2Y5Njc0YTAtN2FiNy00YmZiLWI4ZTktZjk3MzM5NTY4NzYwIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInByZWZlcnJlZF91c2VybmFtZSI6Imd1ZXN0In0.Ul33UaC4EXdxtMqv6fLyOHRvHNkA3U1F2FDKxo4Rs4gIvmrbyjK_RN_AciVZjtphYM4xXDn3E9acchyLcQB690NCneDVwqUUj5c2ZU5LcZsAARtBC8MPk8ekDhfmm3ppsRnnSYzucDC1Qe-iLtmhj-v3NzdkgxIwzbgL2E7QzUuf8KFSj2Ue322r27tPhKLm2ay3lcauKe_u3LziA6S1sgxdABWzTBP8UhSeKtqY0j6JT50LA7mvVgmEZvdzqgt6EVYmU0ALzbdjQuOJhmlTDH68cPqQI1-MLAreHt7BDLTN0YuthzoFKheZBaIpBvdDuSI_iV0iAe_AlT16ka4rUg")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + } + + // Validated token + @Test + public void testValidatedToken() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + this.verifyToken = true; + byte[] response = instance.processResponse(createInitialResponse("user", "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3N0xUZ3BvbFJmU1NqQkNEeTljU3VEeFpkM2hmMTEyN3R5ZzNweU52LVRBIn0.eyJqdGkiOiJmM2E3ZjFhNS0zZGM2LTQ1YjEtOWIyYi1hZjIzYmYxYTc5NTUiLCJleHAiOjE1MjAwODI2NTMsIm5iZiI6MCwiaWF0IjoxNTIwMDgyMzUzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvYW1xcCIsImF1ZCI6ImFtcXAiLCJzdWIiOiI4NjA2NDJiMy0wZmE1LTRiYjctOGI0YS0xZGNiOTdlZjhmZDgiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhbXFwIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiY2Y5Njc0YTAtN2FiNy00YmZiLWI4ZTktZjk3MzM5NTY4NzYwIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInByZWZlcnJlZF91c2VybmFtZSI6Imd1ZXN0In0.Ul33UaC4EXdxtMqv6fLyOHRvHNkA3U1F2FDKxo4Rs4gIvmrbyjK_RN_AciVZjtphYM4xXDn3E9acchyLcQB690NCneDVwqUUj5c2ZU5LcZsAARtBC8MPk8ekDhfmm3ppsRnnSYzucDC1Qe-iLtmhj-v3NzdkgxIwzbgL2E7QzUuf8KFSj2Ue322r27tPhKLm2ay3lcauKe_u3LziA6S1sgxdABWzTBP8UhSeKtqY0j6JT50LA7mvVgmEZvdzqgt6EVYmU0ALzbdjQuOJhmlTDH68cPqQI1-MLAreHt7BDLTN0YuthzoFKheZBaIpBvdDuSI_iV0iAe_AlT16ka4rUg")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertTrue(instance.isAuthenticated()); + } + + // incorrect sasl format + @Test + public void testBadInitialResponse() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + assertThrows(IllegalArgumentException.class, () -> instance.processResponse("potato".getBytes(StandardCharsets.UTF_8))); + } + + + @Override + public AccessToken verifyTokenString(RealmModel realm, String tokenString, URI baseUri, KeycloakSession keycloakSession) throws VerificationException { + if(verifyToken) { + AccessToken accessToken = new AccessToken(); + accessToken.issuedFor("client"); + return accessToken; + } else { + throw new VerificationException(); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java new file mode 100644 index 0000000000..70ab624298 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.mqtt; + + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests related to topic wildcards matches + */ +public class TopicMatcherTest { + + @Test + public void testFixedTopicMatch() { + + String subTopic = "mytopic/foo"; + String pubTopic = "mytopic/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testFixedTopicNotMatch() { + + String subTopic = "mytopic/foo"; + String pubTopic = "mytopic/bar"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicSharpWildcardMatch() { + + String subTopic = "mytopic/#"; + String pubTopic = "mytopic/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicSharpWildcardNotMatch() { + + String subTopic = "mytopic/#"; + String pubTopic = "mytopic"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicPlusWildcardMatch() { + + String subTopic = "mytopic/+/bar"; + String pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + pubTopic = "mytopic/another/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/foo/+"; + pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/+/bar/+/foo"; + pubTopic = "mytopic/a/bar/b/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicPlusWildcardNotMatch() { + + String subTopic = "mytopic/+/bar"; + String pubTopic = "mytopic/bar"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/foo/+"; + pubTopic = "mytopic/foo"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/+/bar/+/foo"; + pubTopic = "mytopic/a/bar/b/foo/c"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java new file mode 100644 index 0000000000..6826966cd5 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.mqtt; + +import enmasse.mqtt.messages.AmqpWillMessage; +import enmasse.mqtt.storage.LwtStorage; +import enmasse.mqtt.storage.impl.InMemoryLwtStorage; +import io.netty.handler.codec.mqtt.MqttQoS; +import io.vertx.core.buffer.Buffer; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Tests related to the LWT storage service only + */ +@ExtendWith(VertxExtension.class) +public class InMemoryLwtStorageTest { + + protected final Logger LOG = LoggerFactory.getLogger(InMemoryLwtStorageTest.class); + private static final AmqpWillMessage WILL_MESSAGE = + new AmqpWillMessage(true, "will_topic", MqttQoS.AT_MOST_ONCE, Buffer.buffer("Hello")); + private static final String CLIENT_ID = "client_id"; + private LwtStorage lwtStorage; + + @BeforeEach + public void before(VertxTestContext context) { + + this.lwtStorage = new InMemoryLwtStorage(); + this.lwtStorage.open(context.succeeding(id -> context.completeNow())); + } + + @AfterEach + public void after() { + this.lwtStorage.close(); + } + + @Test + public void addNotExistingWill(VertxTestContext context) { + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + if (done.succeeded()) { + this.lwtStorage.get(CLIENT_ID, done1 -> { + if (done1.succeeded()) { + AmqpWillMessage willMessage1 = done1.result(); + context.verify(() -> assertEquals(willMessage1, WILL_MESSAGE)); + LOG.info("Added a not existing will"); + } else { + context.verify(() -> fail("")); + } + context.completeNow(); + }); + } else { + context.verify(() -> fail("")); + context.completeNow(); + } + }); + } + + @Test + public void addExistingWill(VertxTestContext context) { + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + if (done.succeeded()) { + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done1 -> { + context.verify(() -> assertTrue(!done1.succeeded())); + LOG.info("Will to add already exists"); + context.completeNow(); + }); + } else { + context.verify(() -> fail("")); + context.completeNow(); + } + }); + } + + @Test + public void updateExistingWill(VertxTestContext context) { + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + if (done.succeeded()) { + AmqpWillMessage willMessage1 = new AmqpWillMessage(false, "will_topic_1", MqttQoS.AT_LEAST_ONCE, Buffer.buffer("Hello_1")); + this.lwtStorage.update(CLIENT_ID, willMessage1, done1 -> { + if (done1.succeeded()) { + this.lwtStorage.get(CLIENT_ID, done2 -> { + if (done2.succeeded()) { + AmqpWillMessage willMessage2 = done2.result(); + // updated message not equals to the original one but to the one got from the storage + context.verify(() -> assertTrue(!willMessage1.equals(WILL_MESSAGE) && willMessage1.equals(willMessage2))); + LOG.info("Existing will updated"); + + } else { + context.verify(() -> fail("")); + } + context.completeNow(); + }); + + } else { + context.verify(() -> fail("")); + context.completeNow(); + } + }); + } else { + context.verify(() -> fail("")); + context.completeNow(); + } + }); + } + + @Test + public void updateNotExistingWill(VertxTestContext context) { + this.lwtStorage.update(CLIENT_ID, WILL_MESSAGE, done -> { + context.verify(() -> assertTrue(!done.succeeded())); + LOG.info("Trying to update a not existing will"); + context.completeNow(); + }); + } + + @Test + public void deleteExistingWill(VertxTestContext context) { + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + if (done.succeeded()) { + this.lwtStorage.delete(CLIENT_ID, done1 -> { + context.verify(() -> assertTrue(done1.succeeded())); + LOG.info("Existing will deleted"); + context.completeNow(); + }); + } else { + context.verify(() -> fail("")); + context.completeNow(); + } + }); + } + + @Test + public void deleteNotExistingWill(VertxTestContext context) { + this.lwtStorage.delete(CLIENT_ID, done -> { + context.verify(() -> assertTrue(!done.succeeded())); + LOG.info("Trying to delete a not existing will"); + context.completeNow(); + }); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java new file mode 100644 index 0000000000..9a2dcbb163 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceStatus; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.auth.AuthApi; +import io.enmasse.api.auth.SubjectAccessReview; +import io.enmasse.api.auth.TokenReview; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.osb.api.provision.ConsoleProxy; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpClientRequest; +import io.vertx.core.json.JsonObject; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(VertxExtension.class) +public class HTTPServerTest { + + private Vertx vertx; + private TestAddressSpaceApi instanceApi; + private AddressSpace addressSpace; + private HTTPServer httpServer; + + @BeforeEach + public void setup(VertxTestContext context) { + vertx = Vertx.vertx(); + instanceApi = new TestAddressSpaceApi(); + String addressSpaceName = "myinstance"; + addressSpace = createAddressSpace(addressSpaceName); + instanceApi.createAddressSpace(addressSpace); + + AuthApi authApi = mock(AuthApi.class); + when(authApi.getNamespace()).thenReturn("controller"); + when(authApi.performTokenReview(eq("mytoken"))).thenReturn(new TokenReview("foo", "myid", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + httpServer = new HTTPServer(instanceApi, new TestSchemaProvider(), authApi, null, false, null, 0, new ConsoleProxy() { + @Override + public String getConsoleUrl(AddressSpace addressSpace) { + return "http://localhost/console/" + addressSpaceName; + } + }); + vertx.deployVerticle(httpServer, context.succeeding(id -> context.completeNow())); + } + + @AfterEach + public void teardown(VertxTestContext context) { + vertx.close(context.succeeding(id -> context.completeNow())); + } + + private AddressSpace createAddressSpace(String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(name) + .setType("mytype") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .appendEndpoint(new EndpointSpec.Builder() + .setName("foo") + .setService("messaging") + .build()) + .build(); + } + + @Test + public void testOpenServiceBrokerAPI(VertxTestContext context) throws InterruptedException { + HttpClientOptions options = new HttpClientOptions(); + HttpClient client = vertx.createHttpClient(options); + try { + HttpClientRequest request = client.get(httpServer.getActualPort(), "localhost", "/osbapi/v2/catalog", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.verify(() -> assertTrue(data.containsKey("services"))); + context.completeNow(); + }); + }); + putAuthzToken(request); + request.end(); + context.awaitCompletion(60, TimeUnit.SECONDS); + } finally { + client.close(); + } + } + + private static HttpClientRequest putAuthzToken(HttpClientRequest request) { + request.putHeader("Authorization", "Bearer mytoken"); + return request; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java new file mode 100644 index 0000000000..73490c92ba --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import io.enmasse.api.common.ConflictException; +import io.enmasse.api.common.GoneException; +import io.enmasse.api.common.UnprocessableEntityException; +import io.enmasse.osb.api.bind.BindRequest; +import io.enmasse.osb.api.bind.BindResponse; +import io.enmasse.osb.api.provision.ProvisionRequest; +import org.jboss.resteasy.util.HttpResponseCodes; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +@Disabled +public class BindingServiceTest extends OSBTestBase { + + public static final String BINDING_ID = UUID.randomUUID().toString(); + + @Override + public void setup() throws Exception { + super.setup(); + provisionService(SERVICE_INSTANCE_ID); + } + + @Test + public void testSyncProvisioningRequest() throws Exception { + UriInfo uriInfo = mock(UriInfo.class); + assertThrows(UnprocessableEntityException.class, + () -> provisioningService.provisionService(getSecurityContext(), null, "123", false, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID))); + } + + @Test + @Disabled + public void testBind() throws Exception { + Response response = bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + BindResponse bindResponse = (BindResponse) response.getEntity(); + + assertThat(response.getStatus(), is(HttpResponseCodes.SC_CREATED)); + assertThat(bindResponse.getCredentials().get("namespace"), notNullValue()); + assertThat(bindResponse.getCredentials().get("destination-address"), notNullValue()); + // TODO: Set fake hosts +// assertThat(bindResponse.getCredentials().get("internal-messaging-host"), notNullValue()); +// assertThat(bindResponse.getCredentials().get("internal-mqtt-host"), notNullValue()); + } + + @Test + public void testInvalidBindingUuid() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, "123", new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + } + + @Test + @Disabled + public void testBindOnNonexistentService() throws Exception { + assertThrows(NotFoundException.class, + () -> bindingService.bindServiceInstance(getSecurityContext(), UUID.randomUUID().toString(), BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID))); + } + + @Test + @Disabled + public void testBindWithoutServiceId() throws Exception { + assertThrows(BadRequestException.class, + () -> bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(null, QUEUE_PLAN_ID))); + } + + @Test + @Disabled + public void testBindWithoutPlanId() throws Exception { + assertThrows(BadRequestException.class, + () -> bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, null))); + } + + @Disabled("Not implemented yet") + @Test + public void testWrongServiceId() throws Exception { + assertThrows(BadRequestException.class, + () -> bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(UUID.randomUUID(), QUEUE_PLAN_ID))); + } + + @Disabled("Not implemented yet") + @Test + public void testWrongPlanId() throws Exception { + assertThrows(BadRequestException.class, + () -> bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, UUID.randomUUID()))); + } + + @Disabled("bindings aren't persisted yet, so we can't do this yet") + @Test + public void testBindTwiceWithDifferentPrameters() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + String otherServiceId = UUID.randomUUID().toString(); + provisionService(otherServiceId); + + exceptionGrabber.expect(ConflictException.class); + bindingService.bindServiceInstance(getSecurityContext(), otherServiceId, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + } + + @Disabled("bindings aren't persisted yet, so we can't do this yet") + @Test + public void testBindTwiceWithSameParameters() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + Response response = bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Test + public void testUnbind() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + Response response = bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Disabled("bindings aren't persisted yet, so we can't do this yet. OSB spec mandates the broker MUST return Gone, when binding doesn't exist") + @Test + public void testUnbindNonexistingBinding() throws Exception { + assertThrows(GoneException.class, + () -> bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, UUID.randomUUID().toString())); + } + + @Disabled("bindings aren't persisted yet, so we can't do this yet. OSB spec mandates the broker MUST return Gone, when binding doesn't exist") + @Test + public void testUnbindTwice() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + + exceptionGrabber.expect(GoneException.class); + bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java new file mode 100644 index 0000000000..29aa1c3b86 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import org.junit.jupiter.api.Disabled; + +@Disabled +public class CatalogServiceTest extends OSBTestBase { +/* + @Test + public void testCatalog() throws IOException { + OSBCatalogService catalogService = new OSBCatalogService(new TestAddressSpaceApi(), schemaProvider, "controller"); + + Response response = catalogService.getCatalog(getSecurityContext()); + CatalogResponse catalogResponse = (CatalogResponse) response.getEntity(); + List services = catalogResponse.getServices(); + + assertThat(services.size(), is(4)); + assertService(services.get(0), "enmasse-anycast", "standard"); + assertService(services.get(1), "enmasse-multicast", "standard"); + assertService(services.get(2), "enmasse-queue", "inmemory", "persisted", "pooled-inmemory", "pooled-persisted"); + assertService(services.get(3), "enmasse-topic", "inmemory", "persisted"); + + Service service = services.get(2); + Plan plan = service.getPlans().get(0); + assertThat(plan.getMetadata().get("displayName"), is("In-memory")); + assertThat(plan.getDescription(), is("Creates a standalone broker cluster for queues. Messages are not persisted on stable storage.")); + } + + private void assertService(Service service, String name, String... planNames) { + assertThat(service.getName(), is(name)); + assertThat(service.getPlans().size(), is(planNames.length)); + for (int i = 0; i < planNames.length; i++) { + String planName = planNames[i]; + Plan plan = service.getPlans().get(i); + assertThat(plan.getName(), is(planName)); + } + } + */ +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java new file mode 100644 index 0000000000..3621ed343a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.osb.api.bind.BindRequest; +import io.enmasse.osb.api.provision.ProvisionRequest; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * + */ +public class DeserializationTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testProvisionRequest() throws IOException { + UUID serviceUuid = UUID.randomUUID(); + UUID planUuid = UUID.randomUUID(); + UUID organizationUuid = UUID.randomUUID(); + UUID spaceUuid = UUID.randomUUID(); + + Map map = new HashMap<>(); + map.put("service_id", serviceUuid.toString()); + map.put("plan_id", planUuid.toString()); + map.put("organization_guid", organizationUuid.toString()); + map.put("space_guid", spaceUuid.toString()); + + Map parameters = new HashMap<>(); + parameters.put("foo", "bar"); + parameters.put("baz", "qux"); + map.put("parameters", parameters); + + String serialized = mapper.writeValueAsString(map); + + ProvisionRequest request = mapper.readValue(serialized, ProvisionRequest.class); + assertThat(request.getServiceId(), is(serviceUuid)); + assertThat(request.getPlanId(), is(planUuid)); + assertThat(request.getOrganizationId(), is(organizationUuid.toString())); + assertThat(request.getSpaceId(), is(spaceUuid.toString())); + assertThat(request.getParameters(), is(parameters)); + } + + @Test + public void testBindRequest() throws IOException { + UUID serviceUuid = UUID.randomUUID(); + UUID planUuid = UUID.randomUUID(); + UUID appUuid = UUID.randomUUID(); + + Map map = new HashMap<>(); + map.put("service_id", serviceUuid.toString()); + map.put("plan_id", planUuid.toString()); + + Map bindResource = new HashMap<>(); + bindResource.put("app_guid", appUuid.toString()); + bindResource.put("route", "some-address"); + map.put("bind_resource", bindResource); + + Map parameters = new HashMap<>(); + parameters.put("foo", "bar"); + parameters.put("baz", "qux"); + map.put("parameters", parameters); + + + String serialized = mapper.writeValueAsString(map); + + BindRequest request = mapper.readValue(serialized, BindRequest.class); + assertThat(request.getServiceId(), is(serviceUuid)); + assertThat(request.getPlanId(), is(planUuid)); + assertThat(request.getBindResource().getAppId(), is(appUuid.toString())); + assertThat(request.getBindResource().getRoute(), is("some-address")); + assertThat(request.getParameters(), is(parameters)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java new file mode 100644 index 0000000000..f4f44137b4 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java @@ -0,0 +1,87 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.osb.api.bind.OSBBindingService; +import io.enmasse.osb.api.lastoperation.OSBLastOperationService; +import io.enmasse.osb.api.provision.ConsoleProxy; +import io.enmasse.osb.api.provision.OSBProvisioningService; +import io.enmasse.osb.api.provision.ProvisionRequest; +import org.apache.http.auth.BasicUserPrincipal; +import org.junit.Rule; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.migrationsupport.rules.ExpectedExceptionSupport; +import org.junit.rules.ExpectedException; + +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.core.UriInfo; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * + */ + +@ExtendWith(ExpectedExceptionSupport.class) +public class OSBTestBase { + protected static final UUID QUEUE_SERVICE_ID = ServiceType.QUEUE.uuid(); + protected static final UUID TOPIC_SERVICE_ID = ServiceType.TOPIC.uuid(); + protected static final UUID QUEUE_PLAN_ID = UUID.fromString("3c7f4fdc-0597-11e8-abdb-507b9def37d9"); + protected static final UUID TOPIC_PLAN_ID = UUID.fromString("48837510-0597-11e8-8517-507b9def37d9"); + protected static final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + protected static final String ORGANIZATION_ID = UUID.randomUUID().toString(); + protected static final String SPACE_ID = UUID.randomUUID().toString(); + + @Rule + public ExpectedException exceptionGrabber = ExpectedException.none(); + + protected OSBProvisioningService provisioningService; + protected TestAddressSpaceApi addressSpaceApi; + protected OSBBindingService bindingService; + protected OSBLastOperationService lastOperationService; + + @BeforeEach + public void setup() throws Exception { + addressSpaceApi = new TestAddressSpaceApi(); + String brokerId = "myspace"; + provisioningService = new OSBProvisioningService(addressSpaceApi, null, null, new ConsoleProxy() { + @Override + public String getConsoleUrl(AddressSpace addressSpace) { + return "http://localhost/console/" + addressSpace.getName(); + } + }); + bindingService = new OSBBindingService(addressSpaceApi, null, null, null); + lastOperationService = new OSBLastOperationService(addressSpaceApi, null, null); + } + + protected void provisionService(String serviceInstanceId) throws Exception { + provisionService(serviceInstanceId, ORGANIZATION_ID, SPACE_ID); + } + + protected SecurityContext getSecurityContext() { + SecurityContext securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + when(securityContext.isSecure()).thenReturn(true); + when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("myuser")); + return securityContext; + } + + protected String provisionService(String serviceInstanceId, String organizationId, String spaceId) throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, organizationId, spaceId); + provisionRequest.putParameter("name", "my-queue"); + provisionRequest.putParameter("group", "my-group"); + + UriInfo uriInfo = mock(UriInfo.class); + provisioningService.provisionService(getSecurityContext(), null, serviceInstanceId, true, provisionRequest); + // TODO: wait for provisioning to finish (poll lastOperation endpoint) + return serviceInstanceId; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java new file mode 100644 index 0000000000..8d2cf4705c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java @@ -0,0 +1,193 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.Status; +import io.enmasse.api.common.ConflictException; +import io.enmasse.api.common.GoneException; +import io.enmasse.api.common.UnprocessableEntityException; +import io.enmasse.osb.api.lastoperation.LastOperationResponse; +import io.enmasse.osb.api.lastoperation.LastOperationState; +import io.enmasse.osb.api.provision.ProvisionRequest; +import io.enmasse.osb.api.provision.ProvisionResponse; +import org.jboss.resteasy.util.HttpResponseCodes; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +@Disabled +public class ProvisionServiceTest extends OSBTestBase { + + public static final String QUEUE_SERVICE_ID_STRING = QUEUE_SERVICE_ID.toString(); + public static final String QUEUE_PLAN_ID_STRING = QUEUE_PLAN_ID.toString(); + + public static final String ADDRESS = "my-queue"; + public static final String TRANSACTIONAL = "transactional"; + private UriInfo uriInfo = mock(UriInfo.class); + + @Test + public void testSyncProvisioningRequest() throws Exception { + assertThrows(UnprocessableEntityException.class, + () -> provisioningService.provisionService(getSecurityContext(), null, "123", false, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID))); + } + + @Test + public void testInvalidServiceUuid() throws Exception { + assertThrows(BadRequestException.class, + () -> provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID))); + } + + @Test + public void testInvalidPlan() throws Exception { + assertThrows(BadRequestException.class, + () -> provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, TOPIC_PLAN_ID, ORGANIZATION_ID, SPACE_ID))); + } + + @Test + public void testInvalidServiceInstandeUuid() throws Exception { + assertThrows(BadRequestException.class, + () -> provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID))); + } + + @Test + public void testProvision() throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID); + provisionRequest.putParameter("name", ADDRESS); + provisionRequest.putParameter("transactional", "true"); + Response response = provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + ProvisionResponse provisionResponse = (ProvisionResponse) response.getEntity(); + + assertThat(response.getStatus(), is(HttpResponseCodes.SC_ACCEPTED)); +// assertThat(provisionResponse.getDashboardUrl(), notNullValue()); + assertThat(provisionResponse.getOperation(), notNullValue()); + + Address destination = new Address.Builder() + .setName(ADDRESS) + .setAddress(ADDRESS) + .setAddressSpace("unknown") + .setStatus(new Status(false)) + .setType("queue") + .setPlan("myplan") + .build(); + //assertThat(addressSpaceApi.getAddresses(), is(new HashSet<>(Collections.singletonList(destination)))); + + LastOperationResponse lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.IN_PROGRESS)); + + addressSpaceApi.setAllInstancesReady(true); + + lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.IN_PROGRESS)); + + addressSpaceApi.getAddressApis().iterator().next().setAllAddressesReady(true); + + lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.SUCCEEDED)); + + destination = new Address.Builder() + .setName(ADDRESS) + .setAddress(ADDRESS) + .setAddressSpace("unknown") + .setStatus(new Status(true)) + .setType("queue") + .setPlan("myplan") + .build(); + + //assertThat(addressSpaceApi.getAddresses(), is(new HashSet<>(Collections.singletonList(destination)))); + } + + private LastOperationResponse getLastOperationResponse(String serviceInstanceId, String serviceId, String planId, String operation) throws Exception { + Response response = lastOperationService.getLastOperationStatus(getSecurityContext(), serviceInstanceId, serviceId, planId, operation); + return (LastOperationResponse) response.getEntity(); + } + + + @Test + public void testProvisionTwiceWithDifferentPrameters() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + exceptionGrabber.expect(ConflictException.class); + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, new ProvisionRequest(ServiceType.TOPIC.uuid(), TOPIC_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test + public void testProvisionTwiceWithSameParameters() throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID); + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + Response response = provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Test + public void testDeprovisionNonexistingServiceInstance() throws Exception { + assertThrows(GoneException.class, + () -> provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING)); + } + + @Test + public void testDeprovisionWithoutServiceId() throws Exception { + assertThrows(BadRequestException.class, + () -> provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, null, QUEUE_PLAN_ID_STRING)); + } + + @Test + public void testDeprovisionWithoutPlanId() throws Exception { + assertThrows(BadRequestException.class, + () -> provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, null)); + } + + @Test + public void testDeprovision() throws Exception { + provisionService(SERVICE_INSTANCE_ID); + Response response = provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddresses(), is(Collections.EMPTY_SET)); + } + + @Test + public void testDeprovisionTwice() throws Exception { + provisionService(SERVICE_INSTANCE_ID); + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + + exceptionGrabber.expect(GoneException.class); + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + } + + @Test + public void testDeprovisionGivenMultipleOrganizations() throws Exception { + String serviceId11 = provisionService(randomUUID(), ORGANIZATION_ID, SPACE_ID); + provisionService(randomUUID(), ORGANIZATION_ID, SPACE_ID); + + String organizationId2 = randomUUID(); + String spaceId2 = randomUUID(); + String serviceId21 = provisionService(randomUUID(), organizationId2, spaceId2); + provisionService(randomUUID(), organizationId2, spaceId2); + + Response response = provisioningService.deprovisionService(getSecurityContext(), serviceId21, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddressUuids(), not(hasItem(serviceId21))); + + response = provisioningService.deprovisionService(getSecurityContext(), serviceId11, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddressUuids(), not(hasItem(serviceId11))); + } + + private String randomUUID() { + return UUID.randomUUID().toString(); + } + + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java new file mode 100644 index 0000000000..3532bd8604 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java @@ -0,0 +1,115 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.jsonSchema.types.ObjectSchema; +import io.enmasse.osb.api.bind.BindResponse; +import io.enmasse.osb.api.catalog.*; +import io.enmasse.osb.api.lastoperation.LastOperationResponse; +import io.enmasse.osb.api.lastoperation.LastOperationState; +import io.enmasse.osb.api.provision.ProvisionResponse; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.*; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * + */ +public class SerializationTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testCatalogResponse() throws IOException { + UUID serviceId = UUID.randomUUID(); + Service service = new Service(serviceId, "test-service", "test-description", true); + service.setPlanUpdatable(false); + + UUID planId = UUID.randomUUID(); + Plan plan = new Plan(planId, "test-plan", "test-plan-description", true, true); + plan.setSchemas(new Schemas(new ServiceInstanceSchema(new InputParameters(new ObjectSchema()), null), null)); + service.getPlans().add(plan); + + CatalogResponse response = new CatalogResponse(Collections.singletonList(service)); + + String serialized = mapper.writeValueAsString(response); + Map map = mapper.readValue(serialized, Map.class); + + List services = (List) map.get("services"); + assertThat(services.size(), is(1)); + + Map serviceMap = (Map) services.get(0); + assertThat(serviceMap.get("name"), is("test-service")); + assertThat(serviceMap.get("id"), is(serviceId.toString())); + assertThat(serviceMap.get("description"), is("test-description")); + assertThat(serviceMap.get("tags"), is(Collections.EMPTY_LIST)); + assertThat(serviceMap.get("requires"), is(Collections.EMPTY_LIST)); + assertThat(serviceMap.get("bindable"), is(true)); + assertThat(serviceMap.get("metadata"), notNullValue()); + assertThat(serviceMap.get("dashboard_client"), nullValue()); + assertThat(serviceMap.get("plan_updateable"), is(false)); + + List plans = (List) serviceMap.get("plans"); + assertThat(plans.size(), is(1)); + + Map planMap = (Map) plans.get(0); + assertThat(planMap.get("id"), is(planId.toString())); + assertThat(planMap.get("name"), is("test-plan")); + assertThat(planMap.get("description"), is("test-plan-description")); + assertThat(planMap.get("metadata"), notNullValue()); + assertThat(planMap.get("free"), is(true)); + assertThat(planMap.get("bindable"), is(true)); + + assertThat(planMap.get("schemas"), notNullValue()); // TODO: expand this + } + + @Test + public void testProvisionResponse() throws IOException { + ProvisionResponse response = new ProvisionResponse("dashboard-url", "some-operation"); + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + + assertThat(map.get("dashboard_url"), is("dashboard-url")); + assertThat(map.get("operation"), is("some-operation")); + } + + @Test + public void testBindResponse() throws IOException { + Map credentials = new HashMap<>(); + credentials.put("foo", "bar"); + credentials.put("baz", "qux"); + BindResponse response = new BindResponse(credentials); + response.setRouteServiceUrl("route-service-url"); + response.setSyslogDrainUrl("syslog-drain-url"); + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + assertThat(map.get("route_service_url"), is("route-service-url")); + assertThat(map.get("syslog_drain_url"), is("syslog-drain-url")); + assertThat(map.get("credentials"), is(credentials)); + } + + @Test + public void testLastOperationResponse() throws IOException { + assertLastOperationResponse(new LastOperationResponse(LastOperationState.IN_PROGRESS, "operation-in-progress"), "in progress"); + assertLastOperationResponse(new LastOperationResponse(LastOperationState.SUCCEEDED, "operation-succeeded"), "succeeded"); + assertLastOperationResponse(new LastOperationResponse(LastOperationState.FAILED, "operation-failed"), "failed"); + } + + private void assertLastOperationResponse(LastOperationResponse response, String expectedState) throws IOException { + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + assertThat(map.get("state"), is(expectedState)); + assertThat(map.get("description"), is(response.getDescription())); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java new file mode 100644 index 0000000000..4bf75a589c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ServiceMappingTest { + @Test + public void testRegexp() { + String regexp = ServiceMapping.addressRegexp; + assertTrue("foobar".matches(regexp)); + assertFalse("/foobar".matches(regexp)); + assertFalse("/foobar/".matches(regexp)); + assertFalse("foobar/".matches(regexp)); + assertTrue("foo.bar".matches(regexp)); + assertTrue("foo/bar".matches(regexp)); + assertTrue("foo/bar/baz".matches(regexp)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java new file mode 100644 index 0000000000..3534d52a96 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.controller.standard; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.Status; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.AddressApi; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.metrics.api.Metrics; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.Duration; +import java.util.*; + +import static org.mockito.Mockito.*; + +public class AddressControllerTest { + private Kubernetes mockHelper; + private AddressApi mockApi; + private AddressController controller; + private OpenShiftClient mockClient; + private BrokerSetGenerator mockGenerator; + + @BeforeEach + public void setUp() throws IOException { + mockHelper = mock(Kubernetes.class); + mockGenerator = mock(BrokerSetGenerator.class); + mockApi = mock(AddressApi.class); + mockClient = mock(OpenShiftClient.class); + EventLogger eventLogger = mock(EventLogger.class); + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(); + when(mockHelper.getRouterCluster()).thenReturn(new RouterCluster("qdrouterd", 1, null)); + StandardControllerOptions options = new StandardControllerOptions(); + options.setAddressSpace("me1"); + options.setAddressSpacePlanName("plan1"); + options.setResyncInterval(Duration.ofSeconds(5)); + options.setVersion("1.0"); + controller = new AddressController(options, mockApi, mockHelper, mockGenerator, eventLogger, standardControllerSchema, new Metrics()); + } + + @Test + public void testAddressGarbageCollection() throws Exception { + Address alive = new Address.Builder() + .setName("q1") + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .setStatus(new Status(true).setPhase(Status.Phase.Active)) + .build(); + Address terminating = new Address.Builder() + .setName("q2") + .setAddress("q2") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .setStatus(new Status(false).setPhase(Status.Phase.Terminating)) + .build(); + when(mockHelper.listClusters()).thenReturn(Arrays.asList(new BrokerCluster("broker", new KubernetesList()))); + controller.onUpdate(Arrays.asList(alive, terminating)); + verify(mockApi).deleteAddress(any()); + verify(mockApi).deleteAddress(eq(terminating)); + } + + @Test + public void testDeleteUnusedClusters() throws Exception { + Address alive = new Address.Builder() + .setName("q1") + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .putAnnotation(AnnotationKeys.CLUSTER_ID, "broker") + .setStatus(new Status(true).setPhase(Status.Phase.Active)) + .build(); + + KubernetesList oldList = new KubernetesListBuilder() + .addToConfigMapItems(new ConfigMapBuilder() + .withNewMetadata() + .withName("mymap") + .endMetadata() + .build()) + .build(); + when(mockHelper.listClusters()).thenReturn(Arrays.asList( + new BrokerCluster("broker", new KubernetesList()), + new BrokerCluster("unused", oldList))); + + controller.onUpdate(Arrays.asList(alive)); + + verify(mockHelper).delete(any()); + verify(mockHelper).delete(eq(oldList)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java new file mode 100644 index 0000000000..6402e44998 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java @@ -0,0 +1,546 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.standard; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressResolver; +import io.enmasse.address.model.AddressSpaceResolver; +import io.enmasse.address.model.Status; +import io.enmasse.admin.model.v1.ResourceAllowance; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.EventLogger; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.internal.util.collections.Sets; + +import java.util.*; +import java.util.function.Consumer; + +import static io.enmasse.address.model.Status.Phase.Configuring; +import static io.enmasse.address.model.Status.Phase.Pending; +import static java.util.Collections.singleton; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class AddressProvisionerTest { + private BrokerSetGenerator generator; + private Kubernetes kubernetes; + + @BeforeEach + public void setup() { + generator = mock(BrokerSetGenerator.class); + kubernetes = mock(Kubernetes.class); + } + + private AddressProvisioner createProvisioner() { + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(); + AddressResolver resolver = new AddressResolver(standardControllerSchema.getType()); + AddressSpaceResolver addressSpaceResolver = new AddressSpaceResolver(standardControllerSchema.getSchema()); + EventLogger logger = mock(EventLogger.class); + + return new AddressProvisioner(addressSpaceResolver, resolver, standardControllerSchema.getPlan(), generator, kubernetes, logger, "1234"); + } + + private AddressProvisioner createProvisioner(List resourceAllowances) { + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(resourceAllowances); + AddressResolver resolver = new AddressResolver(standardControllerSchema.getType()); + AddressSpaceResolver addressSpaceResolver = new AddressSpaceResolver(standardControllerSchema.getSchema()); + EventLogger logger = mock(EventLogger.class); + + return new AddressProvisioner(addressSpaceResolver, resolver, standardControllerSchema.getPlan(), generator, kubernetes, logger, "1234"); + } + + @Test + public void testUsageCheck() { + Set

addresses = new HashSet<>(); + addresses.add(new Address.Builder() + .setAddress("a1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-anycast") + .setType("anycast") + .build()); + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(1)); + assertThat(usageMap.get("router").size(), is(1)); + assertEquals(0.2, usageMap.get("router").get("all").getUsed(), 0.01); + + addresses.add(new Address.Builder() + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-queue") + .setType("queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .build()); + + usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(2)); + assertThat(usageMap.get("router").size(), is(1)); + assertThat(usageMap.get("broker").size(), is(1)); + assertEquals(0.4, usageMap.get("router").get("all").getUsed(), 0.01); + assertEquals(0.4, usageMap.get("broker").get("broker-0").getUsed(), 0.01); + + addresses.add(new Address.Builder() + .setAddress("q2") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-queue") + .setType("queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .build()); + + usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(2)); + assertThat(usageMap.get("router").size(), is(1)); + assertThat(usageMap.get("broker").size(), is(1)); + assertEquals(0.6, usageMap.get("router").get("all").getUsed(), 0.01); + assertEquals(0.8, usageMap.get("broker").get("broker-0").getUsed(), 0.01); + } + + @Test + public void testQuotaCheck() { + Set
addresses = new HashSet<>(); + addresses.add(createQueue("q1", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createQueue("q2", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createQueue("q3", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-1")); + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address largeQueue = createQueue("q4", "xlarge-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(largeQueue), Sets.newSet(largeQueue)); + + assertThat(neededMap, is(usageMap)); + assertThat(largeQueue.getStatus().getPhase(), is(Pending)); + + Address smallQueue = createQueue("q4", "small-queue"); + neededMap = provisioner.checkQuota(usageMap, Sets.newSet(smallQueue), Sets.newSet(smallQueue)); + + assertThat(neededMap, is(not(usageMap))); + } + + @Test + public void testQuotaCheckMany() { + Map addresses = new HashMap<>(); + for (int i = 0; i < 200; i++) { + addresses.put("a" + i, createAddress("a" + i, "anycast", "small-anycast")); + } + + + AddressProvisioner provisioner = createProvisioner(); + + Map> usageMap = new HashMap<>(); + Map> provisionMap = provisioner.checkQuota(usageMap, new LinkedHashSet<>(addresses.values()), new LinkedHashSet<>(addresses.values())); + + assertThat(provisionMap.get("router").get("all").getNeeded(), is(1)); + int numConfiguring = 0; + for (Address address : addresses.values()) { + if (address.getStatus().getPhase().equals(Configuring)) { + numConfiguring++; + } + } + assertThat(numConfiguring, is(5)); + } + + @Test + public void testProvisioningColocated() { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + addresses.add(createAddress("q1", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-0")); + + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address queue = createAddress("q2", "queue", "small-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(queue), Sets.newSet(queue)); + + List clusterList = Arrays.asList(new BrokerCluster("broker-pooled-1234", new KubernetesList())); + provisioner.provisionResources(createDeployment(1), clusterList, neededMap, Sets.newSet(queue)); + + assertThat(clusterList.get(0).getResources().getItems().size(), is(0)); + assertTrue(queue.getStatus().getMessages().isEmpty(), queue.getStatus().getMessages().toString()); + assertThat(queue.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertThat(queue.getAnnotations().get(AnnotationKeys.BROKER_ID), is("broker-pooled-1234-0")); + } + + private static RouterCluster createDeployment(int replicas) { + return new RouterCluster("router", replicas, null); + } + + @Test + public void testScalingColocated() { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + addresses.add(createAddress("q1", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createAddress("q2", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address queue = createAddress("q3", "queue", "small-queue"); + Map> provisionMap = provisioner.checkQuota(usageMap, Sets.newSet(queue), Sets.newSet(queue)); + + List clusterList = Arrays.asList(new BrokerCluster("broker-pooled-1234", new KubernetesList())); + provisioner.provisionResources(createDeployment(1), clusterList, provisionMap, Sets.newSet(queue)); + verify(kubernetes).scaleStatefulSet(eq("broker-pooled-1234"), eq(2)); + + assertTrue(queue.getStatus().getMessages().isEmpty(), queue.getStatus().getMessages().toString()); + assertThat(queue.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertThat(queue.getAnnotations().get(AnnotationKeys.BROKER_ID), is("broker-pooled-1234-1")); + } + + @Test + public void testProvisionColocated() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 2))); + + Set
addressSet = Sets.newSet( + createQueue("q9", "pooled-queue-tiny"), + createQueue("q8", "pooled-queue-tiny"), + createQueue("q11", "pooled-queue-tiny"), + createQueue("q12", "pooled-queue-tiny"), + createQueue("q10", "pooled-queue-tiny"), + createQueue("q1", "pooled-queue-large"), + createQueue("q7", "pooled-queue-tiny"), + createQueue("q6", "pooled-queue-small"), + createQueue("q5", "pooled-queue-small"), + createQueue("q4", "pooled-queue-small"), + createQueue("q3", "pooled-queue-small"), + createQueue("q2", "pooled-queue-large")); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(1)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + + List brokerClusters = Arrays.asList( + createCluster("broker-pooled-1234", 2)); + + provisioner.provisionResources(new RouterCluster("router", 1, null), brokerClusters, neededMap, addressSet); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + } + + private BrokerCluster createCluster(String clusterId, int replicas) { + KubernetesListBuilder builder = new KubernetesListBuilder(); + builder.addToStatefulSetItems(new StatefulSetBuilder() + .editOrNewMetadata() + .withName(clusterId) + .endMetadata() + .editOrNewSpec() + .withReplicas(replicas) + .endSpec() + .build()); + return new BrokerCluster(clusterId, builder.build()); + } + + private Address createQueue(String address, String plan) { + return createQueue(address, plan, null); + } + + private Address createQueue(String address, String plan, Consumer> customizeAnnotations) { + return createAddress(address, "queue", plan, customizeAnnotations); + } + + private static Address createAddress(String address, String type, String plan) { + return createAddress(address, type, plan, null); + } + + private static Address createAddress(String address, String type, String plan, Consumer> customizeAnnotations) { + final Address.Builder addressBuilder = new Address.Builder() + .setName(address) + .setAddress(address) + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan(plan) + .setType(type); + + if (customizeAnnotations != null) { + final Map annotations = new HashMap<>(); + customizeAnnotations.accept(annotations); + addressBuilder.setAnnotations(annotations); + } + + return addressBuilder.build(); + } + + private Address createSubscription(String address, String topic, String plan) { + return new Address.Builder() + .setAddress(address) + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan(plan) + .setType("subscription") + .setTopic(topic) + .build(); + } + + + @Test + public void testProvisioningSharded() throws Exception { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 3), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 4))); + Map> usageMap = provisioner.checkUsage(addresses); + + Address q1 = createQueue("q1", "xlarge-queue"); + Address q2 = createQueue("q2", "large-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(q1, q2), Sets.newSet(q1, q2)); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q1)), anyInt(), eq(q1), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q1), new KubernetesList())); + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q2)), anyInt(), eq(q2), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q2), new KubernetesList())); + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, Sets.newSet(q1, q2)); + + assertTrue(q1.getStatus().getMessages().isEmpty(), q1.getStatus().getMessages().toString()); + assertThat(q1.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q1.getAnnotations().get(AnnotationKeys.BROKER_ID)); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(q1)), eq(2), eq(q1), any(), any()); + + assertTrue(q2.getStatus().getMessages().isEmpty(), q2.getStatus().getMessages().toString()); + assertThat(q2.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q2.getAnnotations().get(AnnotationKeys.BROKER_ID)); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(q2)), eq(1), eq(q2), any(), any()); + } + + @Test + public void testProvisioningShardedWithClusterId() throws Exception { + final Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + + final AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 3), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 4))); + final Map> usageMap = provisioner.checkUsage(addresses); + + final String manualClusterId = "foobar"; + + final Address q = createQueue("q1", "xlarge-queue", annotations -> { + annotations.put(AnnotationKeys.CLUSTER_ID, manualClusterId); + }); + + final Map> neededMap = provisioner.checkQuota(usageMap, singleton(q), singleton(q)); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q)), anyInt(), eq(q), any(), any())) + .thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q), new KubernetesList())); + + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, singleton(q)); + + assertTrue(q.getStatus().getMessages().isEmpty(), q.getStatus().getMessages().toString()); + assertThat(q.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q.getAnnotations().get(AnnotationKeys.BROKER_ID)); + + verify(generator) + .generateCluster(eq(manualClusterId), eq(2), eq(q), any(), any()); + } + + @Test + public void testScalingRouter() { + Set
addresses = new HashSet<>(); + for (int i = 0; i < 199; i++) { + addresses.add(createAddress("a" + i, "anycast", "small-anycast")); + } + + + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 0), + new ResourceAllowance("router", 100000), + new ResourceAllowance("aggregate", 100000))); + + Map> usageMap = new HashMap<>(); + Map> neededMap = provisioner.checkQuota(usageMap, addresses, addresses); + + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, addresses); + + verify(kubernetes, atLeast(1)).scaleStatefulSet(eq("router"), eq(40)); + verify(kubernetes, never()).scaleStatefulSet(eq("router"), eq(41)); + } + + @Test + public void testDurableSubscriptionsColocated() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Set
addressSet = Sets.newSet( + createAddress("t1", "topic", "small-topic"), + createAddress("t2", "topic", "small-topic"), + createSubscription("s1", "t1", "small-subscription")); + + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + } + + @Test + public void testDurableSubscriptionsColocatedStaysOnTopicBroker() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Set
addressSet = Sets.newSet( + createAddress("t1", "topic", "small-topic"), + createSubscription("s1", "t1", "small-subscription"), + createSubscription("s2", "t1", "small-subscription"), + createSubscription("s3", "t1", "small-subscription"), + createSubscription("s4", "t1", "small-subscription"), + createSubscription("s5", "t1", "small-subscription"), + createSubscription("s6", "t1", "small-subscription"), + createSubscription("s7", "t1", "small-subscription"), + createSubscription("s8", "t1", "small-subscription"), + createSubscription("s9", "t1", "small-subscription"), + createSubscription("s10", "t1", "small-subscription"), + createSubscription("s11", "t1", "small-subscription"), + createSubscription("s12", "t1", "small-subscription")); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + Set
configured = new HashSet
(); + Set
unConfigured = new HashSet
(); + + + for (Address address : addressSet) { + if (address.getStatus().getPhase().equals(Pending)) { + unConfigured.add(address); + } else if (address.getStatus().getPhase().equals(Configuring)) { + configured.add(address); + } + } + assertEquals(2, unConfigured.size()); + assertEquals(11, configured.size(), "contains topic + 10 subscriptions"); + Iterator
unconfiguredIterator = unConfigured.iterator(); + assertFalse(configured.contains(unconfiguredIterator.next())); + assertFalse(configured.contains(unconfiguredIterator.next())); + } + + @Test + public void testDurableSubscriptionsSharded() throws Exception { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Address t1 = createAddress("t1", "topic", "xlarge-topic"); + Address t2 = createAddress("t2", "topic", "xlarge-topic"); + Address s1 = createSubscription("s1", "t1", "small-subscription"); + Set
addressSet = Sets.newSet( + t1, + t2, + s1); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(3)); + + List brokerClusters = new ArrayList(Arrays.asList(createCluster("broker", 1))); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(t1)), anyInt(), eq(t1), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(t1), new KubernetesList())); + when(generator.generateCluster(eq(provisioner.getShardedClusterId(t2)), anyInt(), eq(t2), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(t2), new KubernetesList())); + provisioner.provisionResources(createDeployment(1), brokerClusters, neededMap, addressSet); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(t2)), eq(1), eq(t2), any(), any()); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(t1)), eq(1), eq(t1), any(), any()); + } + + @Test + public void testDurableSubscriptionsShardedStaysOnTopicBroker() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Address t1 = createAddress("t1", "topic", "small-topic"); + Address t2 = createAddress("t2", "topic", "small-topic"); + + Set
addressSet = Sets.newSet( + t1, + createSubscription("s1", "t1", "small-subscription"), + createSubscription("s2", "t1", "small-subscription"), + createSubscription("s3", "t1", "small-subscription"), + createSubscription("s4", "t1", "small-subscription"), + createSubscription("s5", "t1", "small-subscription"), + createSubscription("s6", "t1", "small-subscription"), + createSubscription("s7", "t1", "small-subscription"), + createSubscription("s8", "t1", "small-subscription"), + createSubscription("s9", "t1", "small-subscription"), + createSubscription("s10", "t1", "small-subscription"), + createSubscription("s11", "t1", "small-subscription"), + createSubscription("s12", "t1", "small-subscription"), + t2); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + Set
configured = new HashSet
(); + Set
unConfigured = new HashSet
(); + + for (Address address : addressSet) { + if (address.getStatus().getPhase().equals(Pending)) { + unConfigured.add(address); + } else if (address.getStatus().getPhase().equals(Configuring)) { + configured.add(address); + } + } + assertEquals(2, unConfigured.size()); + assertTrue(configured.contains(t1)); + assertTrue(configured.contains(t2)); + assertEquals(12, configured.size(), "contains 2 topic + 10 subscriptions"); + Iterator
unconfiguredIterator = unConfigured.iterator(); + assertFalse(configured.contains(unconfiguredIterator.next())); + assertFalse(configured.contains(unconfiguredIterator.next())); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java new file mode 100644 index 0000000000..f0353a6573 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.controller.standard; + +import io.enmasse.address.model.Address; +import io.enmasse.admin.model.v1.StandardInfraConfig; +import io.enmasse.config.AnnotationKeys; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.openshift.client.ParameterValue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.List; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + +public class TemplateBrokerSetGeneratorTest { + private Kubernetes kubernetes; + private StandardControllerSchema standardControllerSchema; + private BrokerSetGenerator generator; + + @BeforeEach + public void setUp() { + kubernetes = mock(Kubernetes.class); + + standardControllerSchema = new StandardControllerSchema(); + generator = new TemplateBrokerSetGenerator(kubernetes, new StandardControllerOptions()); + } + + @Test + public void testDirect() throws Exception { + Address dest = createAddress("foo_bar_FOO", "anycast"); + ArgumentCaptor captor = ArgumentCaptor.forClass(ParameterValue.class); + BrokerCluster clusterList = generateCluster(dest, captor); + List resources = clusterList.getResources().getItems(); + assertThat(resources.size(), is(1)); + List parameters = captor.getAllValues(); + assertThat(parameters.size(), is(13)); + } + + @Test + public void testStoreAndForward() throws Exception { + Address dest = createAddress("foo.bar", "queue"); + ArgumentCaptor captor = ArgumentCaptor.forClass(ParameterValue.class); + BrokerCluster clusterList = generateCluster(dest, captor); + List resources = clusterList.getResources().getItems(); + assertThat(resources.size(), is(1)); + for (HasMetadata resource : resources) { + Map annotations = resource.getMetadata().getAnnotations(); + assertNotNull(annotations.get(AnnotationKeys.CLUSTER_ID)); + assertThat(annotations.get(AnnotationKeys.CLUSTER_ID), is(dest.getName())); + } + List parameters = captor.getAllValues(); + assertThat(parameters.size(), is(13)); + } + + private Address createAddress(String address, String type) { + return new Address.Builder() + .setName(address) + .setAddress(address) + .setAddressSpace("myinstance") + .setType(type) + .setPlan("plan1") + .build(); + } + + private BrokerCluster generateCluster(Address address, ArgumentCaptor captor) throws Exception { + when(kubernetes.processTemplate(anyString(), captor.capture())).thenReturn(new KubernetesListBuilder().addNewConfigMapItem().withNewMetadata().withName("testmap").endMetadata().endConfigMapItem().build()); + + return generator.generateCluster(address.getName(), 1, address, null, + standardControllerSchema.getSchema().findAddressSpaceType("standard").map(type -> (StandardInfraConfig) type.findInfraConfig("cfg1").orElse(null)).orElse(null)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java new file mode 100644 index 0000000000..f76d26dc38 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-5e0e683531b756ac62a497cca15ddb7211a34e24/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java @@ -0,0 +1,120 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.forwarder; + +import enmasse.discovery.Host; +import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.junit5.VertxExtension; +import io.vertx.junit5.VertxTestContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +@ExtendWith(VertxExtension.class) +public class ForwarderControllerTest { + private static final Logger log = LoggerFactory.getLogger(ForwarderControllerTest.class.getName()); + private Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(10)); + private String localHost = "127.0.0.1"; + private final String address = "mytopic"; + private TestBroker serverA; + private TestBroker serverB; + private TestBroker serverC; + + @BeforeEach + public void setup(VertxTestContext testContext) throws Exception { + serverA = new TestBroker(1, address); + serverB = new TestBroker(2, address); + serverC = new TestBroker(3, address); + vertx.deployVerticle(serverA, testContext.succeeding(arg -> testContext.completeNow())); + vertx.deployVerticle(serverB, testContext.succeeding(arg -> testContext.completeNow())); + vertx.deployVerticle(serverC, testContext.succeeding(arg -> testContext.completeNow())); + } + + @AfterEach + public void teardown() throws Exception { + vertx.close(); + } + + @Test + public void testBrokerReplicator() throws InterruptedException, TimeoutException, ExecutionException { + Host hostA = new Host(localHost, Collections.singletonMap("amqp", serverA.getPort())); + Host hostB = new Host(localHost, Collections.singletonMap("amqp", serverB.getPort())); + Host hostC = new Host(localHost, Collections.singletonMap("amqp", serverC.getPort())); + + ForwarderController replicator = new ForwarderController(hostA, address, null); + CountDownLatch latch = new CountDownLatch(1); + vertx.deployVerticle(replicator, id -> latch.countDown()); + latch.await(1, TimeUnit.MINUTES); + + Set hosts = new LinkedHashSet<>(); + hosts.add(hostB); + replicator.hostsChanged(hosts); + Thread.sleep(5000); + hosts.add(hostC); + replicator.hostsChanged(hosts); + + long timeout = 60_000; + waitForConnections(serverA, 2, timeout); + waitForConnections(serverB, 1, timeout); + waitForConnections(serverC, 1, timeout); + + CompletableFuture> resultB = serverB.recvMessages(2, 60, TimeUnit.SECONDS); + CompletableFuture> resultC = serverC.recvMessages(2, 60, TimeUnit.SECONDS); + + serverA.sendMessage("Hello 1", 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 2", 60, TimeUnit.SECONDS); + + assertMessages(resultB.get(120, TimeUnit.SECONDS), "Hello 1", "Hello 2"); + assertMessages(resultC.get(120, TimeUnit.SECONDS), "Hello 1", "Hello 2"); + + hosts.remove(hostB); + replicator.hostsChanged(hosts); + + waitForConnections(serverA, 2, timeout); + waitForConnections(serverB, 0, timeout); + waitForConnections(serverC, 1, timeout); + + resultC = serverC.recvMessages(2, 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 3", 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 4", 60, TimeUnit.SECONDS); + assertMessages(resultC.get(120, TimeUnit.SECONDS), "Hello 3", "Hello 4"); + } + + private void assertMessages(List result, String... messages) { + assertThat(messages.length, is(2)); + for (String message : messages) { + assertThat(result, hasItem(message)); + } + } + + private static void waitForConnections(TestBroker server, int num, long timeout) throws InterruptedException { + long endTime = System.currentTimeMillis() + timeout; + while (System.currentTimeMillis() < endTime) { + log.info("Num connected on " + server.getId() + " is : " + server.numConnected()); + if (server.numConnected() >= num) { + break; + } + Thread.sleep(1000); + } + assertTrue(server.numConnected() >= num); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java new file mode 100644 index 0000000000..03214da0bc --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-model-lib/src/test/java/io/enmasse/address/model/AuthenticationServiceTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.address.model; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +/** + * Unit tests for {@link AuthenticationService} + */ +public class AuthenticationServiceTest { + + /** + * Test if two empty services are equal + */ + @Test + public void testEqualsEmpty() { + assertEquality(true, + new AuthenticationService.Builder().build(), + new AuthenticationService.Builder().build()); + } + + /** + * Test if two services are equal having the same type + */ + @Test + public void testEqualsSameType() { + assertEquality(true, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build()); + } + + /** + * Test if two services are not equal having the different types + */ + @Test + public void testNonEqualsDifferentType() { + assertEquality(false, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.NONE) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .build()); + } + + /** + * Test if two services are equal having the same type and the same details + */ + @Test + public void testEqualsSameTypeSameDetails() { + final Map details1 = new HashMap<>(); + final Map details2 = new HashMap<>(); + + for (final Map map : Arrays.asList(details1, details2)) { + map.put("string", "foo"); + map.put("int", 1); + map.put("bool", true); + } + + assertEquality(true, + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(details1) + .build(), + new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(details2) + .build()); + } + + /** + * Test for equality + * + * @param isEqual are values to be expected equal? + * @param v1 value 1 + * @param v2 value 2 + */ + protected void assertEquality(final boolean isEqual, final Object v1, final Object v2) { + assertEquals(isEqual, v1.equals(v2)); + assertEquals(isEqual, v2.equals(v1)); + assertEquals(isEqual, v1.hashCode() == v2.hashCode()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java new file mode 100644 index 0000000000..a8a47a8838 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/ControllerChainTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceStatus; +import io.enmasse.controller.common.Kubernetes; +import io.enmasse.metrics.api.Metric; +import io.enmasse.metrics.api.Metrics; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import org.junit.Before; +import org.junit.Test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +public class ControllerChainTest { + private TestAddressSpaceApi testApi; + private Kubernetes kubernetes; + + @Before + public void setup() { + kubernetes = mock(Kubernetes.class); + testApi = new TestAddressSpaceApi(); + + when(kubernetes.getNamespace()).thenReturn("myspace"); + } + + @Test + public void testController() throws Exception { + EventLogger testLogger = mock(EventLogger.class); + Metrics metrics = new Metrics(); + ControllerChain controllerChain = new ControllerChain(kubernetes, testApi, new TestSchemaProvider(), testLogger, metrics, "1.0", Duration.ofSeconds(5), Duration.ofSeconds(5)); + Controller mockController = mock(Controller.class); + controllerChain.addController(mockController); + + AddressSpace a1 = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .build(); + + AddressSpace a2 = new AddressSpace.Builder() + .setName("myspace2") + .setType("type1") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .build(); + + when(mockController.handle(eq(a1))).thenReturn(a1); + when(mockController.handle(eq(a2))).thenReturn(a2); + + controllerChain.onUpdate(Arrays.asList(a1, a2)); + + verify(mockController, times(2)).handle(any()); + verify(mockController).handle(eq(a1)); + verify(mockController).handle(eq(a2)); + + List metricList = metrics.snapshot(); + assertThat(metricList.size(), is(5)); + assertTrue(a1.getStatus().isReady()); + assertTrue(a2.getStatus().isReady()); + } +} + diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java new file mode 100644 index 0000000000..f2fb162f82 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/CreateControllerTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.controller.common.Kubernetes; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.k8s.api.SchemaProvider; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.KubernetesList; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.util.Arrays; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +public class CreateControllerTest { + + @Test + public void testAddressSpaceCreate() throws Exception { + Kubernetes kubernetes = mock(Kubernetes.class); + when(kubernetes.getNamespace()).thenReturn("otherspace"); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setUid(UUID.randomUUID().toString()) + .setNamespace("mynamespace") + .setType("type1") + .setPlan("myplan") + .build(); + + + EventLogger eventLogger = mock(EventLogger.class); + InfraResourceFactory mockResourceFactory = mock(InfraResourceFactory.class); + when(mockResourceFactory.createInfraResources(eq(addressSpace), any())).thenReturn(Arrays.asList(new ConfigMapBuilder() + .editOrNewMetadata() + .withName("mymap") + .endMetadata() + .build())); + + SchemaProvider testSchema = new TestSchemaProvider(); + CreateController createController = new CreateController(kubernetes, testSchema, mockResourceFactory, eventLogger, null, "1.0", new TestAddressSpaceApi()); + + createController.handle(addressSpace); + + ArgumentCaptor resourceCaptor = ArgumentCaptor.forClass(KubernetesList.class); + verify(kubernetes).create(resourceCaptor.capture()); + KubernetesList value = resourceCaptor.getValue(); + assertThat(value.getItems().size(), is(1)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java new file mode 100644 index 0000000000..e0609ed419 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/EndpointControllerTest.java @@ -0,0 +1,183 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.address.model.ExposeSpec; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.util.Arrays; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +public class EndpointControllerTest { + + private OpenShiftClient client; + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + + @Before + public void setup() { + client = openShiftServer.getOpenshiftClient(); + } + + @Test + public void testRoutesNotCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, false); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertNull(newspace.getStatus().getEndpointStatuses().get(0).getExternalHost()); + assertTrue(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().isEmpty()); + } + + @Test + public void testExternalLoadBalancerCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setExposeSpec(new ExposeSpec.Builder() + .setType(ExposeSpec.ExposeType.loadbalancer) + .setLoadBalancerPorts(Arrays.asList("amqps")) + .build()) + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, true); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().size(), is(1)); + } + + @Test + public void testExternalRouteCreated() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .appendEndpoint(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setExposeSpec(new ExposeSpec.Builder() + .setType(ExposeSpec.ExposeType.route) + .setRouteHost("host1.example.com") + .setRouteServicePort("amqps") + .setRouteTlsTermination(ExposeSpec.TlsTermination.passthrough) + .build()) + .build()) + .setType("type1") + .setPlan("myplan") + .build(); + + + Service service = new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToAnnotations(AnnotationKeys.SERVICE_PORT_PREFIX + "amqps", "5671") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .addNewPort() + .withName("amqps") + .withPort(1234) + .withNewTargetPort("amqps") + .endPort() + .addToSelector("component", "router") + .endSpec() + .build(); + + client.services().create(service); + + EndpointController controller = new EndpointController(client, true); + + AddressSpace newspace = controller.handle(addressSpace); + + assertThat(newspace.getStatus().getEndpointStatuses().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getName(), is("myendpoint")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServiceHost(), is("messaging-1234.test.svc")); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getServicePorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().size(), is(1)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalPorts().get("amqps"), is(443)); + assertThat(newspace.getStatus().getEndpointStatuses().get(0).getExternalHost(), is("host1.example.com")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java new file mode 100644 index 0000000000..cfffe2e70c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/NetworkPolicyControllerTest.java @@ -0,0 +1,203 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.KubeUtil; +import io.enmasse.admin.model.v1.*; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.networking.NetworkPolicyEgressRuleBuilder; +import io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRuleBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.util.Collections; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class NetworkPolicyControllerTest { + private static final ObjectMapper mapper = new ObjectMapper(); + private OpenShiftClient client; + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + @Before + public void setup() { + client = openShiftServer.getOpenshiftClient(); + } + + @Test + public void testCreateFromInfraConfig() throws Exception { + InfraConfig infraConfig = createTestInfra(createTestPolicy("my", "label")); + AddressSpace addressSpace = createTestSpace(infraConfig, null); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testCreateFromAddressSpaceConfig() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testAddressSpaceOverridesInfra() throws Exception { + InfraConfig infraConfig = createTestInfra(createTestPolicy("my", "label")); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "overridden")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertEquals("enmasse", networkPolicy.getMetadata().getLabels().get(LabelKeys.APP)); + assertEquals("1234", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_UUID)); + assertEquals("type1", networkPolicy.getMetadata().getLabels().get(LabelKeys.INFRA_TYPE)); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("overridden", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + } + + @Test + public void testUpdatesWhenChanged() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, + createTestPolicy("my", "label1")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label1", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label2")); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label2", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label2", "other", "label3")); + controller.handle(addressSpace); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Egress")); + assertEquals("label2", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + assertEquals("label3", networkPolicy.getSpec().getEgress().get(0).getTo().get(0).getPodSelector().getMatchLabels().get("other")); + } + + @Test + public void testDeletesWhenRemoved() throws Exception { + InfraConfig infraConfig = createTestInfra(null); + AddressSpace addressSpace = createTestSpace(infraConfig, createTestPolicy("my", "label")); + + NetworkPolicyController controller = new NetworkPolicyController(client, new TestSchemaProvider()); + controller.handle(addressSpace); + + assertEquals(1, client.network().networkPolicies().list().getItems().size()); + io.fabric8.kubernetes.api.model.networking.NetworkPolicy networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNotNull(networkPolicy); + assertThat(networkPolicy.getSpec().getPolicyTypes(), hasItem("Ingress")); + assertEquals("label", networkPolicy.getSpec().getIngress().get(0).getFrom().get(0).getPodSelector().getMatchLabels().get("my")); + + addressSpace = createTestSpace(infraConfig, null); + controller.handle(addressSpace); + assertEquals(0, client.network().networkPolicies().list().getItems().size()); + networkPolicy = client.network().networkPolicies().withName(KubeUtil.getNetworkPolicyName(addressSpace)).get(); + assertNull(networkPolicy); + } + + private NetworkPolicy createTestPolicy(String labelKey, String labelValue) { + return new NetworkPolicyBuilder() + .withIngress(Collections.singletonList(new NetworkPolicyIngressRuleBuilder() + .addNewFrom() + .withNewPodSelector() + .addToMatchLabels(labelKey, labelValue) + .endPodSelector() + .endFrom() + .build())) + .build(); + } + + private NetworkPolicy createTestPolicy(String ingressLabelKey, String ingressLabelValue, String egressLabelKey, String egressLabelValue) { + return new NetworkPolicyBuilder() + .withIngress(Collections.singletonList(new NetworkPolicyIngressRuleBuilder() + .addNewFrom() + .withNewPodSelector() + .addToMatchLabels(ingressLabelKey, ingressLabelValue) + .endPodSelector() + .endFrom() + .build())) + .withEgress(Collections.singletonList(new NetworkPolicyEgressRuleBuilder() + .addNewTo() + .withNewPodSelector() + .addToMatchLabels(egressLabelKey, egressLabelValue) + .endPodSelector() + .endTo() + .build())) + .build(); + } + + private InfraConfig createTestInfra(NetworkPolicy networkPolicy) throws JsonProcessingException { + return new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("test") + .build()) + .withNewSpec() + .withNetworkPolicy(networkPolicy) + .endSpec() + .build(); + } + + private AddressSpace createTestSpace(InfraConfig infraConfig, NetworkPolicy networkPolicy) throws JsonProcessingException { + return new AddressSpace.Builder() + .setName("myspace") + .setNamespace("ns") + .setType("type1") + .setPlan("plan1") + .setNetworkPolicy(networkPolicy) + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .putAnnotation(AnnotationKeys.APPLIED_INFRA_CONFIG, mapper.writeValueAsString(infraConfig)) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java new file mode 100644 index 0000000000..f881d6ffad --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/StatusControllerTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceStatus; +import io.enmasse.controller.common.Kubernetes; +import io.fabric8.kubernetes.api.model.apps.Deployment; +import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder; +import org.junit.Test; + +import java.util.Collections; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class StatusControllerTest { + + @Test + public void testStatusControllerSetsNotReady() throws Exception { + InfraResourceFactory infraResourceFactory = mock(InfraResourceFactory.class); + Kubernetes kubernetes = mock(Kubernetes.class); + + Deployment deployment = new DeploymentBuilder() + .withNewMetadata() + .withName("mydepl1") + .endMetadata() + .withNewStatus() + .withUnavailableReplicas(1) + .withAvailableReplicas(0) + .endStatus() + .build(); + + when(kubernetes.getReadyDeployments()).thenReturn(Collections.emptySet()); + + StatusController controller = new StatusController(kubernetes, new TestSchemaProvider(), infraResourceFactory, null); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .build(); + + when(infraResourceFactory.createInfraResources(eq(addressSpace), any())).thenReturn(Collections.singletonList(deployment)); + + assertFalse(addressSpace.getStatus().isReady()); + controller.handle(addressSpace); + assertFalse(addressSpace.getStatus().isReady()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java new file mode 100644 index 0000000000..1d4589101e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/TemplateInfraResourceFactoryTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AuthenticationServiceResolver; +import io.enmasse.address.model.CertSpec; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.admin.model.v1.*; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.controller.common.KubernetesHelper; +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.HasMetadata; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.io.File; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class TemplateInfraResourceFactoryTest { + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + private TemplateInfraResourceFactory resourceFactory; + private NamespacedOpenShiftClient client; + + @Before + public void setup() { + client = openShiftServer.getOpenshiftClient(); + client.secrets().createNew().editOrNewMetadata().withName("certs").endMetadata().addToData("tls.crt", "cert").done(); + AuthenticationServiceResolver authServiceResolver = mock(AuthenticationServiceResolver.class); + when(authServiceResolver.getHost(any())).thenReturn("example.com"); + when(authServiceResolver.getPort(any())).thenReturn(5671); + when(authServiceResolver.getCaSecretName(any())).thenReturn(Optional.of("certs")); + resourceFactory = new TemplateInfraResourceFactory( + new KubernetesHelper("test", + client, + client.getConfiguration().getOauthToken(), + new File("src/test/resources/templates"), + true), + a -> authServiceResolver, + true); + } + + @Test + public void testGenerateStandard() { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("myproject") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .setType("standard") + .setPlan("standard-unlimited") + .appendEndpoint(new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .setCertSpec(new CertSpec("selfsigned", "messaging-secret", null, null)) + .build()) + .appendEndpoint(new EndpointSpec.Builder() + .setName("console") + .setService("console") + .setCertSpec(new CertSpec("selfsigned", "console-secret", null, null)) + .build()) + .build(); + + StandardInfraConfig infraConfig = new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("test") + .build()) + .withNewSpec() + .withVersion("master") + .withAdmin(new StandardInfraConfigSpecAdminBuilder() + .withNewResources("2Mi") + .build()) + .withBroker(new StandardInfraConfigSpecBrokerBuilder() + .withNewResources("2Mi", "1Gi") + .withAddressFullPolicy("FAIL") + .build()) + .withRouter(new StandardInfraConfigSpecRouterBuilder() + .withNewResources("2Mi") + .withLinkCapacity(22) + .build()) + .endSpec() + .build(); + List items = resourceFactory.createInfraResources(addressSpace, infraConfig); + assertEquals(1, items.size()); + ConfigMap map = findItem("ConfigMap", "mymap", items); + assertEquals("FAIL", map.getData().get("key")); + } + + private T findItem(String kind, String name, List items) { + T found = null; + for (HasMetadata item : items) { + if (kind.equals(item.getKind()) && name.equals(item.getMetadata().getName())) { + found = (T) item; + break; + } + } + assertNotNull(found); + return found; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java new file mode 100644 index 0000000000..43cb3d000c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/CertBundleCertProviderTest.java @@ -0,0 +1,102 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +public class CertBundleCertProviderTest { + @Rule + public OpenShiftServer server = new OpenShiftServer(true, true); + + private OpenShiftClient client; + private CertProvider certProvider; + + @Before + public void setup() { + client = server.getOpenshiftClient(); + + certProvider = new CertBundleCertProvider(client); + } + + @Test + public void testProvideCertNoService() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .build(); + + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + } + + @Test + public void testProvideCert() { + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("aGVsbG8=") + .setTlsCert("d29ybGQ=") + .build(); + + space.validate(); + + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNotNull(cert); + assertThat(cert.getData().get("tls.key"), is(spec.getTlsKey())); + assertThat(cert.getData().get("tls.crt"), is(spec.getTlsCert())); + } + + @Test(expected = IllegalArgumentException.class) + public void testValidateBadKey() { + new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("/%^$lkg") + .setTlsCert("d29ybGQ=") + .build() + .validate(); + } + + @Test(expected = IllegalArgumentException.class) + public void testValidateBadCert() { + new CertSpec.Builder() + .setProvider("certBundle") + .setSecretName("mycerts") + .setTlsKey("d29ybGQ=") + .setTlsCert("/%^$lkg") + .build() + .validate(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java new file mode 100644 index 0000000000..dab7596ac2 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/OpenShiftCertProviderTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.config.LabelKeys; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class OpenShiftCertProviderTest { + @Rule + public OpenShiftServer server = new OpenShiftServer(true, true); + + private OpenShiftClient client; + private CertProvider certProvider; + + @Before + public void setup() { + client = server.getOpenshiftClient(); + + certProvider = new OpenshiftCertProvider(client); + } + + @Test + public void testProvideCertNoService() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + CertSpec spec = new CertSpec.Builder().setProvider("openshift").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + } + + @Test + public void testProvideCert() { + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .putAnnotation(AnnotationKeys.INFRA_UUID, "1234") + .build(); + + client.services().inNamespace("test").create(new ServiceBuilder() + .editOrNewMetadata() + .withName("messaging-1234") + .addToLabels(LabelKeys.INFRA_UUID, "1234") + .endMetadata() + .editOrNewSpec() + .endSpec() + .build()); + + CertSpec spec = new CertSpec.Builder().setProvider("openshift").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertNull(cert); + + Service service = client.services().inNamespace("test").withName("messaging-1234").get(); + assertNotNull(service); + // Should verify that annotation is set, but bug in mock-server seems to not set it + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java new file mode 100644 index 0000000000..9f6e600fa8 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/address-space-controller/src/test/java/io/enmasse/controller/auth/WildcardCertProviderTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.auth; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.CertSpec; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.server.mock.KubernetesServer; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +public class WildcardCertProviderTest { + @Rule + public KubernetesServer server = new KubernetesServer(true, true); + + private KubernetesClient client; + private CertProvider certProvider; + + @Before + public void setup() { + client = server.getClient(); + String wildcardCert = "wildcardcert"; + + certProvider = new WildcardCertProvider(client, wildcardCert); + } + + @Test(expected = IllegalStateException.class) + public void testUnknownWildcardSecret() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setType("standard") + .setPlan("myplan") + .build(); + CertSpec spec = new CertSpec.Builder().setProvider("wildcard").setSecretName("mycerts").build(); + + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + } + + @Test + public void testProvideCert() { + + AddressSpace space = new AddressSpace.Builder() + .setName("myspace") + .setPlan("myplan") + .setType("standard") + .build(); + + client.secrets().create(new SecretBuilder() + .editOrNewMetadata() + .withName("wildcardcert") + .endMetadata() + .addToData("tls.key", "mykey") + .addToData("tls.crt", "myvalue") + .build()); + + CertSpec spec = new CertSpec.Builder().setProvider("wildcard").setSecretName("mycerts").build(); + certProvider.provideCert(space, new EndpointInfo("messaging", spec)); + + Secret cert = client.secrets().withName("mycerts").get(); + assertThat(cert.getData().get("tls.key"), is("mykey")); + assertThat(cert.getData().get("tls.crt"), is("myvalue")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java new file mode 100644 index 0000000000..61800c9a0a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ArtemisTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.amqp; + +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ArtemisTest { + + private static class TestClient implements SyncRequestClient { + + Message response; + Message request; + + @Override + public void connect(String host, int port, ProtonClientOptions clientOptions, String address, CompletableFuture connectedPromise) { + + } + + @Override + public String getRemoteContainer() { + return null; + } + + @Override + public String getReplyTo() { + return "tome"; + } + + @Override + public void close() { + + } + + @Override + public Message request(Message message, long timeout, TimeUnit timeUnit) { + request = message; + return response; + } + } + + @Test + public void testManagement() throws InterruptedException, ExecutionException, TimeoutException { + TestClient testClient = new TestClient(); + try (Artemis artemis = new Artemis(testClient)) { + + testClient.response = Proton.message(); + artemis.deployQueue("queue1", "queue1"); + String body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[\"queue1\",\"queue1\",null,false]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("deployQueue", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + artemis.deployQueue("queue2", "queue2"); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[\"queue2\",\"queue2\",null,false]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("deployQueue", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + testClient.response = Proton.message(); + testClient.response.setBody(new AmqpValue("[[\"q1\"],[\"q2\"],[\"tome\"]]")); + long numQueues = artemis.getNumQueues(); + assertEquals(2, numQueues); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[]", body); + assertEquals("broker", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("getQueueNames", testClient.request.getApplicationProperties().getValue().get("_AMQ_OperationName")); + + testClient.response = Proton.message(); + testClient.response.setBody(new AmqpValue("[42]")); + long messageCount = artemis.getQueueMessageCount("q1"); + assertEquals(42, messageCount); + body = (String)((AmqpValue)testClient.request.getBody()).getValue(); + assertEquals("[]", body); + assertEquals("queue.q1", testClient.request.getApplicationProperties().getValue().get("_AMQ_ResourceName")); + assertEquals("messageCount", testClient.request.getApplicationProperties().getValue().get("_AMQ_Attribute")); + + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java new file mode 100644 index 0000000000..e3310cb678 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/BlockingClientTest.java @@ -0,0 +1,123 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.amqp; + +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonSession; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + +public class BlockingClientTest { + private static final Logger log = LoggerFactory.getLogger(BlockingClientTest.class); + + private Vertx vertx; + private ProtonServer server; + private BlockingQueue inbox; + private BlockingQueue outbox; + private int actualPort; + + @Before + public void setup() throws Exception { + vertx = Vertx.vertx(); + server = ProtonServer.create(vertx); + inbox = new LinkedBlockingDeque<>(); + outbox = new LinkedBlockingDeque<>(); + CountDownLatch latch = new CountDownLatch(1); + server.connectHandler(conn -> { + conn.closeHandler(c -> { + conn.close(); + conn.disconnect(); + }); + conn.disconnectHandler(c -> { + conn.disconnect(); + }).open(); + + conn.sessionOpenHandler(ProtonSession::open); + + conn.receiverOpenHandler(receiver -> { + log.debug("Receiver open"); + receiver.setTarget(receiver.getRemoteTarget()); + receiver.handler((delivery, message) -> { + inbox.add(message); + }); + receiver.open(); + }); + + conn.senderOpenHandler(sender -> { + vertx.setPeriodic(100, id -> { + try { + Message m = outbox.poll(0, TimeUnit.SECONDS); + if (m != null) { + sender.send(m); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + // Try again later + } + }); + sender.open(); + }); + }).listen(0, res -> latch.countDown()); + latch.await(); + actualPort = server.actualPort(); + log.debug("Using port {}", actualPort); + } + + @Test + public void testSend() throws Exception { + try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) { + Message m = Message.Factory.create(); + m.setAddress("testsend"); + m.setBody(new AmqpValue("hello there")); + client.send("testsend", Arrays.asList(m), 1, TimeUnit.MINUTES); + + Message received = inbox.poll(1, TimeUnit.MINUTES); + assertNotNull(received); + assertThat(received.getMessageId(), is(m.getMessageId())); + assertThat(((AmqpValue)received.getBody()).getValue(), is("hello there")); + } + } + + @Test + public void testReceive() throws Exception { + try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) { + Message m = Message.Factory.create(); + m.setAddress("testreceive"); + m.setBody(new AmqpValue("hello there")); + outbox.put(m); + + List messages = client.recv("testsend", 1, 1, TimeUnit.MINUTES); + assertThat(messages.size(), is(1)); + + Message received = messages.get(0); + assertNotNull(received); + assertThat(received.getMessageId(), is(m.getMessageId())); + assertThat(((AmqpValue)received.getBody()).getValue(), is("hello there")); + } + } + + @After + public void teardown() { + server.close(); + vertx.close(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java new file mode 100644 index 0000000000..5637d9cb6b --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/amqp-utils/src/test/java/io/enmasse/amqp/ProtonRequestClientTest.java @@ -0,0 +1,98 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.amqp; + +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonSender; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonSession; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + +public class ProtonRequestClientTest { + private Vertx vertx; + private ProtonServer server; + + @Before + public void setup() throws InterruptedException { + vertx = Vertx.vertx(); + server = ProtonServer.create(vertx); + CountDownLatch latch = new CountDownLatch(1); + CompletableFuture futureSender = new CompletableFuture<>(); + server.connectHandler(conn -> { + conn.closeHandler(c -> { + conn.close(); + conn.disconnect(); + }); + conn.disconnectHandler(c -> { + conn.disconnect(); + }).open(); + + conn.sessionOpenHandler(ProtonSession::open); + + conn.receiverOpenHandler(receiver -> { + System.out.println("Receiver open"); + receiver.setTarget(receiver.getRemoteTarget()); + receiver.handler((delivery, message) -> { + Message response = Message.Factory.create(); + response.setAddress(message.getAddress()); + response.setBody(new AmqpValue(true)); + response.setCorrelationId(message.getCorrelationId()); + response.setReplyTo(message.getReplyTo()); + try { + futureSender.get().send(response); + } catch (Exception e) { + e.printStackTrace(); + } + }); + receiver.open(); + }); + + conn.senderOpenHandler(sender -> { + sender.setSource(sender.getRemoteSource()); + sender.open(); + futureSender.complete(sender); + }); + }).listen(12347, res -> { + latch.countDown(); + }); + latch.await(); + } + + @After + public void teardown() { + server.close(); + vertx.close(); + } + + @Test + public void testRequest() throws Exception { + try (ProtonRequestClient client = new ProtonRequestClient(Vertx.vertx(), "test-client")) { + CompletableFuture future = new CompletableFuture<>(); + client.connect("127.0.0.1", 12347, future); + future.get(10, TimeUnit.SECONDS); + Message request = Message.Factory.create(); + request.setAddress("health-check"); + request.setBody(new AmqpValue("[{\"name\":\"myqueue\",\"store_and_forward\":true,\"multicast\":false}]")); + request.setSubject("health-check"); + Message response = client.request(request, 10, TimeUnit.SECONDS); + assertTrue((Boolean) ((AmqpValue) response.getBody()).getValue()); + + future = new CompletableFuture<>(); + client.connect("127.0.0.1", 12347, future); + future.get(10, TimeUnit.SECONDS); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java new file mode 100644 index 0000000000..c1e310c18e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/auth/AuthInterceptorTest.java @@ -0,0 +1,192 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.auth; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.vertx.core.http.HttpConnection; +import io.vertx.core.http.HttpServerRequest; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.function.Predicate; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.core.UriInfo; + +public class AuthInterceptorTest { + + private File tokenFile; + private AuthInterceptor handler; + private ContainerRequestContext mockRequestContext; + private UriInfo mockUriInfo; + private AuthApi mockAuthApi; + + @Before + public void setUp() throws IOException { + tokenFile = File.createTempFile("token", ""); + mockAuthApi = mock(AuthApi.class); + when(mockAuthApi.getNamespace()).thenReturn("myspace"); + handler = new AuthInterceptor(mockAuthApi, new Predicate() { + @Override + public boolean test(String s) { + return "/healthz".equals(s); + } + }); + mockRequestContext = mock(ContainerRequestContext.class); + + mockUriInfo = mock(UriInfo.class); + when(mockUriInfo.getAbsolutePath()).thenReturn(URI.create("https://localhost:443/apis/enmasse.io/v1alpha1/addressspaces")); + when(mockUriInfo.getPath()).thenReturn("/apis/enmasse.io/v1alpha1/addressspaces"); + when(mockRequestContext.getUriInfo()).thenReturn(mockUriInfo); + } + + + private void assertAuthenticatedAs(ContainerRequestContext requestContext, String userName) { + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + handler.filter(requestContext); + verify(requestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + assertThat(RbacSecurityContext.getUserName(context.getUserPrincipal()), is(userName)); + } + + @Test + public void testNoAuthorizationHeader() { + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn(null); + assertAuthenticatedAs(mockRequestContext, "system:anonymous"); + } + + @Test + public void testBasicAuth() throws IOException { + Files.write(Paths.get(tokenFile.getAbsolutePath()), "valid_token".getBytes()); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Basic dXNlcjpwYXNzCg=="); + + assertAuthenticatedAs(mockRequestContext, "system:anonymous"); + } + + @Test(expected = NotAuthorizedException.class) + public void testInvalidToken() { + TokenReview returnedTokenReview = new TokenReview(null, null, false); + when(mockAuthApi.performTokenReview("invalid_token")).thenReturn(returnedTokenReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer invalid_token"); + handler.filter(mockRequestContext); + } + + @Test + public void testValidTokenButNotAuthorized() { + TokenReview returnedTokenReview = new TokenReview("foo", "myid", true); + when(mockAuthApi.performTokenReview("valid_token")).thenReturn(returnedTokenReview); + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("foo", false); + when(mockAuthApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer valid_token"); + when(mockRequestContext.getMethod()).thenReturn(HttpMethod.POST); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + handler.filter(mockRequestContext); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertNotNull(context); + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("foo")); + assertThat(RbacSecurityContext.getUserId(rbacSecurityContext.getUserPrincipal()), is("myid")); + assertFalse(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "configmaps", ""))); + } + + @Test + public void testHealthAuthz() { + when(mockUriInfo.getPath()).thenReturn("/healthz"); + handler.filter(mockRequestContext); + } + + @Test + public void testCertAuthorization() { + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("me", true); + when(mockAuthApi.performSubjectAccessReviewResource(eq("me"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString("X-Remote-User")).thenReturn("me"); + + HttpServerRequest request = mock(HttpServerRequest.class); + HttpConnection connection = mock(HttpConnection.class); + when(request.isSSL()).thenReturn(true); + when(request.connection()).thenReturn(connection); + + handler.setRequest(request); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("me")); + assertTrue(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "addressspaces", "enmasse.io"))); + } + + @Test + public void testCertAuthorizationFailed() throws SSLPeerUnverifiedException { + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("system:anonymous", false); + when(mockAuthApi.performSubjectAccessReviewResource(eq("system:anonymous"), any(), any(), eq("create"), eq("enmasse.io"))).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString("X-Remote-User")).thenReturn("me"); + + HttpServerRequest request = mock(HttpServerRequest.class); + HttpConnection connection = mock(HttpConnection.class); + when(request.isSSL()).thenReturn(true); + when(request.connection()).thenReturn(connection); + when(connection.peerCertificateChain()).thenThrow(new SSLPeerUnverifiedException("")); + + handler.setRequest(request); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("system:anonymous")); + assertFalse(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "addressspaces", "enmasse.io"))); + } + + @Test + public void testAuthorized() throws IOException { + TokenReview returnedTokenReview = new TokenReview("foo", "myid", true); + when(mockAuthApi.performTokenReview("valid_token")).thenReturn(returnedTokenReview); + SubjectAccessReview returnedSubjectAccessReview = new SubjectAccessReview("foo", true); + when(mockAuthApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), eq("create"), any())).thenReturn(returnedSubjectAccessReview); + when(mockRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer valid_token"); + when(mockRequestContext.getMethod()).thenReturn(HttpMethod.POST); + + handler.filter(mockRequestContext); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(SecurityContext.class); + verify(mockRequestContext).setSecurityContext(contextCaptor.capture()); + SecurityContext context = contextCaptor.getValue(); + + assertThat(context.getAuthenticationScheme(), is("RBAC")); + RbacSecurityContext rbacSecurityContext = (RbacSecurityContext) context; + assertThat(RbacSecurityContext.getUserName(rbacSecurityContext.getUserPrincipal()), is("foo")); + assertTrue(rbacSecurityContext.isUserInRole(RbacSecurityContext.rbacToRole("myspace", ResourceVerb.create, "configmaps", ""))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java new file mode 100644 index 0000000000..1bc7fc19f6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-common/src/test/java/io/enmasse/api/common/DefaultExceptionMapperTest.java @@ -0,0 +1,50 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.common; + +import io.fabric8.kubernetes.api.model.StatusBuilder; +import io.fabric8.kubernetes.client.KubernetesClientException; +import org.junit.Test; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import static org.junit.Assert.*; + +public class DefaultExceptionMapperTest { + + @Test + public void testToResponse() { + int code = 410; + Response.Status status = Response.Status.fromStatusCode(code); + String message = "Some error message"; + WebApplicationException exception = new WebApplicationException(message, status); + + Response response = new DefaultExceptionMapper().toResponse(exception); + assertEquals(code, response.getStatus()); + assertEquals(status.getReasonPhrase(), response.getStatusInfo().getReasonPhrase()); + assertTrue(response.getEntity() instanceof Status); + Status responseEntity = (Status) response.getEntity(); + assertEquals(status.getReasonPhrase(), responseEntity.getReason()); + assertEquals(message, responseEntity.getMessage()); + } + + @Test + public void testToResponseStatus422() { + int code = 422; + io.fabric8.kubernetes.api.model.Status status = new StatusBuilder().withCode(code).build(); + String message = "Some error message"; + KubernetesClientException kubernetesClientException = new KubernetesClientException(message, code, status); + + Response response = new DefaultExceptionMapper().toResponse(kubernetesClientException); + assertEquals(code, response.getStatus()); + // can't check for response.getStatusInfo().getReasonPhrase() here because 422 isn't known in Response.Status + assertTrue(response.getEntity() instanceof Status); + Status responseEntity = (Status) response.getEntity(); + assertEquals("Unprocessable Entity", responseEntity.getReason()); + assertEquals(message, responseEntity.getMessage()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java new file mode 100644 index 0000000000..12de1c16d6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/AddressSpaceTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model; + + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + + +public class AddressSpaceTest { + + @Test + public void testSimpleCreateFromBuilder() { + AddressSpace space = new AddressSpace.Builder() + .setName("name") + .setType("type") + .setPlan("plan") + .build(); + + assertNotNull(space); + + assertThat(space.getName(), is("name")); + assertThat(space.getType(), is("type")); + assertThat(space.getPlan(), is("plan")); + assertThat(space.getStatus(), is(new AddressSpaceStatus(false))); + assertNotNull(space.getEndpoints()); + assertThat(space.getEndpoints().size(), is(0)); + assertNotNull(space.getAuthenticationService()); + assertNotNull(space.getAnnotations()); + assertThat(space.getAnnotations().size(), is(0)); + assertNotNull(space.getLabels()); + assertThat(space.getLabels().size(), is(0)); + } + + + @Test + public void testSimpleWithMissingMandatory() { + try { + new AddressSpace.Builder() + .setType("type") + .setPlan("plan") + .build(); + fail(); + } catch (NullPointerException e) { + // pass + } + + try { + new AddressSpace.Builder() + .setName("name") + .setPlan("plan") + .build(); + fail(); + } catch (NullPointerException e) { + // pass + } + + try { + new AddressSpace.Builder() + .setName("name") + .setType("type") + .build(); + fail(); + } catch (NullPointerException e) { + // pass + } + } + + @Test + public void testEqualityIsBasedOnNameAndNamespace() { + AddressSpace space1 = new AddressSpace.Builder() + .setName("name") + .setType("type") + .setPlan("plan") + .build(); + AddressSpace space2 = new AddressSpace.Builder() + .setName("name") + .setType("type2") + .setPlan("plan") + .build(); + assertEquals(space1, space2); + AddressSpace space3 = new AddressSpace.Builder() + .setName("name") + .setNamespace("ns") + .setType("type2") + .setPlan("plan") + .build(); + assertNotEquals(space1, space3); + AddressSpace space4 = new AddressSpace.Builder() + .setName("name") + .setNamespace("ns") + .setType("type") + .setPlan("plan2") + .build(); + assertEquals(space3, space4); + AddressSpace space5 = new AddressSpace.Builder() + .setName("name2") + .setNamespace("ns") + .setType("type") + .setPlan("plan2") + .build(); + assertNotEquals(space4, space5); + + + + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java new file mode 100644 index 0000000000..85616ae89c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/AddressTest.java @@ -0,0 +1,95 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.*; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.hasItem; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class AddressTest { + @Test + public void testCreateFromBuilder() { + Address.Builder b1 = new Address.Builder() + .setAddress("addr1") + .setAddressSpace("space1") + .setName("myname") + .setType("queue") + .setPlan("myplan") + .setStatus(new Status(true)) + .setUid("myuuid") + .setResourceVersion("1234") + .setSelfLink("/my/link") + .setCreationTimestamp("my stamp"); + + Address a1 = b1.build(); + + Address.Builder b2 = new Address.Builder(a1); + + Address a2 = b2.build(); + + assertThat(a1.getAddress(), is(a2.getAddress())); + assertThat(a1.getAddressSpace(), is(a2.getAddressSpace())); + assertThat(a1.getName(), is(a2.getName())); + assertThat(a1.getPlan(), is(a2.getPlan())); + assertThat(a1.getStatus(), is(a2.getStatus())); + assertThat(a1.getType(), is(a2.getType())); + assertThat(a1.getUid(), is(a2.getUid())); + assertThat(a1.getResourceVersion(), is(a2.getResourceVersion())); + assertThat(a1.getSelfLink(), is(a2.getSelfLink())); + assertThat(a1.getCreationTimestamp(), is(a2.getCreationTimestamp())); + } + + @Test + public void testSanitizer() { + Address b1 = new Address.Builder() + .setNamespace("ns1") + .setAddress("myAddr_-") + .setAddressSpace("myspace") + .setPlan("p1") + .setType("t1") + .build(); + + Address b2 = new Address.Builder() + .setNamespace("ns1") + .setAddress(b1.getAddress()) + .setAddressSpace("myspace") + .setName(b1.getName()) + .setPlan(b1.getPlan()) + .setType(b1.getType()) + .build(); + assertNull(b1.getName()); + String generated = Address.generateName(b1.getAddressSpace(), b1.getAddress()); + System.out.println(generated); + assertTrue(generated.startsWith("myspace.myaddr1.")); + assertThat(b1.getName(), is(b2.getName())); + assertThat(b1.getAddress(), is(b2.getAddress())); + assertThat(b1.getPlan(), is(b2.getPlan())); + assertThat(b1.getType(), is(b2.getType())); + } + + @Test + public void testCopy() { + Address a = new Address.Builder() + .setAddress("a1") + .setPlan("p1") + .setType("t1") + .setNamespace("ns") + .setAddressSpace("myspace") + .setStatus(new Status(true).setPhase(Status.Phase.Active).appendMessage("foo")) + .build(); + + Address b = new Address.Builder(a).build(); + + assertThat(a, is(b)); + assertTrue(b.getStatus().isReady()); + assertThat(b.getStatus().getPhase(), is(Status.Phase.Active)); + assertThat(b.getStatus().getMessages(), hasItem("foo")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java new file mode 100644 index 0000000000..634c5ec63c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/KubeUtilTest.java @@ -0,0 +1,22 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.KubeUtil; +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +public class KubeUtilTest { + @Test + public void testLeaveSpaceForPodIdentifier() { + String address = "receiver-round-robincli_rhearatherlongaddresswhichcanbeverylongblablabla"; + String id = KubeUtil.sanitizeName(address); + assertThat(id.length(), is(60)); + String id2 = KubeUtil.sanitizeName(id); + assertThat(id, is(id2)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java new file mode 100644 index 0000000000..d45dbaa807 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/address/model/v1/address/SerializationTest.java @@ -0,0 +1,490 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.address.model.v1.address; + +import io.enmasse.address.model.*; +import io.enmasse.address.model.v1.CodecV1; +import io.enmasse.address.model.v1.DeserializeException; +import io.enmasse.admin.model.v1.AddressPlan; +import io.enmasse.admin.model.v1.AddressSpacePlan; +import io.enmasse.admin.model.v1.AddressSpacePlanBuilder; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import org.junit.Test; +import org.mockito.internal.util.collections.Sets; + +import java.io.IOException; +import java.util.*; + +import static io.enmasse.address.model.ExposeSpec.ExposeType.route; +import static io.enmasse.address.model.ExposeSpec.TlsTermination.passthrough; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +// TODO: Add more tests of invalid input to deserialization +public class SerializationTest { + + @Test + public void testSerializeAddress() throws IOException { + String uuid = UUID.randomUUID().toString(); + Address address = new Address.Builder() + .setName("as1.a1") + .setAddress("addr1") + .setAddressSpace("as1") + .setNamespace("ns") + .setType("queue") + .setPlan("inmemory") + .setUid(uuid) + .putAnnotation("my", "annotation") + .setResourceVersion("1234") + .setSelfLink("/my/link") + .setCreationTimestamp("my stamp") + .build(); + + byte [] serialized = CodecV1.getMapper().writeValueAsBytes(address); + + Address deserialized = CodecV1.getMapper().readValue(serialized, Address.class); + + assertThat(deserialized, is(address)); + assertThat(deserialized.getName(), is(address.getName())); + assertThat(deserialized.getAddressSpace(), is(address.getAddressSpace())); + assertThat(deserialized.getType(), is(address.getType())); + assertThat(deserialized.getUid(), is(address.getUid())); + assertThat(deserialized.getResourceVersion(), is(address.getResourceVersion())); + assertThat(deserialized.getSelfLink(), is(address.getSelfLink())); + assertThat(deserialized.getCreationTimestamp(), is(address.getCreationTimestamp())); + assertThat(deserialized.getPlan(), is(address.getPlan())); + assertThat(deserialized.getAddress(), is(address.getAddress())); + assertThat(deserialized.getAnnotations(), is(address.getAnnotations())); + } + + @Test + public void testSerializeAddressList() throws IOException { + Address addr1 = new Address.Builder() + .setName("a1.a1") + .setAddress("addr1") + .setAddressSpace("a1") + .setNamespace("ns") + .setType("queue") + .setPlan("myplan") + .build(); + + Address addr2 = new Address.Builder() + .setName("a1.a2") + .setAddressSpace("a1") + .setAddress("addr2") + .setNamespace("ns") + .setType("anycast") + .setPlan("myplan") + .build(); + + + AddressList list = new AddressList(Sets.newSet(addr1, addr2)); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + List
deserialized = CodecV1.getMapper().readValue(serialized, AddressList.class); + + assertThat(deserialized, is(list)); + } + + + @Test + public void testSerializeEmptyAddressList() throws IOException { + + AddressList list = new AddressList(Collections.emptySet()); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + assertTrue("Serialized form '"+serialized+"' does not include empty items list", + serialized.matches(".*\"items\"\\s*:\\s*\\[\\s*\\].*")); + List
deserialized = CodecV1.getMapper().readValue(serialized, AddressList.class); + + assertThat(deserialized, is(list)); + } + + @Test(expected = DeserializeException.class) + public void testSerializeAddressSpaceWithIllegalName() throws IOException { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace.bar") + .setPlan("myplan") + .setType("mytype") + .build(); + + String serialized = CodecV1.getMapper().writeValueAsString(addressSpace); + CodecV1.getMapper().readValue(serialized, AddressSpace.class); + } + + @SuppressWarnings("serial") + @Test + public void testSerializeAddressSpace() throws IOException { + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .setPlan("defaultplan") + .setType("standard") + .setCreationTimestamp("some date") + .setResourceVersion("1234") + .setSelfLink("/my/resource") + .setStatus(new AddressSpaceStatus(true).appendMessage("hello").appendEndpointStatus( + new EndpointStatus.Builder() + .setName("myendpoint") + .setExternalHost("example.com") + .setExternalPorts(Collections.singletonMap("amqps", 443)) + .setServiceHost("messaging.svc") + .setServicePorts(Collections.singletonMap("amqp", 5672)) + .build())) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .setCertSpec(new CertSpec.Builder().setProvider("provider").setSecretName("mysecret").build()) + .setExposeSpec(new ExposeSpec.Builder() + .setType(route) + .setRouteHost("example.com") + .setRouteTlsTermination(passthrough) + .setRouteServicePort("amqp") + .build()) + .build())) + .setAuthenticationService(new AuthenticationService.Builder() + .setType(AuthenticationServiceType.EXTERNAL) + .setDetails(new HashMap() {{ + put("host", "my.example.com"); + put("port", 5671); + put("caCertSecretName", "authservicesecret"); + put("clientCertSecretName", "clientcertsecret"); + put("saslInitHost", "my.example.com"); + }}) + .build()) + .build(); + + String serialized = CodecV1.getMapper().writeValueAsString(addressSpace); + AddressSpace deserialized = CodecV1.getMapper().readValue(serialized, AddressSpace.class); + + assertThat(deserialized.getName(), is(addressSpace.getName())); + assertThat(deserialized.getNamespace(), is(addressSpace.getNamespace())); + assertThat(deserialized.getType(), is(addressSpace.getType())); + assertThat(deserialized.getPlan(), is(addressSpace.getPlan())); + assertThat(deserialized.getSelfLink(), is(addressSpace.getSelfLink())); + assertThat(deserialized.getCreationTimestamp(), is(addressSpace.getCreationTimestamp())); + assertThat(deserialized.getResourceVersion(), is(addressSpace.getResourceVersion())); + assertThat(deserialized.getStatus().isReady(), is(addressSpace.getStatus().isReady())); + assertThat(deserialized.getStatus().getMessages(), is(addressSpace.getStatus().getMessages())); + assertThat(deserialized.getStatus().getEndpointStatuses().size(), is(addressSpace.getEndpoints().size())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getName(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getName())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getExternalHost(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getExternalHost())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getExternalPorts().values().iterator().next(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getExternalPorts().values().iterator().next())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getServiceHost(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getServiceHost())); + assertThat(deserialized.getStatus().getEndpointStatuses().get(0).getServicePorts(), is(addressSpace.getStatus().getEndpointStatuses().get(0).getServicePorts())); + assertThat(deserialized.getEndpoints().size(), is(addressSpace.getEndpoints().size())); + assertThat(deserialized.getEndpoints().get(0).getName(), is(addressSpace.getEndpoints().get(0).getName())); + assertThat(deserialized.getEndpoints().get(0).getService(), is(addressSpace.getEndpoints().get(0).getService())); + assertThat(deserialized.getEndpoints().get(0).getCertSpec().get().getProvider(), is(addressSpace.getEndpoints().get(0).getCertSpec().get().getProvider())); + assertThat(deserialized.getEndpoints().get(0).getCertSpec().get().getSecretName(), is(addressSpace.getEndpoints().get(0).getCertSpec().get().getSecretName())); + assertThat(deserialized.getAuthenticationService().getType(), is(addressSpace.getAuthenticationService().getType())); + assertThat(deserialized.getAuthenticationService().getDetails(), is(addressSpace.getAuthenticationService().getDetails())); + assertThat(addressSpace, is(deserialized)); + } + + @Test + public void testDeserializeAddressSpaceCompat() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\":{" + + " \"type\": \"standard\"," + + " \"plan\": \"unlimited-standard\"," + + " \"endpoints\":[" + + " {\"name\":\"messaging\",\"service\":\"messaging\",\"servicePort\":\"amqps\"}" + + " ]"+ + "}}"; + AddressSpace addressSpace = CodecV1.getMapper().readValue(json, AddressSpace.class); + assertThat(addressSpace.getEndpoints().size(), is(1)); + assertTrue(addressSpace.getEndpoints().get(0).getExposeSpec().isPresent()); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getType(), is(route)); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getRouteTlsTermination(), is(passthrough)); + assertThat(addressSpace.getEndpoints().get(0).getExposeSpec().get().getRouteServicePort(), is("amqps")); + } + + @Test(expected = DeserializeException.class) + public void testDeserializeAddressSpaceMissingDefaults() throws IOException { + String serialized = "{\"kind\": \"AddressSpace\", \"apiVersion\": \"v1alpha1\"}"; + CodecV1.getMapper().readValue(serialized, AddressSpace.class); + } + + @Test(expected = DeserializeException.class) + public void testDeserializeAddressMissingDefaults() throws IOException { + String serialized = "{\"kind\": \"Address\", \"apiVersion\": \"v1alpha1\"}"; + CodecV1.getMapper().readValue(serialized, Address.class); + } + + @Test + public void testDeserializeAddressSpacePlan() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpacePlan\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"," + + " \"annotations\": {" + + " \"mykey\": \"myvalue\"" + + " }" + + "}," + + "\"displayName\": \"MySpace\"," + + "\"shortDescription\": \"MySpace is cool\"," + + "\"longDescription\": \"MySpace is cool, but not much used anymore\"," + + "\"uuid\": \"12345\"," + + "\"addressPlans\":[\"plan1\"]," + + "\"addressSpaceType\": \"standard\"," + + "\"resources\": [" + + " { \"name\": \"router\", \"min\": 0.5, \"max\": 1.0 }, " + + " { \"name\": \"broker\", \"min\": 0.1, \"max\": 0.5 }" + + "]" + + "}"; + + AddressSpacePlan addressSpacePlan = CodecV1.getMapper().readValue(json, AddressSpacePlan.class); + assertThat(addressSpacePlan.getMetadata().getName(), is("myspace")); + assertThat(addressSpacePlan.getAdditionalProperties().get("displayName"), is("MySpace")); + assertFalse(addressSpacePlan.getUuid().isEmpty()); + assertThat(addressSpacePlan.getAddressPlans().size(), is(1)); + assertThat(addressSpacePlan.getAddressPlans().get(0), is("plan1")); + assertThat(addressSpacePlan.getResources().size(), is(2)); + assertThat(addressSpacePlan.getResources().get(0).getName(), is("router")); + assertThat(addressSpacePlan.getResources().get(1).getName(), is("broker")); + assertThat(addressSpacePlan.getMetadata().getAnnotations().size(), is (1)); + assertThat(addressSpacePlan.getMetadata().getAnnotations().get("mykey"), is("myvalue")); + } + + @Test + public void testDeserializeAddressSpacePlanWithDefaults() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpacePlan\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"addressPlans\":[\"plan1\"]," + + "\"addressSpaceType\": \"standard\"," + + "\"resources\": [" + + " { \"name\": \"router\", \"min\": 0.5, \"max\": 1.0 }, " + + " { \"name\": \"broker\", \"min\": 0.1, \"max\": 0.5 }" + + "]" + + "}"; + + AddressSpacePlan addressSpacePlan = CodecV1.getMapper().readValue(json, AddressSpacePlan.class); + assertThat(addressSpacePlan.getMetadata().getName(), is("myspace")); + assertNull(addressSpacePlan.getUuid()); + assertThat(addressSpacePlan.getAddressPlans().size(), is(1)); + assertThat(addressSpacePlan.getAddressPlans().get(0), is("plan1")); + assertThat(addressSpacePlan.getResources().size(), is(2)); + assertThat(addressSpacePlan.getResources().get(0).getName(), is("router")); + assertThat(addressSpacePlan.getResources().get(1).getName(), is("broker")); + } + + @Test + public void testBuilder() { + AddressSpacePlan plan = new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace("ns") + .build()) + .withShortDescription("desc") + .withUuid("uuid") + .withAddressPlans(Arrays.asList("a", "b")) + .build(); + assertEquals(2, plan.getAddressPlans().size()); + assertEquals("plan1", plan.getMetadata().getName()); + assertEquals("desc", plan.getShortDescription()); + } + + /* + @Test + public void testDeserializeResourceDefinitionWithTemplate() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"ResourceDefinition\"," + + "\"metadata\":{" + + " \"name\":\"rdef1\"" + + "}," + + "\"template\": \"mytemplate\"," + + "\"parameters\": [" + + " {\"name\": \"MY_VAR1\", \"value\": \"MY_VAL1\"}," + + " {\"name\": \"MY_VAR2\", \"value\": \"MY_VAL2\"}" + + "]}"; + + ResourceDefinition rdef = CodecV1.getMapper().readValue(json, ResourceDefinition.class); + assertThat(rdef.getName(), is("rdef1")); + assertTrue(rdef.getTemplateName().isPresent()); + assertThat(rdef.getTemplateName().get(), is("mytemplate")); + Map parameters = rdef.getTemplateParameters(); + assertThat(parameters.size(), is(2)); + assertThat(parameters.get("MY_VAR1"), is("MY_VAL1")); + assertThat(parameters.get("MY_VAR2"), is("MY_VAL2")); + } + + @Test + public void testDeserializeResourceDefinitionNoTemplate() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"ResourceDefinition\"," + + "\"metadata\":{" + + " \"name\":\"rdef1\"" + + "}" + + "}"; + + ResourceDefinition rdef = CodecV1.getMapper().readValue(json, ResourceDefinition.class); + assertThat(rdef.getName(), is("rdef1")); + assertFalse(rdef.getTemplateName().isPresent()); + }*/ + + @Test + public void testDeserializeAddressPlan() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressPlan\"," + + "\"metadata\":{" + + " \"name\":\"plan1\"" + + "}," + + "\"displayName\": \"MyPlan\"," + + "\"shortDescription\": \"MyPlan is cool\"," + + "\"longDescription\": \"MyPlan is cool, but not much used anymore\"," + + "\"addressType\": \"queue\"," + + "\"requiredResources\": [" + + " { \"name\": \"router\", \"credit\": 0.2 }," + + " { \"name\": \"broker\", \"credit\": 0.5 }" + + "]" + + "}"; + + AddressPlan addressPlan = CodecV1.getMapper().readValue(json, AddressPlan.class); + assertThat(addressPlan.getMetadata().getName(), is("plan1")); + assertThat(addressPlan.getAdditionalProperties().get("displayName"), is("MyPlan")); + assertThat(addressPlan.getAddressType(), is("queue")); + assertNull(addressPlan.getUuid()); + assertThat(addressPlan.getRequiredResources().size(), is(2)); + assertThat(addressPlan.getRequiredResources().get(0).getName(), is("router")); + assertThat(addressPlan.getRequiredResources().get(1).getName(), is("broker")); + } + + @Test + public void testDeserializeAddressPlanWithDefaults() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressPlan\"," + + "\"metadata\":{" + + " \"name\":\"plan1\"" + + "}," + + "\"addressType\": \"queue\"," + + "\"requiredResources\": [" + + " { \"name\": \"router\", \"credit\": 0.2 }," + + " { \"name\": \"broker\", \"credit\": 0.5 }" + + "]" + + "}"; + + AddressPlan addressPlan = CodecV1.getMapper().readValue(json, AddressPlan.class); + assertThat(addressPlan.getMetadata().getName(), is("plan1")); + assertThat(addressPlan.getAddressType(), is("queue")); + assertNull(addressPlan.getUuid()); + assertThat(addressPlan.getRequiredResources().size(), is(2)); + assertThat(addressPlan.getRequiredResources().get(0).getName(), is("router")); + assertThat(addressPlan.getRequiredResources().get(1).getName(), is("broker")); + } + + @Test(expected = RuntimeException.class) + public void testDeserializeAddressSpaceWithMissingAuthServiceValues() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.io/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\": {" + + " \"type\":\"standard\"," + + " \"authenticationService\": {" + + " \"type\": \"external\"" + + " }" + + "}" + + "}"; + + CodecV1.getMapper().readValue(json, AddressSpace.class); + } + + @Test(expected = RuntimeException.class) + public void testDeserializeAddressSpaceWithExtraAuthServiceValues() throws IOException { + String json = "{" + + "\"apiVersion\":\"enmasse.i/v1alpha1\"," + + "\"kind\":\"AddressSpace\"," + + "\"metadata\":{" + + " \"name\":\"myspace\"" + + "}," + + "\"spec\": {" + + " \"type\":\"standard\"," + + " \"authenticationService\": {" + + " \"type\": \"standard\"," + + " \"details\": {" + + " \"host\": \"my.example.com\"" + + " }" + + " }" + + "}" + + "}"; + + CodecV1.getMapper().readValue(json, AddressSpace.class); + } + + @Test + public void testSerializeAddressSpaceList() throws IOException { + AddressSpace a1 = new AddressSpace.Builder() + .setName("myspace") + .setNamespace("mynamespace") + .setPlan("myplan") + .setType("standard") + .setStatus(new AddressSpaceStatus(true).appendMessage("hello")) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("myendpoint") + .setService("messaging") + .build())) + .build(); + + AddressSpace a2 = new AddressSpace.Builder() + .setName("mysecondspace") + .setNamespace("myothernamespace") + .setPlan("myotherplan") + .setType("brokered") + .setStatus(new AddressSpaceStatus(false)) + .setEndpointList(Arrays.asList(new EndpointSpec.Builder() + .setName("bestendpoint") + .setService("mqtt") + .setCertSpec(new CertSpec.Builder().setProvider("myprovider").setSecretName("mysecret").build()) + .build())) + .build(); + + AddressSpaceList list = new AddressSpaceList(); + list.add(a1); + list.add(a2); + + String serialized = CodecV1.getMapper().writeValueAsString(list); + + AddressSpaceList deserialized = CodecV1.getMapper().readValue(serialized, AddressSpaceList.class); + + assertAddressSpace(deserialized, a1); + assertAddressSpace(deserialized, a2); + } + + private void assertAddressSpace(AddressSpaceList deserialized, AddressSpace expected) { + AddressSpace found = null; + for (AddressSpace addressSpace : deserialized) { + if (addressSpace.getName().equals(expected.getName())) { + found = addressSpace; + break; + } + + } + assertNotNull(found); + + assertThat(found.getName(), is(expected.getName())); + assertThat(found.getNamespace(), is(expected.getNamespace())); + assertThat(found.getType(), is(expected.getType())); + assertThat(found.getPlan(), is(expected.getPlan())); + assertThat(found.getStatus().isReady(), is(expected.getStatus().isReady())); + assertThat(found.getStatus().getMessages(), is(expected.getStatus().getMessages())); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java new file mode 100644 index 0000000000..eb2604d8b4 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/admin/model/v1/InfraConfigDeserializerTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.admin.model.v1; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.address.model.InfraConfigDeserializer; +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InfraConfigDeserializerTest { + + private final InfraConfigDeserializer deserializer = json -> new ObjectMapper().readValue(json, StandardInfraConfig.class); + + + @Test + public void deserializeNetworkPolicy() throws Exception { + + + String str = "{\n" + + " \"spec\": {\n" + + " \"networkPolicy\": {\n" + + " \"ingress\": [\n" + + " {\n" + + " \"from\": [\n" + + " {\n" + + " \"podSelector\": {\n" + + " \"my\": \"label\"\n" + + " }\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + + InfraConfig infraConfig = deserializer.fromJson(str); + + assertTrue(infraConfig instanceof StandardInfraConfig); + + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java new file mode 100644 index 0000000000..56554a5dcf --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-model/src/test/java/io/enmasse/user/model/v1/UserModelTest.java @@ -0,0 +1,226 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.user.model.v1; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class UserModelTest { + @Test + public void testSerializeUserPassword() throws IOException { + User user = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + ObjectMapper mapper = new ObjectMapper(); + byte [] serialized = mapper.writeValueAsBytes(user); + + User deserialized = mapper.readValue(serialized, User.class); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + + UserList list = new UserList(); + list.getItems().add(user); + + serialized = mapper.writeValueAsBytes(list); + UserList deserializedList = mapper.readValue(serialized, UserList.class); + + assertEquals(1, deserializedList.getItems().size()); + + deserialized = deserializedList.getItems().get(0); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + } + + @Test + public void testSerializeUserFederated() throws IOException { + User user = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.federated) + .withProvider("openshift") + .withFederatedUserid("uuid") + .withFederatedUsername("user1") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + ObjectMapper mapper = new ObjectMapper(); + byte [] serialized = mapper.writeValueAsBytes(user); + + User deserialized = mapper.readValue(serialized, User.class); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + + UserList list = new UserList(); + list.getItems().add(user); + + serialized = mapper.writeValueAsBytes(list); + UserList deserializedList = mapper.readValue(serialized, UserList.class); + + assertEquals(1, deserializedList.getItems().size()); + + deserialized = deserializedList.getItems().get(0); + + assertEquals(user.getMetadata().getName(), deserialized.getMetadata().getName()); + assertEquals(user.getMetadata().getNamespace(), deserialized.getMetadata().getNamespace()); + assertEquals(user.getSpec().getUsername(), deserialized.getSpec().getUsername()); + assertEquals(user.getSpec().getAuthentication().getType(), deserialized.getSpec().getAuthentication().getType()); + assertEquals(user.getSpec().getAuthentication().getPassword(), deserialized.getSpec().getAuthentication().getPassword()); + assertEquals(user.getSpec().getAuthorization().size(), deserialized.getSpec().getAuthorization().size()); + + assertAuthorization(deserialized, Arrays.asList("queue1", "topic1"), Arrays.asList(Operation.send, Operation.recv)); + } + + @Test + public void testValidation() { + createAndValidate("myspace.user1", "user1", true); + createAndValidate("myspace.usEr1", "user1", false); + createAndValidate("myspace.user1", "usEr1", false); + createAndValidate("myspace.user1", "usEr1", false); + createAndValidate("myspaceuser1", "user1", false); + + createAndValidate("myspace.user1_", "user1", false); + createAndValidate("myspace_.user1", "user1", false); + createAndValidate("_myspace.user1", "user1", false); + createAndValidate("myspace._user1", "user1", false); + createAndValidate("myspace.user1", "user1_", false); + createAndValidate("myspace.user_1", "user1", false); + createAndValidate("myspace.user1", "user_1", true); + + createAndValidate("myspace.user1@", "user1", false); + createAndValidate("myspace@.user1", "user1", false); + createAndValidate("@myspace.user1", "user1", false); + createAndValidate("myspace.@user1", "user1", false); + createAndValidate("myspace.user1", "user1@", false); + createAndValidate("myspace.user@1", "user1", true); + createAndValidate("myspace.user1", "user@1", true); + + createAndValidate("myspace.user1@example.com", "user1@example.com", true); + + createAndValidate("myspace.user1-", "user1", false); + createAndValidate("myspace-.user1", "user1", false); + createAndValidate("-myspace.user1", "user1", false); + createAndValidate("myspace.-user1", "user1", false); + createAndValidate("myspace.user1", "user1-", false); + createAndValidate("myspace.user1", "-user1-", false); + createAndValidate("myspace.user1-foo-bar", "user1-foo-bar", true); + UUID uuid = UUID.randomUUID(); + createAndValidate("myspace." + uuid.toString(), uuid.toString(), true); + createAndValidate("a.ab", "ab", true); + createAndValidate("aa.b", "b", true); + createAndValidate("a.b", "b", true); + } + + private void createAndValidate(String name, String username, boolean shouldValidate) { + User u1 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName(name) + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername(username) + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.federated) + .withProvider("openshift") + .withFederatedUserid("uuid") + .withFederatedUsername("user1") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + try { + u1.validate(); + assertTrue(shouldValidate); + } catch (UserValidationFailedException e) { + // e.printStackTrace(); + assertFalse(shouldValidate); + } + } + + private void assertAuthorization(User deserialized, List addresses, List operations) { + for (UserAuthorization authorization : deserialized.getSpec().getAuthorization()) { + if (authorization.getOperations().equals(operations) && authorization.getAddresses().equals(addresses)) { + return; + } + } + assertFalse(true, "Unable to find matching authorization"); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java new file mode 100644 index 0000000000..df7e71893d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/server/HTTPServerTest.java @@ -0,0 +1,345 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.api.server; + +import io.enmasse.address.model.*; +import io.enmasse.api.auth.AuthApi; +import io.enmasse.api.auth.SubjectAccessReview; +import io.enmasse.api.auth.TokenReview; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.metrics.api.Metrics; +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.*; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpClientRequest; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.time.Clock; +import java.util.Arrays; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@RunWith(VertxUnitRunner.class) +public class HTTPServerTest { + + private Vertx vertx; + private TestAddressSpaceApi instanceApi; + private AddressSpace addressSpace; + + @Before + public void setup(TestContext context) throws InterruptedException { + vertx = Vertx.vertx(); + instanceApi = new TestAddressSpaceApi(); + String addressSpaceName = "myinstance"; + addressSpace = createAddressSpace(addressSpaceName); + instanceApi.createAddressSpace(addressSpace); + + AuthApi authApi = mock(AuthApi.class); + when(authApi.getNamespace()).thenReturn("controller"); + when(authApi.performTokenReview(eq("mytoken"))).thenReturn(new TokenReview("foo", "myid", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + + UserApi userApi = mock(UserApi.class); + UserList users = new UserList(); + users.getItems().add(new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myinstance.user1") + .withNamespace("myinstance") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("admin") + .build()) + .withAuthorization(Arrays.asList(new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build()); + when(userApi.listUsers(any())).thenReturn(users); + + ApiServerOptions options = new ApiServerOptions(); + options.setVersion("1.0"); + options.setCertDir("/doesnotexist"); + vertx.deployVerticle(new HTTPServer(instanceApi, new TestSchemaProvider(),authApi, userApi, new Metrics(), options, null, null, Clock.systemUTC()), context.asyncAssertSuccess()); + } + + @After + public void teardown(TestContext context) { + vertx.close(context.asyncAssertSuccess()); + } + + private AddressSpace createAddressSpace(String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(name) + .setType("type1") + .setPlan("myplan") + .setStatus(new io.enmasse.address.model.AddressSpaceStatus(false)) + .appendEndpoint(new EndpointSpec.Builder() + .setName("foo") + .setService("messaging") + .build()) + .build(); + } + + @Test + public void testAddressingApi(TestContext context) throws InterruptedException { + instanceApi.withAddressSpace(addressSpace).createAddress( + new Address.Builder() + .setAddressSpace("myinstance") + .setName("myinstance.addr1") + .setAddress("addR1") + .setNamespace("ns") + .setType("queue") + .setPlan("myplan") + .build()); + + HttpClient client = vertx.createHttpClient(); + try { + { + Async async = context.async(); + HttpClientRequest r1 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses", response -> { + context.assertEquals(200, response.statusCode()); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("items")); + context.assertEquals("myinstance.addr1", data.getJsonArray("items").getJsonObject(0).getJsonObject("metadata").getString("name")); + async.complete(); + }); + }); + putAuthzToken(r1); + r1.end(); + async.awaitSuccess(60_000); + } + { + Async async = context.async(); + HttpClientRequest r2 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addresses/myinstance.addr1", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("metadata")); + context.assertEquals("myinstance.addr1", data.getJsonObject("metadata").getString("name")); + async.complete(); + }); + }); + putAuthzToken(r2); + r2.end(); + async.awaitSuccess(60_000); + } + { + Async async = context.async(); + HttpClientRequest r3 = client.post(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses", response -> { + response.bodyHandler(buffer -> { + context.assertEquals(201, response.statusCode()); + async.complete(); + }); + }); + r3.putHeader("Content-Type", "application/json"); + putAuthzToken(r3); + r3.end("{\"apiVersion\":\"enmasse.io/v1alpha1\",\"kind\":\"AddressList\",\"items\":[{\"metadata\":{\"name\":\"a4\"},\"spec\":{\"address\":\"a4\",\"type\":\"queue\",\"plan\":\"plan1\"}}]}"); + async.awaitSuccess(60_000); + } + { + Async async = context.async(); + HttpClientRequest r4 = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/ns/addressspaces/myinstance/addresses?address=addR1", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + System.out.println(data.toString()); + context.assertTrue(data.containsKey("metadata")); + context.assertEquals("addR1", data.getJsonObject("spec").getString("address")); + async.complete(); + }); + }); + putAuthzToken(r4); + r4.end(); + async.awaitSuccess(60_000); + } + } finally { + client.close(); + } + } + + private static HttpClientRequest putAuthzToken(HttpClientRequest request) { + request.putHeader("Authorization", "Bearer mytoken"); + return request; + } + + @Test + public void testApiResources(TestContext context) throws InterruptedException { + HttpClient client = vertx.createHttpClient(); + try { + { + Async async = context.async(); + HttpClientRequest rootReq = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1", response -> { + context.assertEquals(200, response.statusCode()); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("resources")); + JsonArray resources = data.getJsonArray("resources"); + context.assertEquals(3, resources.size()); + async.complete(); + }); + }); + putAuthzToken(rootReq); + rootReq.end(); + async.awaitSuccess(60_000); + } + { + Async async = context.async(); + HttpClientRequest rootReq = client.get(8080, "localhost", "/apis/user.enmasse.io/v1alpha1", response -> { + context.assertEquals(200, response.statusCode()); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("resources")); + JsonArray resources = data.getJsonArray("resources"); + context.assertEquals(1, resources.size()); + async.complete(); + }); + }); + putAuthzToken(rootReq); + rootReq.end(); + async.awaitSuccess(60_000); + } + } finally { + client.close(); + } + } + + @Test + public void testSchemaApi(TestContext context) throws InterruptedException { + HttpClient client = vertx.createHttpClient(); + try { + { + Async async = context.async(); + HttpClientRequest request = client.get(8080, "localhost", "/apis/enmasse.io/v1alpha1/namespaces/myinstance/addressspaceschemas", response -> { + context.assertEquals(200, response.statusCode()); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + System.out.println(data.toString()); + context.assertTrue(data.containsKey("items")); + context.assertEquals(1, data.getJsonArray("items").size()); + async.complete(); + }); + }); + putAuthzToken(request); + request.end(); + async.awaitSuccess(60_000); + } + } finally { + client.close(); + } + } + + @Test + public void testUserApi(TestContext context) { + HttpClient client = vertx.createHttpClient(); + try { + { + Async async = context.async(); + HttpClientRequest r1 = client.get(8080, "localhost", "/apis/user.enmasse.io/v1alpha1/namespaces/ns/messagingusers", response -> { + context.assertEquals(200, response.statusCode()); + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("items")); + context.assertEquals("myinstance.user1", data.getJsonArray("items").getJsonObject(0).getJsonObject("metadata").getString("name")); + async.complete(); + }); + }); + putAuthzToken(r1); + r1.end(); + async.awaitSuccess(60_000); + } + } finally { + client.close(); + } + } + + /* + @Test + public void testInstanceApi() throws InterruptedException { + Instance instance = new Instance.Builder(AddressSpaceId.withId("myinstance")) + .messagingHost(Optional.of("messaging.example.com")) + .build(); + addressSpaceApi.createAddressSpace(instance); + + HttpClient client = vertx.createHttpClient(); + try { + { + final CountDownLatch latch = new CountDownLatch(1); + client.getNow(8080, "localhost", "/v3/addressspace", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + assertTrue(data.containsKey("kind")); + assertThat(data.getString("kind"), is("InstanceList")); + assertTrue(data.containsKey("items")); + JsonArray items = data.getJsonArray("items"); + assertThat(items.size(), is(1)); + assertThat(items.getJsonObject(0).getJsonObject("spec").getString("messagingHost"), is("messaging.example.com")); + latch.countDown(); + }); + }); + assertTrue(latch.await(1, TimeUnit.MINUTES)); + } + + { + final CountDownLatch latch = new CountDownLatch(1); + client.getNow(8080, "localhost", "/v3/addressspace/myinstance", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + assertTrue(data.containsKey("metadata")); + assertThat(data.getJsonObject("metadata").getString("name"), is("myinstance")); + assertThat(data.getString("kind"), is("Instance")); + assertThat(data.getJsonObject("spec").getString("messagingHost"), is("messaging.example.com")); + latch.countDown(); + }); + }); + assertTrue(latch.await(1, TimeUnit.MINUTES)); + } + } finally { + client.close(); + } + } + */ + + @Test + public void testOpenApiSpec(TestContext context) throws InterruptedException { + HttpClientOptions options = new HttpClientOptions(); + HttpClient client = vertx.createHttpClient(options); + try { + Async async = context.async(); + HttpClientRequest request = client.get(8080, "localhost", "/swagger.json", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("paths")); + async.complete(); + }); + }); + putAuthzToken(request); + request.end(); + async.awaitSuccess(60_000); + } finally { + client.close(); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java new file mode 100644 index 0000000000..8020517a8c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/AddressApiHelperTest.java @@ -0,0 +1,209 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.api.v1; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +import java.util.*; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.AddressApi; +import io.enmasse.k8s.api.AddressSpaceApi; +import org.apache.http.auth.BasicUserPrincipal; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.internal.util.collections.Sets; + +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.SecurityContext; + +public class AddressApiHelperTest { + + @Rule + public final ExpectedException expectedException = ExpectedException.none(); + + private AddressApiHelper helper; + private AddressApi addressApi; + private SecurityContext securityContext; + + @Before + public void setup() { + AddressSpace addressSpace = mock(AddressSpace.class); + when(addressSpace.getType()).thenReturn("type1"); + AddressSpaceApi addressSpaceApi = mock(AddressSpaceApi.class); + addressApi = mock(AddressApi.class); + securityContext = mock(SecurityContext.class); + when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("me")); + when(securityContext.isUserInRole(any())).thenReturn(true); + when(addressSpaceApi.getAddressSpaceWithName(any(), eq("test"))).thenReturn(Optional.of(addressSpace)); + when(addressSpaceApi.withAddressSpace(eq(addressSpace))).thenReturn(addressApi); + helper = new AddressApiHelper(addressSpaceApi, new TestSchemaProvider()); + } + + @Test + public void testCreateAddressResourceNameAlreadyExists() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.singleton(createAddress("q1", "q1"))); + expectedException.expect(BadRequestException.class); + expectedException.expectMessage("Address 'q1' already exists with resource name 'q1'"); + + Address invalidAddress = createAddress("someOtherName", "q1"); + helper.createAddress("test", invalidAddress); + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testCreateAddress() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr = createAddress("someOtherName", "q1"); + helper.createAddress("test", addr); + verify(addressApi).createAddress(eq(addr)); + } + + @Test + public void testCreateAddresses() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr1 = createAddress("test.q1", "q1"); + Address addr2 = createAddress("test.q2", "q2"); + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + verify(addressApi).createAddress(eq(addr1)); + verify(addressApi).createAddress(eq(addr2)); + } + + @Test + public void testCreateAddressesResourceNameAlreadyExists() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.singleton(createAddress("test1.q1", "q1"))); + + Address addr1 = createAddress("test.q1", "q1"); + Address addr2 = createAddress("test.q2", "q2"); + try { + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + fail("Exception not thrown"); + } catch (BadRequestException e) { + // PASS + } + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testCreateAddressesResourceNameDuplicates() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Collections.emptySet()); + + Address addr1 = createAddress("dup", "q1"); + Address addr2 = createAddress("dup", "q2"); + Address addr3 = createAddress("test.q3", "q3"); + try { + helper.createAddresses("test", new HashSet<>(Arrays.asList(addr1, addr2))); + fail("Exception not thrown"); + } catch (BadRequestException e) { + // PASS + assertEquals("Address resource names must be unique. Duplicate resource names: [dup]", e.getMessage()); + } + verify(addressApi, never()).createAddress(any(Address.class)); + } + + @Test + public void testReplaceAddress() throws Exception { + when(addressApi.replaceAddress(any())).thenReturn(true); + + helper.replaceAddress("test", createAddress("q1")); + verify(addressApi).replaceAddress(eq(createAddress("q1"))); + } + + @Test + public void testReplaceAddressNotFound() throws Exception { + when(addressApi.replaceAddress(any())).thenReturn(false); + expectedException.expect(NotFoundException.class); + expectedException.expectMessage("Address q1 not found"); + + helper.replaceAddress("test", createAddress("q1")); + verify(addressApi, never()).replaceAddress(any(Address.class)); + } + + @Test + public void testReplaceAddressWithInvalidAddress() throws Exception { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("q1", "q1")); + addresses.add(createAddress("q2", "q2")); + when(addressApi.listAddresses(any())).thenReturn(addresses); + when(addressApi.replaceAddress(any())).thenReturn(true); + expectedException.expect(BadRequestException.class); + expectedException.expectMessage("Address 'q2' already exists with resource name 'q2'"); + + Address invalidAddress = createAddress("q1", "q2"); + helper.replaceAddress("test", invalidAddress); + verify(addressApi, never()).replaceAddress(any(Address.class)); + } + + @Test + public void testDeleteAddress() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.of(address)); + when(addressApi.deleteAddress(same(address))).thenReturn(true); + assertNotNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDeleteAddressNotFound() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.empty()); + assertNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDeleteAddressReturningFalse() throws Exception { + Address address = createAddress("testAddress"); + when(addressApi.getAddressWithName(same("ns"), same(address.getAddress()))).thenReturn(Optional.of(address)); + when(addressApi.deleteAddress(same(address))).thenReturn(false); + assertNull(helper.deleteAddress("ns", "test", address.getName())); + } + + @Test + public void testDuplicateAddresses() throws Exception { + when(addressApi.listAddresses(any())).thenReturn(Sets.newSet(createAddress("q1"), createAddress("q2"))); + + try { + helper.createAddress("test", createAddress("q3", "q1")); + fail("Expected exception for duplicate address"); + } catch (BadRequestException e) { + assertThat(e.getMessage(), is("Address 'q1' already exists with resource name 'q1'")); + } + } + + @Test + public void testParseLabelSelector() throws Exception { + Map labels = AddressApiHelper.parseLabelSelector("key=value"); + assertThat(labels.size(), is(1)); + assertThat(labels.get("key"), is("value")); + + labels = AddressApiHelper.parseLabelSelector("key1=value1,key2=value2,key3=value3"); + assertThat(labels.size(), is(3)); + assertThat(labels.get("key1"), is("value1")); + assertThat(labels.get("key2"), is("value2")); + assertThat(labels.get("key3"), is("value3")); + } + + private Address createAddress(String name, String address) + { + return new Address.Builder().setName(name).setNamespace("ns").setAddress(address).setAddressSpace("test").setType("queue").setPlan("plan1").build(); + } + + private Address createAddress(String address) + { + return createAddress(address, address); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java new file mode 100644 index 0000000000..cc28687e7b --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpAddressSpaceServiceTest.java @@ -0,0 +1,215 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceList; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.k8s.util.TimeUtil; +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpAddressSpaceServiceTest { + private HttpAddressSpaceService addressSpaceService; + private TestAddressSpaceApi addressSpaceApi; + private AddressSpace a1; + private AddressSpace a2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @Before + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + addressSpaceService = new HttpAddressSpaceService(addressSpaceApi, new TestSchemaProvider(), Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + a1 = new AddressSpace.Builder() + .setName("a1") + .setNamespace("myspace") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(123))) + .setEndpointList(Arrays.asList( + new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .build(), + new EndpointSpec.Builder() + .setName("mqtt") + .setService("mqtt") + .build())) + .build(); + + a2 = new AddressSpace.Builder() + .setName("a2") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(12))) + .setNamespace("othernamespace") + .build(); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null, null)); + assertThat(response.getStatus(), is(200)); + AddressSpaceList data = (AddressSpaceList) response.getEntity(); + + assertThat(data.size(), is(2)); + assertThat(data, hasItem(a1)); + assertThat(data, hasItem(a2)); + } + + @Test + public void testListTableFormat() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null, null)); + assertThat(response.getStatus(), is(200)); + Table data = (Table) response.getEntity(); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().size(), is(2)); + } + + @Test + public void testListException() { + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null, null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGet() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.getAddressSpace(securityContext, null, null, "a1")); + assertThat(response.getStatus(), is(200)); + AddressSpace data = ((AddressSpace)response.getEntity()); + + assertThat(data, is(a1)); + assertThat(data.getEndpoints().size(), is(a1.getEndpoints().size())); + } + + @Test + public void testGetTableFormat() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.getAddressSpace(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null, "a1")); + assertThat(response.getStatus(), is(200)); + Table data = ((Table)response.getEntity()); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().get(0).getObject().getMetadata().getName(), is(a1.getName())); + } + + @Test + public void testPut() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).putAnnotation("foo", "bar").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(200)); + + assertFalse(addressSpaceApi.listAddressSpaces(null).isEmpty()); + assertThat(addressSpaceApi.listAddressSpaces(null).iterator().next().getAnnotation("foo"), is("bar")); + } + + @Test + public void testPutChangeType() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).setType("type2").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutChangePlan() { + addressSpaceApi.createAddressSpace(a1); + AddressSpace a1Adapted = new AddressSpace.Builder(a1).setPlan("otherplan").build(); + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1Adapted.getName(), a1Adapted)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonMatchingAddressSpaceName() { + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, "xxxxxx", a1)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonExistingAddressSpace() { + Response response = invoke(() -> addressSpaceService.replaceAddressSpace(securityContext, null, a1.getName(), a1)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDelete() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null,"a1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status)response.getEntity()).getStatusCode(), is(200)); + + assertThat(addressSpaceApi.listAddressSpaces(null), hasItem(a2)); + assertThat(addressSpaceApi.listAddressSpaces(null).size(), is(1)); + } + + @Test + public void testDeleteException() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null,"a1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testDeleteNotFound() { + addressSpaceApi.createAddressSpace(a1); + Response response = invoke(() -> addressSpaceService.deleteAddressSpace(securityContext, null,"doesnotexist")); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDeleteAll() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + + Response response = invoke(() -> addressSpaceService.deleteAddressSpaces(securityContext, "myspace")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status)response.getEntity()).getStatusCode(), is(200)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java new file mode 100644 index 0000000000..104901dd3f --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpClusterAddressSpaceServiceTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceList; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.k8s.util.TimeUtil; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpClusterAddressSpaceServiceTest { + private HttpClusterAddressSpaceService addressSpaceService; + private TestAddressSpaceApi addressSpaceApi; + private AddressSpace a1; + private AddressSpace a2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @Before + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + addressSpaceService = new HttpClusterAddressSpaceService(addressSpaceApi, Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + a1 = new AddressSpace.Builder() + .setName("a1") + .setNamespace("myspace") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(123))) + .setEndpointList(Arrays.asList( + new EndpointSpec.Builder() + .setName("messaging") + .setService("messaging") + .build(), + new EndpointSpec.Builder() + .setName("mqtt") + .setService("mqtt") + .build())) + .build(); + + a2 = new AddressSpace.Builder() + .setName("a2") + .setType("type1") + .setPlan("myplan") + .setCreationTimestamp(TimeUtil.formatRfc3339(Instant.ofEpochSecond(12))) + .setNamespace("othernamespace") + .build(); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null)); + assertThat(response.getStatus(), is(200)); + AddressSpaceList data = (AddressSpaceList) response.getEntity(); + + assertThat(data.size(), is(2)); + assertThat(data, hasItem(a1)); + assertThat(data, hasItem(a2)); + } + + @Test + public void testListTableFormat() { + addressSpaceApi.createAddressSpace(a1); + addressSpaceApi.createAddressSpace(a2); + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", null)); + assertThat(response.getStatus(), is(200)); + Table data = (Table) response.getEntity(); + + assertThat(data.getColumnDefinitions().size(), is(6)); + assertThat(data.getRows().size(), is(2)); + } + + @Test + public void testListException() { + addressSpaceApi.throwException = true; + Response response = invoke(() -> addressSpaceService.getAddressSpaceList(securityContext, MediaType.APPLICATION_JSON, null)); + assertThat(response.getStatus(), is(500)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java new file mode 100644 index 0000000000..42fc40cdb6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpNestedAddressServiceTest.java @@ -0,0 +1,268 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.AddressList; +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.v1.Either; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.api.server.TestSchemaProvider; +import io.enmasse.k8s.api.TestAddressApi; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Set; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpNestedAddressServiceTest { + private HttpNestedAddressService addressService; + private TestAddressSpaceApi addressSpaceApi; + private TestAddressApi addressApi; + private Address q1; + private Address a1; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @Before + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + this.addressService = new HttpNestedAddressService(addressSpaceApi, new TestSchemaProvider(), Clock.fixed(Instant.ofEpochSecond(1234), ZoneId.of("UTC"))); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + + AddressSpace addressSpace = new AddressSpace.Builder() + .setName("myspace") + .setType("type1") + .setPlan("myplan") + .build(); + + addressSpaceApi.createAddressSpace(addressSpace); + addressApi = (TestAddressApi) addressSpaceApi.withAddressSpace(addressSpace); + q1 = new Address.Builder() + .setName("q1") + .setAddress("Q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .build(); + a1 = new Address.Builder() + .setName("a1") + .setAddress("A1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("anycast") + .build(); + addressApi.createAddress(q1); + addressApi.createAddress(a1); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", null, null)); + + assertThat(response.getStatus(), is(200)); + AddressList list = (AddressList) response.getEntity(); + + assertThat(list.size(), is(2)); + assertThat(list, hasItem(q1)); + assertThat(list, hasItem(a1)); + } + + @Test + public void testListTableFormat() { + Response response = invoke(() -> addressService.getAddressList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns", "myspace", null, null)); + + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(9)); + assertThat(table.getRows().size(), is(2)); + } + + @Test + public void testGetByAddress() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", "A1", null)); + + assertThat(response.getStatus(), is(200)); + Address address = (Address) response.getEntity(); + + assertThat(address, is(a1)); + } + + @Test + public void testGetByAddressNotFound() { + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace","b1", null)); + + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testListException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.getAddressList(securityContext, null, "ns", "myspace", null, null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGet() { + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(200)); + Address address = (Address) response.getEntity(); + + assertThat(address, is(q1)); + } + + @Test + public void testGetTableFormat() { + Response response = invoke(() -> addressService.getAddress(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(9)); + assertThat(table.getRows().get(0).getObject().getMetadata().getName(), is(q1.getName())); + } + + @Test + public void testGetException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "q1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGetUnknown() { + Response response = invoke(() -> addressService.getAddress(securityContext, null, "ns", "myspace", "doesnotexist")); + assertThat(response.getStatus(), is(404)); + } + + + @Test + public void testCreate() { + Address a2 = new Address.Builder() + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.createAddress(securityContext, new ResteasyUriInfo("http://localhost:8443/", null, "/"), "ns", "myspace", Either.createLeft(a2))); + assertThat(response.getStatus(), is(201)); + + Address a2ns = new Address.Builder(a2).setNamespace("ns").build(); + assertThat(addressApi.listAddresses("ns"), hasItem(a2ns)); + } + + @Test + public void testCreateException() { + addressApi.throwException = true; + Address a2 = new Address.Builder() + .setAddress("a2") + .setPlan("plan1") + .setAddressSpace("myspace") + .setType("anycast") + .build(); + Response response = invoke(() -> addressService.createAddress(securityContext, null, "ns", "myspace", Either.createLeft(a2))); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPut() { + Set
addresses = addressApi.listAddresses("ns"); + assertThat(addresses.isEmpty(), is(false)); + Address address = addresses.iterator().next(); + Address a1 = new Address.Builder(address).setPlan("plan1").build(); + + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", a1.getName(), a1)); + assertThat(response.getStatus(), is(200)); + + Address a2ns = new Address.Builder(a1).setNamespace("ns").build(); + assertThat(addressApi.listAddresses("ns"), hasItem(a2ns)); + } + + @Test + public void testPutNonMatchingAddressName() { + Address a2 = new Address.Builder() + .setName("a2") + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", "xxxxxxx", a2)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNonExistingAddress() { + Address a2 = new Address.Builder() + .setName("a2") + .setAddress("a2") + .setType("anycast") + .setPlan("plan1") + .setAddressSpace("myspace") + .build(); + Response response = invoke(() -> addressService.replaceAddress(securityContext, "ns", "myspace", a2.getName(), a2)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testDelete() { + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "a1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status)response.getEntity()).getStatusCode(), is(200)); + + assertThat(addressApi.listAddresses("ns"), hasItem(q1)); + assertThat(addressApi.listAddresses("ns").size(), is(1)); + } + + @Test + public void testDeleteException() { + addressApi.throwException = true; + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "a1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testDeleteNotFound() { + Response response = invoke(() -> addressService.deleteAddress(securityContext, "ns", "myspace", "notFound")); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void deleteAllAddresses() { + Response response = invoke(() -> addressService.deleteAddresses(securityContext, "unknown")); + assertThat(response.getStatus(), is(200)); + assertThat(addressApi.listAddresses("ns").size(), is(2)); + + response = invoke(() -> addressService.deleteAddresses(securityContext, "ns")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status)response.getEntity()).getStatusCode(), is(200)); + assertThat(addressApi.listAddresses("ns").size(), is(0)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java new file mode 100644 index 0000000000..efe07d7ed6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/HttpUserServiceTest.java @@ -0,0 +1,361 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.api.common.DefaultExceptionMapper; +import io.enmasse.api.common.Status; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.k8s.model.v1beta1.Table; +import io.enmasse.user.model.v1.*; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; + +import org.jboss.resteasy.spi.ResteasyUriInfo; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import java.time.Clock; +import java.util.Arrays; +import java.util.concurrent.Callable; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class HttpUserServiceTest { + private HttpUserService userService; + private TestAddressSpaceApi addressSpaceApi; + private TestUserApi userApi; + private User u1; + private User u2; + private DefaultExceptionMapper exceptionMapper = new DefaultExceptionMapper(); + private SecurityContext securityContext; + + @Before + public void setup() { + addressSpaceApi = new TestAddressSpaceApi(); + userApi = new TestUserApi(); + this.userService = new HttpUserService(addressSpaceApi, userApi, Clock.systemUTC()); + securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + + + + addressSpaceApi.createAddressSpace(new AddressSpace.Builder() + .setName("myspace") + .setNamespace("ns1") + .putAnnotation(AnnotationKeys.REALM_NAME, "r1") + .setType("type1") + .setPlan("myplan") + .build()); + + addressSpaceApi.createAddressSpace(new AddressSpace.Builder() + .setName("otherspace") + .setNamespace("ns2") + .putAnnotation(AnnotationKeys.REALM_NAME, "r2") + .setType("type1") + .setPlan("myplan") + .build()); + u1 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build(), + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("direct*")) + .withOperations(Arrays.asList(Operation.view)) + .build())) + .build()) + .build(); + + u2 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("otherspace.user2") + .withNamespace("ns2") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user2") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("pswd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withOperations(Arrays.asList(Operation.manage)) + .build())) + .build()) + .build(); + + userApi.createUser("r1", u1); + userApi.createUser("r2", u2); + } + + private Response invoke(Callable fn) { + try { + return fn.call(); + } catch (Exception e) { + return exceptionMapper.toResponse(e); + } + } + + @Test + public void testList() { + Response response = invoke(() -> userService.getUserList(securityContext, null, "ns1", null)); + + assertThat(response.getStatus(), is(200)); + UserList list = (UserList) response.getEntity(); + + assertThat(list.getItems().size(), is(1)); + assertThat(list.getItems(), hasItem(u1)); + } + + @Test + public void testListTable() { + Response response = invoke(() -> userService.getUserList(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns1", null)); + + assertThat(response.getStatus(), is(200)); + Table table = (Table) response.getEntity(); + + assertThat(table.getColumnDefinitions().size(), is(4)); + assertThat(table.getRows().size(), is(1)); + } + + @Test + public void testGetByUser() { + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user1")); + + assertThat(response.getStatus(), is(200)); + User user = (User) response.getEntity(); + + assertThat(user, is(u1)); + } + + @Test + public void testGetByUserTable() { + Response response = invoke(() -> userService.getUser(securityContext, "application/json;as=Table;g=meta.k8s.io;v=v1beta1", "ns1", "myspace.user1")); + + Table table = (Table) response.getEntity(); + + assertThat(response.getStatus(), is(200)); + assertThat(table.getColumnDefinitions().size(), is(4)); + assertThat(table.getRows().get(0).getObject().getMetadata().getName(), is(u1.getMetadata().getName())); + } + + @Test + public void testGetByUserNotFound() { + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user2")); + + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testListException() { + userApi.throwException = true; + Response response = invoke(() -> userService.getUserList(securityContext, null, "ns1", null)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testGetException() { + userApi.throwException = true; + Response response = invoke(() -> userService.getUser(securityContext, null, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testCreate() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.createUser(securityContext, new ResteasyUriInfo("http://localhost:8443/", null, "/"), "ns1", u3)); + assertThat(response.getStatus(), is(201)); + + assertThat(userApi.listUsers("ns1").getItems(), hasItem(u3)); + } + + @Test + public void testCreateException() { + userApi.throwException = true; + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.createUser(securityContext, null, "ns1", u3)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPutException() { + userApi.throwException = true; + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void testPutNotMatchingName() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(400)); + } + + @Test + public void testPutNotExists() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user3") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user3") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue1", "topic1")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user3", u3)); + assertThat(response.getStatus(), is(404)); + } + + @Test + public void testPut() { + User u3 = new UserBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("myspace.user1") + .withNamespace("ns1") + .build()) + .withSpec(new UserSpecBuilder() + .withUsername("user1") + .withAuthentication(new UserAuthenticationBuilder() + .withType(UserAuthenticationType.password) + .withPassword("p4ssw0rd") + .build()) + .withAuthorization(Arrays.asList( + new UserAuthorizationBuilder() + .withAddresses(Arrays.asList("queue2", "topic2")) + .withOperations(Arrays.asList(Operation.send, Operation.recv)) + .build())) + .build()) + .build(); + Response response = invoke(() -> userService.replaceUser(securityContext, "ns1", "myspace.user1", u3)); + assertThat(response.getStatus(), is(200)); + } + + @Test + public void testDelete() { + Response response = invoke(() -> userService.deleteUser(securityContext, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(200)); + assertThat(((Status)response.getEntity()).getStatusCode(), is(200)); + + assertTrue(userApi.listUsers("ns1").getItems().isEmpty()); + assertFalse(userApi.listUsers("ns2").getItems().isEmpty()); + } + + @Test + public void testDeleteException() { + userApi.throwException = true; + Response response = invoke(() -> userService.deleteUser(securityContext, "ns1", "myspace.user1")); + assertThat(response.getStatus(), is(500)); + } + + @Test + public void deleteAllUsers() { + Response response = invoke(() -> userService.deleteUsers(securityContext, "unknown")); + assertThat(response.getStatus(), is(200)); + assertThat(userApi.listUsers("ns1").getItems().size(), is(1)); + + response = invoke(() -> userService.deleteUsers(securityContext, "ns1")); + assertThat(response.getStatus(), is(200)); + assertThat(userApi.listUsers("ns1").getItems().size(), is(0)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java new file mode 100644 index 0000000000..617955ae25 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/api-server/src/test/java/io/enmasse/api/v1/http/TestUserApi.java @@ -0,0 +1,106 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.api.v1.http; + +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.User; +import io.enmasse.user.model.v1.UserList; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class TestUserApi implements UserApi { + private final Map> userMap = new HashMap<>(); + public boolean throwException = false; + + @Override + public Optional getUserWithName(String realm, String name) { + if (throwException) { + throw new RuntimeException("exception"); + } + return Optional.ofNullable(userMap.get(realm).get(name)); + } + + @Override + public void createUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + String name = user.getSpec().getUsername(); + userMap.computeIfAbsent(realm, k -> new HashMap<>()).put(name, user); + + } + + @Override + public boolean replaceUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + + String name = user.getSpec().getUsername(); + Map users = userMap.computeIfAbsent(realm, k -> new HashMap<>()); + if (!users.containsKey(name)) { + return false; + } + users.put(name, user); + return true; + } + + @Override + public void deleteUser(String realm, User user) { + if (throwException) { + throw new RuntimeException("exception"); + } + Map m = userMap.get(realm); + if (m != null) { + m.remove(user.getSpec().getUsername()); + } + } + + @Override + public boolean realmExists(String realm) { + return userMap.containsKey(realm); + } + + @Override + public UserList listUsers(String namespace) { + if (throwException) { + throw new RuntimeException("exception"); + } + UserList list = new UserList(); + for (Map users : userMap.values()) { + for (User user : users.values()) { + if (user.getMetadata().getNamespace().equals(namespace)) { + list.getItems().add(user); + } + } + } + return list; + } + + @Override + public UserList listUsersWithLabels(String namespace, Map labels) { + if (throwException) { + throw new RuntimeException("exception"); + } + return listUsers(namespace); + } + + @Override + public void deleteUsers(String namespace) { + if (throwException) { + throw new RuntimeException("exception"); + } + for (Map users : userMap.values()) { + for (User user : new ArrayList<>(users.values())) { + if (user.getMetadata().getNamespace().equals(namespace)) { + users.remove(user.getSpec().getUsername()); + } + } + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java new file mode 100644 index 0000000000..af266fb9f9 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/sasl-delegation/src/test/java/io/enmasse/artemis/sasl_delegation/SaslDelegatingLoginTest.java @@ -0,0 +1,477 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.artemis.sasl_delegation; + +import io.vertx.core.AbstractVerticle; +import io.vertx.core.Handler; +import io.vertx.core.Vertx; +import io.vertx.core.net.NetSocket; +import io.vertx.proton.ProtonConnection; +import io.vertx.proton.ProtonServer; +import io.vertx.proton.ProtonServerOptions; +import io.vertx.proton.sasl.ProtonSaslAuthenticator; +import io.vertx.proton.sasl.impl.ProtonSaslPlainImpl; +import org.apache.activemq.artemis.core.security.Role; +import org.apache.activemq.artemis.core.settings.HierarchicalRepository; +import org.apache.activemq.artemis.core.settings.impl.HierarchicalObjectRepository; +import org.apache.activemq.artemis.spi.core.security.jaas.CertificateCallback; +import org.apache.activemq.artemis.spi.core.security.jaas.RolePrincipal; +import org.apache.activemq.artemis.spi.core.security.jaas.UserPrincipal; +import org.apache.qpid.proton.amqp.Symbol; +import org.apache.qpid.proton.engine.Sasl; +import org.apache.qpid.proton.engine.Transport; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.security.Principal; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.stream.Collectors; +import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.LoginException; +import javax.security.cert.CertificateException; +import javax.security.cert.X509Certificate; + +import static junit.framework.TestCase.assertFalse; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class SaslDelegatingLoginTest { + + private SaslDelegatingLogin loginModule; + private Map options = new HashMap<>(); + private Map validLogins = new HashMap<>(); + private Map> groups = new HashMap<>(); + private int port; + private AuthServer authServer; + private Vertx vertx; + private String verticleId; + private String mechName; + private SaslGroupBasedSecuritySettingsPlugin securityPlugin = new SaslGroupBasedSecuritySettingsPlugin(); + + @Before + public void setup() throws ExecutionException, InterruptedException { + options.clear(); + loginModule = new SaslDelegatingLogin(); + + Map initMap = new HashMap<>(); + initMap.put("name", "test"); + initMap.put("useGroupsFromSaslDelegation", "true"); + securityPlugin.init(initMap); + HierarchicalRepository> repo = new HierarchicalObjectRepository<>(); + repo.setDefault(Collections.emptySet()); + securityPlugin.setSecurityRepository(repo); + + CompletableFuture portFuture = new CompletableFuture<>(); + mechName = ProtonSaslPlainImpl.MECH_NAME; + authServer = new AuthServer(portFuture); + vertx = Vertx.vertx(); + CompletableFuture idFuture = new CompletableFuture<>(); + vertx.deployVerticle(authServer, result -> { + if(result.succeeded()) { + idFuture.complete(result.result()); + } else { + idFuture.completeExceptionally(result.cause()); + } + }); + verticleId = idFuture.get(); + port = portFuture.get(); + options.put("hostname", "127.0.0.1"); + options.put("port", port); + options.put("security_settings", "test"); + options.put("default_roles_authenticated", "all"); + } + + @After + public void tearDown() { + vertx.close(); + } + + // successful credentials login with roles + @Test + public void testSuccessfulCredentialLogin() throws Exception { + Subject subject = new Subject(); + validLogins.put("user", "password"); + groups.put("user", Arrays.asList("send_a","recv_b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + assertTrue("Login unexpectedly failed", loginModule.login()); + assertEquals("No principals should be added until after the commit", 0, subject.getPrincipals().size()); + assertTrue("Commit unexpectedly failed", loginModule.commit()); + assertEquals("Unexpected user principal names", Collections.singleton("user"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + assertEquals("Unexpected role principal names", new HashSet<>(Arrays.asList("send_a","recv_b","all")), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + } + + // unsuccessful credentials login + @Test + public void testUnsuccessfulCredentialLogin() throws Exception { + Subject subject = new Subject(); + validLogins.put("user", "password2"); + groups.put("user", Arrays.asList("a","b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + assertFalse("Login unexpectedly succeeded", loginModule.login()); + assertEquals("No principals should be added until after the commit", 0, subject.getPrincipals().size()); + loginModule.commit(); + assertEquals("Unexpected user principal names", Collections.emptySet(), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + assertEquals("Unexpected role principal names", Collections.emptySet(), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + + } + + // no matching sasl mechanism + @Test + public void testUnsuccessfulCredentialLoginWithBadMechanism() throws Exception { + mechName = "WIBBLE"; + Subject subject = new Subject(); + validLogins.put("user", "password"); + groups.put("user", Arrays.asList("a","b")); + loginModule.initialize(subject, createCallbackHandler("user", "password".toCharArray()), Collections.emptyMap(), options); + try { + loginModule.login(); + fail("Login should not succeed if there are no matching mechanisms"); + } catch (LoginException e) { + // pass + } + } + + // successful cert login + @Test + public void testSuccessfulCertLogin() throws Exception { + + options.put("valid_cert_users", "foo:a,b;bar:c"); + + Subject subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_FOO)), Collections.emptyMap(), options); + assertTrue("Login unexpectedly failed", loginModule.login()); + assertEquals("No principals should be added until after the commit", 0, subject.getPrincipals().size()); + assertTrue("Commit unexpectedly failed", loginModule.commit()); + assertEquals("Unexpected user principal names", Collections.singleton("foo"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + assertEquals("Unexpected role principal names", new HashSet<>(Arrays.asList("a","b")), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + + subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_BAR)), Collections.emptyMap(), options); + assertTrue("Login unexpectedly failed", loginModule.login()); + assertEquals("No principals should be added until after the commit", 0, subject.getPrincipals().size()); + assertTrue("Commit unexpectedly failed", loginModule.commit()); + assertEquals("Unexpected user principal names", Collections.singleton("bar"), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + assertEquals("Unexpected role principal names", Collections.singleton("c"), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + + } + + // unsuccessful cert login + @Test + public void testUnsuccessfulCertLogin() throws Exception { + + Map options = new HashMap<>(); + options.put("valid_cert_users", "foo:a,b;bar:c"); + + Subject subject = new Subject(); + + loginModule.initialize(subject, createCallbackHandler(null, null, generateCertificate(CERT_BANANA)), Collections.emptyMap(), options); + assertFalse("Login unexpectedly succeeded", loginModule.login()); + assertEquals("No principals should be added until after the commit", 0, subject.getPrincipals().size()); + loginModule.commit(); + assertEquals("Unexpected user principal names", Collections.emptySet(), subject.getPrincipals(UserPrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + assertEquals("Unexpected role principal names", Collections.emptySet(), subject.getPrincipals(RolePrincipal.class).stream().map(Principal::getName).collect(Collectors.toSet())); + + } + + + private CallbackHandler createCallbackHandler(String user, char[] password, X509Certificate... certificates) { + return callbacks -> { + for(Callback callback : callbacks) { + if(callback instanceof NameCallback && user != null) { + ((NameCallback)callback).setName(user); + } else if(callback instanceof PasswordCallback && password != null) { + ((PasswordCallback)callback).setPassword(password); + } else if(callback instanceof CertificateCallback && (certificates.length != 0)) { + ((CertificateCallback)callback).setCertificates(certificates); + } + } + }; + } + + private X509Certificate generateCertificate(String cert) throws CertificateException { + return X509Certificate.getInstance(cert.getBytes(StandardCharsets.US_ASCII)); + } + + private static final Symbol ADDRESS_AUTHZ_CAPABILITY = Symbol.valueOf("ADDRESS-AUTHZ"); + private static final Symbol ADDRESS_AUTHZ_PROPERTY = Symbol.valueOf("address-authz"); + + private final class AuthServer extends AbstractVerticle { + + + + private ProtonServer server; + private final CompletableFuture portFuture; + private final SaslAuthenticator saslAuthenticator; + + private AuthServer(CompletableFuture portFuture) { + this.portFuture = portFuture; + saslAuthenticator = new SaslAuthenticator(); + } + + private void connectHandler(ProtonConnection connection) { + String containerId = "auth-server"; + connection.setContainer(containerId); + connection.openHandler(conn -> { + Map props = new HashMap<>(); + Map claims = new HashMap<>(); + claims.put("sub", saslAuthenticator.getUser()); + claims.put("preferred_username", saslAuthenticator.getUser()); + props.put(Symbol.valueOf("authenticated-identity"),claims); + if(connection.getRemoteDesiredCapabilities() != null && Arrays.asList(connection.getRemoteDesiredCapabilities()).contains(ADDRESS_AUTHZ_CAPABILITY)) { + connection.setOfferedCapabilities(new Symbol[] { ADDRESS_AUTHZ_CAPABILITY }); + if(groups.containsKey(saslAuthenticator.getUser())) { + props.put(ADDRESS_AUTHZ_PROPERTY, getPermissionsFromGroups(groups.get(saslAuthenticator.getUser()))); + } + } + + if(groups.containsKey(saslAuthenticator.getUser())) { + props.put(Symbol.valueOf("groups"), groups.get(saslAuthenticator.getUser())); + } + connection.setProperties(props); + connection.open(); + connection.close(); + }).closeHandler(conn -> { + connection.close(); + connection.disconnect(); + }).disconnectHandler(protonConnection -> { + connection.disconnect(); + }); + + } + + Map getPermissionsFromGroups(List groups) { + Map> authMap = new HashMap<>(); + for(String group : groups) { + String[] parts = group.split("_", 2); + if(parts[0] != null) { + Set permissions = authMap.computeIfAbsent(parts[1], a -> new HashSet<>()); + permissions.add(parts[0]); + } + } + return authMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toArray(new String[e.getValue().size()]))); + } + + + @Override + public void start() { + ProtonServerOptions options = new ProtonServerOptions(); + + server = ProtonServer.create(vertx, options); + server.saslAuthenticatorFactory(() -> saslAuthenticator); + server.connectHandler(this::connectHandler); + + server.listen(0, "127.0.0.1", event -> { + if(event.failed()) { + portFuture.completeExceptionally(event.cause()); + } else { + portFuture.complete(server.actualPort()); + } + }); + } + + @Override + public void stop() { + if (server != null) { + server.close(); + } + } + + } + + private static final String CERT_FOO = "-----BEGIN CERTIFICATE-----\n" + + "MIIFDjCCAvagAwIBAgIJAJjPI7TtVOCpMA0GCSqGSIb3DQEBBQUAMA4xDDAKBgNV\n" + + "BAMTA2ZvbzAeFw0xNzEwMTIwODU4NTNaFw0xODEwMTIwODU4NTNaMA4xDDAKBgNV\n" + + "BAMTA2ZvbzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALsasR9eE/77\n" + + "qmt1Gjz+/wJzu3V9pgde1iBuwoXHKGZyayMHLucnKXVF3o7DEk0R/1m3hKh5QoNV\n" + + "BHgiUzfjxKFxk85F00G/B1FkDXGjxqUz84hsSnOZS7917AdVHQ4FNfbUIeWgkRe3\n" + + "EqK/C3QiyVPr0Uou9jU+YLxOItB22KXVKO3gtBaZfaj8MpzPi8XOxesfpTB+1Fws\n" + + "336aYeeDxH78t05EnwqEd+bX7BPs+0DsReARKVi1v9YNRUX2AAQDBGqLKz39Eg0M\n" + + "0BaiRLv7O4i0DEJlGYC05P8L5Nb8JwZ8XQV0jlZrqNiqSqL2Glt+m4LkBLFwDfZz\n" + + "Q95FVeSSD4AlUB1eHnv41lT3SDOvLV8e6c222MDuC0V7eKDdCWVNlzQpwMyZKeBR\n" + + "HOl5IRjVAi2+JEE7YyzgIn68ZY2YLOBzoUKawPeThak6hJEzDaXzpUVJtKH9LnIW\n" + + "Yyt+K+c9/Sm4Cs95tCALA005r4GSypcTIdAdOpO9UcS4ObeKRhdCFHgkNitkw4i0\n" + + "X2i80y7lzoEV64ZbzMpqq0jWN2LzkHNU5zl5AoL7s8pFMSoQruOEOhIq3yHlDJ9W\n" + + "0cGgzz2XvTQgXtCi4H/pVSXo7ojLffGW5CP4+k8iFAO4uIsqAUKRG2kCSNv3KTMj\n" + + "f6d00flOm6S2+zIBCSz8UF8RmUknf6Y/AgMBAAGjbzBtMB0GA1UdDgQWBBTlJ705\n" + + "R48NTZMfuQyn9D4TeEeDvjA+BgNVHSMENzA1gBTlJ705R48NTZMfuQyn9D4TeEeD\n" + + "vqESpBAwDjEMMAoGA1UEAxMDZm9vggkAmM8jtO1U4KkwDAYDVR0TBAUwAwEB/zAN\n" + + "BgkqhkiG9w0BAQUFAAOCAgEAB0Xamx2uhf7kixCyS2RVGubxTjgu0r+jz9fk6iPW\n" + + "PzzAAb364NkgtWqOg4yOD88VjtRy1meNhOYs/lZ4Eo7STBpsb+zNF1fB9Yg9cNqy\n" + + "A3W6Wjuon7pMWXZDmXFlehPSibbO2tnaiBuBe5j6EL5BWrtHHWlvALUrIG9aB9sI\n" + + "oWRg2WK9GJcKQ90huM8z7ZeA8h0tjEhB5UXc9eAtNmsXnIQ1aWq2mb3/Fg9ALrkl\n" + + "9cHXkdGRty1INXi0b3NSa2lK7m0Rt1iWRlIv5Q9DNAGADx6azrWdbSm/DppOQCrm\n" + + "0KgdzpESIt/ZcibWYVkCOkY3KAl3MmgFc/ezOmYhuBMPzxxi+2omt+B1AFaubsRc\n" + + "65FBKjIzLEB+SuNAgfrk1kdttqMNT3JyY7hYLoMM/wryAZ7pxMCJ4ylJ85LTuoFM\n" + + "l9EPPXJI7cnplgsifDwAI0VfCu7VNIYKMUSk5UhJdJIQMPajThjg4EyXtoETcOZR\n" + + "TIN0PGC2W5n7CFO5WLNsQcWi0Rwq/RVy1y6EDYsZBqwvjUTWw9CkLXtJo1Naizb3\n" + + "qS7WskaD+kciXQ/t/aAXCd1zBZU85tjbaiMzAln8LG5jHChGi3lfNR/V24KxmNyY\n" + + "9KoXswCfB65shysC8t9FaJ4DFtcZxxY5jj9DNuzTiIYvdkpHZG+MYjesQDrxX/cp\n" + + "W0s=\n" + + "-----END CERTIFICATE-----\n"; + + private static final String CERT_BAR = "-----BEGIN CERTIFICATE-----\n" + + "MIIFDjCCAvagAwIBAgIJAIoMqv3u2Y9OMA0GCSqGSIb3DQEBBQUAMA4xDDAKBgNV\n" + + "BAMTA2JhcjAeFw0xNzEwMTIwODU5MTNaFw0xODEwMTIwODU5MTNaMA4xDDAKBgNV\n" + + "BAMTA2JhcjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKjew9A5JoJ/\n" + + "PC7fQsUokG9jE+PVwpiXIFXF3dR8pARnMyjq8YXIV66wFKmcRQlM0WvOYBbxVfFT\n" + + "vjo3ASNsoaAt6HEDeCI6BwfJjXnnw3ko7o5TSPVmgS39G9vjGqZEGmbmM/Elrnc/\n" + + "VML5+wGw9g8I6YKFRfs70QxL7BDlO4YSbEki7lppyYSWGMGW7YrByCpgZaO21e5V\n" + + "CyTlREAKbcnchqtIheDjra2syna5G3L7OYGI4k/Y1D1VyShooV2FsJFB6M4TYaGO\n" + + "/T5ewEStMU+E2O79iHWsVUj/Z2gnlnbzPvk6Sy/wWAUP14B3WUPHyzBynRAwYA7u\n" + + "zHodcMLcpcHjBRZGnqEvuSB2muycRrLDtgIlvKxVZ6Da1Y75YGdgRGdxedeuhQky\n" + + "TTiGwctq6FVHH9uV4MTdVNe5eE6pzkuuSBX+X8Hv3LsbqKW0wMvyyZZtTlD19tTe\n" + + "QhJsacpIbCvm/QP+JMOKZtIMaSRdRCj11EtA5bbHJKvHilt1rpufXL9OHnqSr3lp\n" + + "vUiNWq9sKqvxkRvZbKVUVRrjDMA8oOmhMc0llAHunC1m84fwI/SHZ6l6ceqAmWWc\n" + + "JlSLT6vsrfzavibJjVJnXwIsr3Jy3itjpudvFbEz7mB30i9YCjr8OXZr7/x1KYU8\n" + + "SePtV5ZYF3COFE9PomWHwq76VBgtcrKbAgMBAAGjbzBtMB0GA1UdDgQWBBSHMfZS\n" + + "fov+3UCqlB+9oKmDr32SiDA+BgNVHSMENzA1gBSHMfZSfov+3UCqlB+9oKmDr32S\n" + + "iKESpBAwDjEMMAoGA1UEAxMDYmFyggkAigyq/e7Zj04wDAYDVR0TBAUwAwEB/zAN\n" + + "BgkqhkiG9w0BAQUFAAOCAgEAPBq/1p7l0u3vyBAjnmuBPvMEg7UaaNxcrDbl1gf0\n" + + "DpxprCJifZWYp4vsPdCE7zLXyJNfR1Cn0BKJ1hoAGU53Q689KSqRMgRb/lyU1y7s\n" + + "m7nphXR39kTN06YPkQpPs4WGKQc79FIeIxxWBYJzi3wkK2nBAyRXswbtDfVS46j1\n" + + "+kCYENiXFoIQboE4HjZ0G3Wh0Ct8au4oTFiTZ1XyxeKri7TykOwvJRIh3m6nByQi\n" + + "UPYthIWcrcZDk6c0kTOFapS0ufQ7AeynFHiveIT4CL75jdME9Ll/3Re/EgHkOJ/1\n" + + "dElESlcnjdkRzHyHCdXWnDs0gfWj1F56GGUFh0HhrIABl0Uzd/ukCHDzUOLTGRQg\n" + + "eJ3eFLMgjY3oDpbFgEupBRP266e/XbnmzXhDMdguL7+Pp9gka5tA7a67SL05FG0Z\n" + + "nWU5XXLLr+jxh7hIIdpVe+TZxdVMD0znn68MxOz8liJcGmdO+9Gnwg3FLZR0e02L\n" + + "iehS0b/oddF5xMUyDdwt/dIyU1gOc1ozLld1U7RTZIKa2Y0M65vD/sMjfsWku1Kf\n" + + "xaFEMI94vAWa9WyzveDrvFCyQNfqgmdiyh7t81TTMbFMvaGY+VUUT5UsKZX5FPFS\n" + + "AiYa8rwmnlKLVoNC6s9WSrlaPXfpWvucT4YE3L7RJ/WuP8t2oXgLtR/ATjhTnveg\n" + + "d4s=\n" + + "-----END CERTIFICATE-----\n"; + + private static final String CERT_BANANA = "-----BEGIN CERTIFICATE-----\n" + + "MIIFFzCCAv+gAwIBAgIJAOk9W2pKKYDVMA0GCSqGSIb3DQEBBQUAMBExDzANBgNV\n" + + "BAMTBmJhbmFuYTAeFw0xNzEwMTIwODU5MzBaFw0xODEwMTIwODU5MzBaMBExDzAN\n" + + "BgNVBAMTBmJhbmFuYTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJ5L\n" + + "SDzBElCjuFf7jXYaOLDPL3ifeuM01k56oHdBjwmRBPLc/c0Tz5609Q9ODn5PglnZ\n" + + "zhpGayGh/XfJ5iQtP20xKd5zkP/+RHKI9SU/r682nmkLW7KDWfizKP7pmUuHkXz7\n" + + "VxtBTLtQLdEfquKUlPibxKfbGARmRaLv6i1o9nh2z4QotFB++ionlUicmGKbC6aR\n" + + "boCaEydDYP/vvftwcKucfRRKrxJqQ4dlBQ3wwTaJ5eqjXTHTHn0d5gg36xAcUxwr\n" + + "azc7TMeRd3QYhB7hOaJSh5H24X9khrzWSawho6eKk4QrvlXvzGV9Q2QDpsi4jYv5\n" + + "K/+jHgCukLsLW2aRRkFbKbCE4ghuVyOmfedUSj06/obVg+W3XW3dndwRHmc21M5q\n" + + "ECpZqBsitNWj7vaunCgIgBzJjL1IdcMA4gaEt8M0sslPyOrZUNMj1LL+izoN7K7G\n" + + "aD/RqepNEBU5OKVNmZgFyXgZWADIrpPQxGVgrEY0j9Tagw5GgeHvdJNNIeGcVbci\n" + + "/8osHlH4us2/lphUXPrwIAgh4dVIygKhkH6aSRbrq84urqJ57Zghnz9XPDosgdRY\n" + + "l0fMvReMX9J9Tjk3mWfTYlmul19I4LTrWRS1kHlS6KjUweQ/QaMqo1kPD4Kae0SA\n" + + "lLAeDq4Jntj/b1v29kIkhNdCbm1jMUIKhgLaL9l3AgMBAAGjcjBwMB0GA1UdDgQW\n" + + "BBRBDIZnqyn/lKPhosxwYC6eRnSy7DBBBgNVHSMEOjA4gBRBDIZnqyn/lKPhosxw\n" + + "YC6eRnSy7KEVpBMwETEPMA0GA1UEAxMGYmFuYW5hggkA6T1bakopgNUwDAYDVR0T\n" + + "BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAgEAMABQyp8wXQnO16+2hSFY2EdO0UGi\n" + + "A/1O6NwiVTMt9A6Ltjk5nQ5t4cgonaHBiMa25HeQ6BJ2iAKGvmPr9R5S9XIjD2BI\n" + + "3ov02bglUCD40EJE1krFJOj3elCBjN6991OOzvWOK38FTlpJTXI9FzTxIqIcjlGJ\n" + + "SB4dbpnJH7Nat3T73n0MrHguGx7SQ+3MS5wvy3ZWO5Eg7Pu1pATfHgQHUwf+uv1T\n" + + "FDD8Ulct/hAGuNvRlRv1nkzplXCM9nY9aW3316Rg1HV/P5aBKaW23Sa6pJlIDEwa\n" + + "whNw8pQlTtahgM36K7AZbGSDBrkIN5+cJd93Orbu4dg2RCVPxLi2/yvNP0t4lBrW\n" + + "5e/5Ye/kLt23Z6Tv/d3BhbM3RwgUVmsTbdjUDChed5u7lwWf77LXW7ptEbDC3Vlk\n" + + "TOeCRsgFzV7OzXEsSlpqXTsR6+Q8a9ffg5vaaaWcwqUQIBfPdFFLmYvDpcJQXOc6\n" + + "rnKe6CnAfpE17tczCQ0TBHp4MkPyuO9WfoCb0+5Lw+O4Ny59NKLKV1zFHSELzaKt\n" + + "4msENSPdy+6YxKMJUlWMe+Z26aj8FCGuFoC17kzXlw9QP/aYPBhh2E0diOpgfs1R\n" + + "0XZg9N4M+d9oJFjK43wdDjUcPdjpfqbrc5IzBY01j7V/r+zFTn+yuLIc8B4MF6Dn\n" + + "DQkhI+BdvtzGTwE=\n" + + "-----END CERTIFICATE-----\n"; + + private class SaslAuthenticator implements ProtonSaslAuthenticator { + + private Sasl sasl; + private String user; + private boolean succeeded; + + private SaslAuthenticator() { + } + + @Override + public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) { + sasl = transport.sasl(); + sasl.server(); + sasl.allowSkip(false); + + sasl.setMechanisms(mechName); + + } + + @Override + public void process(Handler completionHandler) { + String[] remoteMechanisms = sasl.getRemoteMechanisms(); + + if (remoteMechanisms.length > 0) { + byte[] response; + if(sasl.pending()>0) { + response = new byte[sasl.pending()]; + sasl.recv(response, 0, response.length); + } else { + response = new byte[0]; + } + + int authzidNullPosition = findNullPosition(response, 0); + if (authzidNullPosition < 0) { + throw new IllegalArgumentException("Invalid PLAIN encoding, authzid null terminator not found"); + } + + int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); + if (authcidNullPosition < 0) { + throw new IllegalArgumentException("Invalid PLAIN encoding, authcid null terminator not found"); + } + + String username = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, StandardCharsets.UTF_8); + int passwordLen = response.length - authcidNullPosition - 1; + String password = new String(response, authcidNullPosition + 1, passwordLen, StandardCharsets.UTF_8); + + if(validLogins.containsKey(username)) { + if(password.equals(validLogins.get(username))) { + this.user = username; + succeeded = true; + sasl.done(Sasl.SaslOutcome.PN_SASL_OK); + } else { + sasl.done(Sasl.SaslOutcome.PN_SASL_AUTH); + } + } else { + sasl.done(Sasl.SaslOutcome.PN_SASL_AUTH); + } + completionHandler.handle(true); + } else { + completionHandler.handle(false); + } + } + + private int findNullPosition(byte[] response, int startPosition) { + int position = startPosition; + while (position < response.length) { + if (response[position] == (byte) 0) { + return position; + } + position++; + } + return -1; + } + + @Override + public boolean succeeded() { + return succeeded; + } + + public String getUser() { + return user; + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java new file mode 100644 index 0000000000..f77fdd4f72 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/QueueDrainerTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Host; +import io.enmasse.amqp.Artemis; +import io.enmasse.amqp.PubSubBroker; +import io.vertx.core.Vertx; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(VertxUnitRunner.class) +public class QueueDrainerTest { + private QueueDrainer client; + private PubSubBroker fromServer; + private PubSubBroker toServer; + private TestManagementServer localBroker; + private Host from; + private Host to; + private Vertx vertx; + + + @Before + public void setup(TestContext context) throws Exception { + vertx = Vertx.vertx(); + fromServer = new PubSubBroker("fromServer"); + toServer = new PubSubBroker("toServer"); + Async async = context.async(2); + vertx.deployVerticle(fromServer, ar -> { + if (ar.succeeded()) { + async.countDown(); + } else { + context.fail(ar.cause()); + } + }); + + vertx.deployVerticle(toServer, ar -> { + if (ar.succeeded()) { + async.countDown(); + } else { + context.fail(ar.cause()); + } + }); + async.awaitSuccess(30_000); + from = TestUtil.createHost("127.0.0.1", fromServer.port()); + to = TestUtil.createHost("127.0.0.1", toServer.port()); + localBroker = new TestManagementServer(); + + client = new QueueDrainer(Vertx.vertx(), from, (vertx, clientOptions, endpoint) -> new Artemis(localBroker), new ProtonClientOptions(), Optional.empty()); + } + + @Test + public void testDrain() throws Exception { + sendMessages(fromServer, "myqueue", "testfrom", 100); + sendMessages(fromServer, "queue2", "q2from", 10); + sendMessages(toServer, "myqueue","testto", 100); + sendMessages(toServer, "queue2", "q2to", 1); + + System.out.println("Starting drain"); + + localBroker.setHandler(message -> { + Map props = message.getApplicationProperties().getValue(); + Message response = Proton.message(); + String resourceName = (String) props.get("_AMQ_ResourceName"); + if ("broker".equals(resourceName) && + "getQueueNames".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[[\"myqueue\"],[\"queue2\"]]")); + } else if ("queue.myqueue".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("myqueue") + "]")); + } else if ("queue.queue2".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("queue2") + "]")); + } else { + response.setBody(new AmqpValue("[]")); + } + return response; + }); + + client.drainMessages(to.amqpEndpoint(), ""); + assertThat(toServer.numMessages("myqueue"), is(200)); + assertThat(toServer.numMessages("queue2"), is(11)); + + assertReceive(toServer, "myqueue", "testto", 100); + assertReceive(toServer, "myqueue", "testfrom", 100); + assertReceive(toServer, "queue2", "q2to", 1); + assertReceive(toServer, "queue2", "q2from", 10); + + System.out.println("Checking shutdown"); + } + + private static void sendMessages(PubSubBroker broker, String address, String prefix, int numMessages) throws IOException, InterruptedException { + List messages = IntStream.range(0, numMessages) + .mapToObj(i -> prefix + i) + .collect(Collectors.toList()); + broker.sendMessages(address, messages); + } + + private static void assertReceive(PubSubBroker broker, String address, String prefix, int numMessages) throws IOException, InterruptedException { + List messages = broker.recvMessages(address, numMessages); + for (int i = 0; i < numMessages; i++) { + String actualBody = messages.get(i); + String expectedBody = prefix + i; + assertThat(actualBody, is(expectedBody)); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java new file mode 100644 index 0000000000..addc5f34c6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestManagementServer.java @@ -0,0 +1,53 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package enmasse.broker.prestop; + +import io.enmasse.amqp.SyncRequestClient; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.message.Message; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +class TestManagementServer implements SyncRequestClient { + + private Handler handler; + + @Override + public void connect(String host, int port, ProtonClientOptions clientOptions, String address, CompletableFuture connectedPromise) { + + } + + @Override + public String getRemoteContainer() { + return null; + } + + @Override + public String getReplyTo() { + return "tome"; + } + + @Override + public void close() { + + } + + public void setHandler(Handler handler) { + this.handler = handler; + } + + @Override + public Message request(Message message, long timeout, TimeUnit timeUnit) { + return handler.handle(message); + } + + public interface Handler { + Message handle(Message message); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java new file mode 100644 index 0000000000..d7c3b82e5d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TestSubscriber.java @@ -0,0 +1,92 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Endpoint; +import io.vertx.core.Vertx; +import io.vertx.proton.ProtonClient; +import io.vertx.proton.ProtonConnection; +import io.vertx.proton.ProtonLinkOptions; +import io.vertx.proton.ProtonReceiver; +import org.apache.qpid.proton.amqp.Symbol; +import org.apache.qpid.proton.amqp.messaging.Source; +import org.apache.qpid.proton.amqp.messaging.TerminusDurability; +import org.apache.qpid.proton.message.Message; + +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.zip.ZipFile; + +public class TestSubscriber implements AutoCloseable { + private final Vertx vertx = Vertx.vertx(); + private volatile ProtonConnection connection; + + private final BlockingQueue received = new LinkedBlockingQueue<>(); + + public void subscribe(Endpoint endpoint, String address) throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + String containerId = "test-subscriber"; + ProtonClient client = ProtonClient.create(vertx); + client.connect(endpoint.hostname(), endpoint.port(), connection -> { + if (connection.succeeded()) { + ProtonConnection conn = connection.result(); + conn.setContainer(containerId); + conn.closeHandler(res -> { + System.out.println("CLIENT cONN cLOSED"); + }); + this.connection = conn; + System.out.println("Connected: " + connection.result().getRemoteContainer()); + Source source = new Source(); + source.setAddress(address); + source.setCapabilities(Symbol.getSymbol("topic")); + source.setDurable(TerminusDurability.UNSETTLED_STATE); + ProtonReceiver receiver = conn.createReceiver(address, new ProtonLinkOptions().setLinkName(containerId)); + receiver.setSource(source); + receiver.openHandler(res -> { + if (res.succeeded()) { + System.out.println("Opened receiver"); + latch.countDown(); + } else { + System.out.println("Failed opening received: " + res.cause().getMessage()); + } + }); + receiver.closeHandler(res -> { + System.out.println("CLIENT CLOSED"); + conn.close(); + }); + receiver.handler((delivery, message) -> { + System.out.println("GOT MESSAGE"); + received.add(message); + }); + receiver.open(); + conn.open(); + } else { + System.out.println("Connection failed: " + connection.cause().getMessage()); + } + }); + latch.await(1, TimeUnit.MINUTES); + } + + public void unsubscribe() { + vertx.runOnContext(v -> connection.close()); + } + + @Override + public void close() throws Exception { + unsubscribe(); + vertx.close(); + } + + + public Message receiveMessage(long timeout, TimeUnit timeUnit) throws InterruptedException { + return received.poll(timeout, timeUnit); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java new file mode 100644 index 0000000000..ee31d07d38 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/broker-plugin/shutdown-hook/src/test/java/enmasse/broker/prestop/TopicMigratorTest.java @@ -0,0 +1,120 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.prestop; + +import enmasse.discovery.Endpoint; +import enmasse.discovery.Host; +import io.enmasse.amqp.Artemis; +import io.enmasse.amqp.PubSubBroker; +import io.vertx.core.Vertx; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import io.vertx.proton.ProtonClientOptions; +import org.apache.qpid.proton.Proton; +import org.apache.qpid.proton.amqp.messaging.AmqpValue; +import org.apache.qpid.proton.message.Message; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(VertxUnitRunner.class) +public class TopicMigratorTest { + private Host from; + private Host to; + private PubSubBroker fromServer; + private PubSubBroker toServer; + private TestSubscriber subscriber; + private TestPublisher publisher; + private TestManagementServer localBroker; + private Vertx vertx; + + @Before + public void setup(TestContext context) throws Exception { + vertx = Vertx.vertx(); + subscriber = new TestSubscriber(); + publisher = new TestPublisher(); + fromServer = new PubSubBroker("fromServer"); + toServer = new PubSubBroker("toServer"); + Async async = context.async(2); + vertx.deployVerticle(fromServer, ar -> { + if (ar.succeeded()) { + async.countDown(); + } else { + context.fail(ar.cause()); + } + }); + + vertx.deployVerticle(toServer, ar -> { + if (ar.succeeded()) { + async.countDown(); + } else { + context.fail(ar.cause()); + } + }); + async.awaitSuccess(30_000); + localBroker = new TestManagementServer(); + from = TestUtil.createHost("127.0.0.1", fromServer.port()); + to = TestUtil.createHost("127.0.0.1", toServer.port()); + } + + @After + public void teardown() throws Exception { + subscriber.close(); + publisher.close(); + vertx.close(); + } + + @Test + @Ignore + public void testMigrator() throws Exception { + System.out.println("Attempting to subscribe"); + subscriber.subscribe(from.amqpEndpoint(), "mytopic"); + subscriber.unsubscribe(); + + System.out.println("Publishing message"); + publisher.publish(from.amqpEndpoint(), "mytopic", "hello, world"); + + System.out.println("Done publishing"); + TopicMigrator migrator = new TopicMigrator(Vertx.vertx(), from, new Endpoint("messaging.example.com", 5672), (vertx, clientOptions, endpoint) -> new Artemis(localBroker), new ProtonClientOptions()); + + localBroker.setHandler(message -> { + Map props = message.getApplicationProperties().getValue(); + Message response = Proton.message(); + String resourceName = (String) props.get("_AMQ_ResourceName"); + if ("broker".equals(resourceName) && + "getQueueNames".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[[\"mytopic\"]]")); + } else if ("queue.mytopic".equals(resourceName) && + "getAddress".equals(props.get("_AMQ_OperationName"))) { + response.setBody(new AmqpValue("[\"mytopic\"]")); + } else if ("queue.mytopic".equals(resourceName) && + "messageCount".equals(props.get("_AMQ_Attribute"))) { + response.setBody(new AmqpValue("[" + fromServer.numMessages("mytopic") + "]")); + } else { + System.out.println("Props: " + props); + response.setBody(new AmqpValue("[]")); + } + return response; + }); + + System.out.println("Starting migrator"); + migrator.migrate(Collections.singleton(to)); + + subscriber.subscribe(to.amqpEndpoint(), "mytopic"); + Message message = subscriber.receiveMessage(1, TimeUnit.MINUTES); + assertThat(((AmqpValue)message.getBody()).getValue(), is("hello, world")); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java new file mode 100644 index 0000000000..7a26c899d0 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/discovery-lib/src/test/java/enmasse/discovery/DiscoveryTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package enmasse.discovery; + +import io.fabric8.kubernetes.api.model.*; +import io.fabric8.kubernetes.client.KubernetesClient; +import org.junit.jupiter.api.Test; + +import java.util.*; +import java.util.concurrent.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; + +public class DiscoveryTest { + + @Test + public void testDiscovery() throws Exception { + Map expectedLabelFilter = Collections.singletonMap("my", "key"); + Map expectedAnnotationFilter = Collections.singletonMap("my", "annotation"); + CompletableFuture> changedHosts = new CompletableFuture<>(); + KubernetesClient kubeClient = mock(KubernetesClient.class); + + System.out.println("Deploying server verticle"); + DiscoveryClient client = new DiscoveryClient(kubeClient, expectedLabelFilter, expectedAnnotationFilter, null); + client.addListener(changedHosts::complete); + + System.out.println("Waiting for subscriber to be created"); + client.resourcesUpdated(Collections.singletonList(createPod("False", "Pending"))); + + System.out.println("Sending second response"); + client.resourcesUpdated(Collections.singletonList(createPod("False", "Running"))); + try { + changedHosts.get(10, TimeUnit.SECONDS); + fail("Ready must be true before returning host"); + } catch (TimeoutException ignored) { + } + + System.out.println("Sending third response"); + client.resourcesUpdated(Collections.singletonList(createPod("True", "Running"))); + try { + Set actual = changedHosts.get(2, TimeUnit.MINUTES); + assertEquals(actual.size(), 1); + Host actualHost = actual.iterator().next(); + assertEquals(actualHost.getHostname(), "10.0.0.1"); + } catch (Exception e) { + fail("Unexpected exception" + e.getMessage()); + e.printStackTrace(); + } + } + + public enmasse.discovery.Pod createPod(String ready, String phase) { + return new enmasse.discovery.Pod(new PodBuilder() + .editOrNewMetadata() + .withName("mypod") + .withLabels(Collections.singletonMap("my", "key")) + .withAnnotations(Collections.singletonMap("my", "annotation")) + .endMetadata() + .editOrNewStatus() + .withPhase(phase) + .withPodIP("10.0.0.1") + .addNewCondition() + .withType("Ready") + .withStatus(ready) + .endCondition() + .endStatus() + .withNewSpec() + .addToContainers(new ContainerBuilder() + .withName("c") + .addToPorts(new ContainerPortBuilder() + .withName("http") + .withContainerPort(1234) + .build()) + .build()) + .endSpec() + .build()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java new file mode 100644 index 0000000000..65c466674a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/AddressSpacePlanApiTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.admin.model.v1.AddressSpacePlan; +import io.enmasse.admin.model.v1.AddressSpacePlanList; +import io.enmasse.admin.model.v1.AdminCrd; +import io.enmasse.admin.model.v1.DoneableAddressSpacePlan; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Rule; +import org.junit.Test; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; + + +public class AddressSpacePlanApiTest { + + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + + @Test + public void testNotifiesExisting() throws Exception { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + CustomResourceDefinition crd = AdminCrd.addressSpacePlans(); + AddressSpacePlanApi addressSpacePlanApi = new KubeAddressSpacePlanApi(client, client.getNamespace(), crd); + + client.customResources(crd, AddressSpacePlan.class, AddressSpacePlanList.class, DoneableAddressSpacePlan.class) + .createNew() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace(client.getNamespace()) + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("p1", "p2")) + .done(); + + CompletableFuture> promise = new CompletableFuture<>(); + try (Watch watch = addressSpacePlanApi.watchAddressSpacePlans(items -> { + if (!items.isEmpty()) { + promise.complete(items); + } + }, Duration.ofMinutes(1))) { + List list = promise.get(30, TimeUnit.SECONDS); + assertEquals(1, list.size()); + assertEquals("plan1", list.get(0).getMetadata().getName()); + } + } + + @Test + public void testNotifiesCreated() throws Exception { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + CustomResourceDefinition crd = AdminCrd.addressSpacePlans(); + AddressSpacePlanApi addressSpacePlanApi = new KubeAddressSpacePlanApi(client, client.getNamespace(), crd); + + CompletableFuture> promise = new CompletableFuture<>(); + try (Watch watch = addressSpacePlanApi.watchAddressSpacePlans(items -> { + if (!items.isEmpty()) { + promise.complete(items); + } + + }, Duration.ofSeconds(2))) { + client.customResources(crd, AddressSpacePlan.class, AddressSpacePlanList.class, DoneableAddressSpacePlan.class) + .createNew() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .withNamespace(client.getNamespace()) + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("p1", "p2")) + .done(); + + List list = promise.get(30, TimeUnit.SECONDS); + assertEquals(1, list.size()); + assertEquals("plan1", list.get(0).getMetadata().getName()); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java new file mode 100644 index 0000000000..42017a257e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressApiTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.Address; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.util.Optional; +import java.util.UUID; + +import static org.junit.Assert.*; + +public class ConfigMapAddressApiTest { + private static final String ADDRESS = "myaddress"; + private static final String ADDRESS_TYPE = "mytype"; + private static final String ADDRESS_PLAN = "myplan"; + private static final String ADDRESS_SPACE_NAMESPACE = "myproject"; + private static final String ADDRESS_SPACE = "myspace"; + private static final String ADDRESS_NAME = String.format("%s.%s", ADDRESS_SPACE, ADDRESS); + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + private AddressApi api; + + @Before + public void setUp() { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + api = new ConfigMapAddressApi(client, UUID.randomUUID().toString()); + } + + @Test + public void create() { + Address address = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + api.createAddress(address); + Optional
readAddress = api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + assertTrue(readAddress.isPresent()); + Address read = readAddress.get(); + + assertEquals(ADDRESS, read.getAddress()); + assertEquals(ADDRESS_SPACE, read.getAddressSpace()); + assertEquals(ADDRESS_NAME, read.getName()); + assertEquals(ADDRESS_TYPE, read.getType()); + assertEquals(ADDRESS_PLAN, read.getPlan()); + } + + @Test + public void replace() { + Address adddress = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + final String annotationKey = "myannotation"; + String annotationValue = "value"; + Address update = new Address.Builder(adddress).putAnnotation(annotationKey, annotationValue).build(); + + api.createAddress(adddress); + assertTrue(api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).isPresent()); + + boolean replaced = api.replaceAddress(update); + assertTrue(replaced); + + Address read = api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).get(); + + assertEquals(ADDRESS_NAME, read.getName()); + assertEquals(annotationValue, read.getAnnotation(annotationKey)); + } + + @Test + public void replaceNotFound() { + Address address = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + boolean replaced = api.replaceAddress(address); + assertFalse(replaced); + } + + @Test + public void delete() { + Address space = createAddress(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME); + + api.createAddress(space); + + boolean deleted = api.deleteAddress(space); + assertTrue(deleted); + + assertFalse(api.getAddressWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_NAME).isPresent()); + + boolean deletedAgain = api.deleteAddress(space); + assertFalse(deletedAgain); + } + + private Address createAddress(String namespace, String name) { + return new Address.Builder() + .setName(name) + .setNamespace(namespace) + .setAddress(ADDRESS) + .setAddressSpace(ADDRESS_SPACE) + .setType(ADDRESS_TYPE) + .setPlan(ADDRESS_PLAN) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java new file mode 100644 index 0000000000..990153afd3 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ConfigMapAddressSpaceApiTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.AddressSpace; +import io.fabric8.openshift.client.NamespacedOpenShiftClient; +import io.fabric8.openshift.client.server.mock.OpenShiftServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.*; + +/** + * The mock server does not emulate behaviour with respect to resourceVersion. + */ +public class ConfigMapAddressSpaceApiTest { + private static final String ADDRESS_SPACE_NAME = "myspace"; + private static final String ADDRESS_SPACE_TYPE = "mytype"; + private static final String ADDRESS_SPACE_PLAN = "myplan"; + private static final String ADDRESS_SPACE_NAMESPACE = "myproject"; + @Rule + public OpenShiftServer openShiftServer = new OpenShiftServer(false, true); + private AddressSpaceApi api; + + @Before + public void setUp() { + NamespacedOpenShiftClient client = openShiftServer.getOpenshiftClient(); + api = new ConfigMapAddressSpaceApi(client); + } + + @Test + public void create() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + api.createAddressSpace(space); + Optional readAddressSpace = api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + assertTrue(readAddressSpace.isPresent()); + AddressSpace read = readAddressSpace.get(); + + assertEquals(ADDRESS_SPACE_NAME, read.getName()); + assertEquals(ADDRESS_SPACE_TYPE, read.getType()); + assertEquals(ADDRESS_SPACE_PLAN, read.getPlan()); + } + + @Test + public void replace() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + final String annotationKey = "myannotation"; + String annotationValue = "value"; + AddressSpace update = new AddressSpace.Builder(space).putAnnotation(annotationKey, annotationValue).build(); + + api.createAddressSpace(space); + assertTrue(api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).isPresent()); + + boolean replaced = api.replaceAddressSpace(update); + assertTrue(replaced); + + AddressSpace read = api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).get(); + + assertEquals(ADDRESS_SPACE_NAME, read.getName()); + assertEquals(annotationValue, read.getAnnotation(annotationKey)); + } + + @Test + public void replaceNotFound() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + boolean replaced = api.replaceAddressSpace(space); + assertFalse(replaced); + } + + @Test + public void delete() throws Exception { + AddressSpace space = createAddressSpace(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME); + + api.createAddressSpace(space); + + boolean deleted = api.deleteAddressSpace(space); + assertTrue(deleted); + + assertFalse(api.getAddressSpaceWithName(ADDRESS_SPACE_NAMESPACE, ADDRESS_SPACE_NAME).isPresent()); + + boolean deletedAgain = api.deleteAddressSpace(space); + assertFalse(deletedAgain); + } + + private AddressSpace createAddressSpace(String namespace, String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(namespace) + .setType(ADDRESS_SPACE_TYPE) + .setPlan(ADDRESS_SPACE_PLAN) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java new file mode 100644 index 0000000000..aad99358c3 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeEventLoggerTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.fabric8.kubernetes.api.model.DoneableEvent; +import io.fabric8.kubernetes.api.model.Event; +import io.fabric8.kubernetes.api.model.EventList; +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.dsl.MixedOperation; +import io.fabric8.kubernetes.client.dsl.Resource; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; + +import static io.enmasse.k8s.api.EventLogger.Type.Warning; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class KubeEventLoggerTest { + + private enum TestReason implements EventLogger.Reason { + NONE + } + + private enum TestKind implements EventLogger.ObjectKind { + KIND + } + + @Test + public void testLogger() { + String ns = "myspace"; + String component = "me"; + Clock clock = Clock.fixed(Instant.ofEpochSecond(10), ZoneId.of("UTC")); + + String message = "it crashed"; + + KubernetesClient mockClient = mock(KubernetesClient.class); + MixedOperation> eventOperation = mock(MixedOperation.class); + Resource eventResource = mock(Resource.class); + + when(mockClient.events()).thenReturn(eventOperation); + when(eventOperation.inNamespace(any())).thenReturn(eventOperation); + when(eventOperation.withName(startsWith("me."))).thenReturn(eventResource); + when(eventResource.get()).thenReturn(null); + + EventLogger logger = new KubeEventLogger(mockClient, ns, clock, component); + logger.log(TestReason.NONE, "it crashed", Warning, TestKind.KIND, "myqueue"); + + ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); + verify(eventResource).create(eventArgumentCaptor.capture()); + Event newEvent = eventArgumentCaptor.getValue(); + assertNotNull(newEvent); + assertThat(newEvent.getMessage(), is(message)); + assertThat(newEvent.getReason(), is(TestReason.NONE.name())); + assertThat(newEvent.getType(), is(Warning.name())); + assertThat(newEvent.getFirstTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getLastTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getCount(), is(1)); + assertThat(newEvent.getInvolvedObject().getName(), is("myqueue")); + assertThat(newEvent.getInvolvedObject().getKind(), is(TestKind.KIND.name())); + + newEvent.setFirstTimestamp(Instant.ofEpochSecond(5).toString()); + when(eventResource.get()).thenReturn(newEvent); + logger.log(TestReason.NONE, "it crashed", Warning, TestKind.KIND, "myqueue"); + + eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); + verify(eventResource).create(eventArgumentCaptor.capture()); + newEvent = eventArgumentCaptor.getValue(); + assertNotNull(newEvent); + assertThat(newEvent.getMessage(), is(message)); + assertThat(newEvent.getReason(), is(TestReason.NONE.name())); + assertThat(newEvent.getType(), is(Warning.name())); + assertThat(newEvent.getFirstTimestamp(), is(Instant.ofEpochSecond(5).toString())); + assertThat(newEvent.getLastTimestamp(), is(clock.instant().toString())); + assertThat(newEvent.getCount(), is(2)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java new file mode 100644 index 0000000000..cc1bbc6922 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/KubeSchemaApiTest.java @@ -0,0 +1,146 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import io.enmasse.address.model.AddressSpaceType; +import io.enmasse.address.model.Schema; +import io.enmasse.admin.model.v1.*; +import io.enmasse.config.AnnotationKeys; +import io.fabric8.kubernetes.api.model.ObjectMetaBuilder; +import org.junit.Before; +import org.junit.Test; + +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +public class KubeSchemaApiTest { + + private AddressSpacePlanApi addressSpacePlanApi; + private AddressPlanApi addressPlanApi; + private StandardInfraConfigApi standardInfraConfigApi; + private BrokeredInfraConfigApi brokeredInfraConfigApi; + + @Before + public void setup() { + addressSpacePlanApi = mock(AddressSpacePlanApi.class); + addressPlanApi = mock(AddressPlanApi.class); + standardInfraConfigApi = mock(StandardInfraConfigApi.class); + brokeredInfraConfigApi = mock(BrokeredInfraConfigApi.class); + } + + @Test + public void testSchemaAssemble() { + KubeSchemaApi schemaApi = new KubeSchemaApi(addressSpacePlanApi, addressPlanApi, brokeredInfraConfigApi, standardInfraConfigApi, Clock.systemUTC(), false); + + List addressSpacePlans = Arrays.asList( + new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("spaceplan1") + .addToAnnotations(AnnotationKeys.DEFINED_BY, "infra1") + .build()) + .withAddressSpaceType("standard") + .withAddressPlans(Arrays.asList("plan1", "plan2")) + .build(), + new AddressSpacePlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("spaceplan2") + .addToAnnotations(AnnotationKeys.DEFINED_BY, "infra1") + .build()) + .withAddressSpaceType("brokered") + .withAddressPlans(Arrays.asList( "plan3")) + .build()); + + List addressPlans = Arrays.asList( + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan1") + .build()) + .withAddressType("queue") + .build(), + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan2") + .build()) + .withAddressType("topic") + .build(), + new AddressPlanBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("plan3") + .build()) + .withAddressType("queue") + .build()); + + List standardInfraConfigs = Arrays.asList( + new StandardInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("infra1") + .build()) + .build()); + + List brokeredInfraConfigs = Arrays.asList( + new BrokeredInfraConfigBuilder() + .withMetadata(new ObjectMetaBuilder() + .withName("infra1") + .build()) + .build()); + + Schema schema = schemaApi.assembleSchema(addressSpacePlans, addressPlans, standardInfraConfigs, brokeredInfraConfigs); + + assertTrue(schema.findAddressSpaceType("standard").isPresent()); + assertTrue(schema.findAddressSpaceType("brokered").isPresent()); + + { + AddressSpaceType type = schema.findAddressSpaceType("standard").get(); + assertTrue(type.findAddressSpacePlan("spaceplan1").isPresent()); + assertFalse(type.findAddressSpacePlan("spaceplan2").isPresent()); + assertTrue(type.findAddressSpacePlan("spaceplan1").get().getAddressPlans().contains("plan1")); + assertTrue(type.findAddressSpacePlan("spaceplan1").get().getAddressPlans().contains("plan2")); + assertTrue(type.findInfraConfig("infra1").isPresent()); + } + { + AddressSpaceType type = schema.findAddressSpaceType("brokered").get(); + assertTrue(type.findAddressSpacePlan("spaceplan2").isPresent()); + assertFalse(type.findAddressSpacePlan("spaceplan1").isPresent()); + assertTrue(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan3")); + assertFalse(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan1")); + assertFalse(type.findAddressSpacePlan("spaceplan2").get().getAddressPlans().contains("plan2")); + assertTrue(type.findInfraConfig("infra1").isPresent()); + } + } + + @Test + public void testWatchCreated() throws Exception { + AddressSpacePlanApi addressSpacePlanApi = mock(AddressSpacePlanApi.class); + AddressPlanApi addressPlanApi = mock(AddressPlanApi.class); + StandardInfraConfigApi standardInfraConfigApi = mock(StandardInfraConfigApi.class); + BrokeredInfraConfigApi brokeredInfraConfigApi = mock(BrokeredInfraConfigApi.class); + + Watch mockWatch = mock(Watch.class); + + when(addressSpacePlanApi.watchAddressSpacePlans(any(), any())).thenReturn(mockWatch); + when(addressPlanApi.watchAddressPlans(any(), any())).thenReturn(mockWatch); + when(brokeredInfraConfigApi.watchBrokeredInfraConfigs(any(), any())).thenReturn(mockWatch); + when(standardInfraConfigApi.watchStandardInfraConfigs(any(), any())).thenReturn(mockWatch); + + SchemaApi schemaApi = new KubeSchemaApi(addressSpacePlanApi, addressPlanApi, brokeredInfraConfigApi, standardInfraConfigApi, Clock.systemUTC(), true); + + schemaApi.watchSchema(items -> { }, Duration.ofSeconds(5)); + verify(addressSpacePlanApi).watchAddressSpacePlans(any(), eq(Duration.ofSeconds(5))); + verify(addressPlanApi).watchAddressPlans(any(), eq(Duration.ofSeconds(5))); + verify(standardInfraConfigApi).watchStandardInfraConfigs(any(), eq(Duration.ofSeconds(5))); + verify(brokeredInfraConfigApi).watchBrokeredInfraConfigs(any(), eq(Duration.ofSeconds(5))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java new file mode 100644 index 0000000000..4e3dba2312 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/ResourceCheckerTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.internal.util.collections.Sets; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import static org.mockito.Mockito.*; + +public class ResourceCheckerTest { + ResourceChecker controller; + Watcher watcher; + + @Before + public void setup() { + watcher = mock(Watcher.class); + controller = new ResourceChecker<>(watcher, Duration.ofMillis(1)); + } + + @Test + public void testResourcesUpdated() throws Exception { + controller.doWork(); + verify(watcher, never()).onUpdate(any()); + + List items = Arrays.asList("hello", "there"); + controller.onInit(() -> items); + controller.onUpdate(); + controller.doWork(); + verify(watcher).onUpdate(eq(items)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java new file mode 100644 index 0000000000..13f94f788a --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/EventCacheTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api.cache; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import org.junit.Test; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class EventCacheTest { + @Test + public void testAdd() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.add(map("k1")); + assertTrue(queue.hasSynced()); + assertFalse(queue.listKeys().contains("k1")); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().contains("k1")); + assertTrue(queue.list().contains(map("k1"))); + } + + @Test + public void testUpdate() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.update(map("k1")); + assertFalse(queue.listKeys().contains("k1")); + assertFalse(queue.list().contains(map("k1"))); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().contains("k1")); + assertTrue(queue.list().contains(map("k1"))); + } + + @Test + public void testRemove() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.add(map("k1")); + queue.delete(map("k1")); + assertTrue(queue.hasSynced()); + assertTrue(queue.listKeys().isEmpty()); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().isEmpty()); + assertTrue(queue.list().isEmpty()); + + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(eq(map("k1"))); + assertTrue(queue.listKeys().isEmpty()); + assertTrue(queue.list().isEmpty()); + } + + @Test + public void testEmpty() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verifyZeroInteractions(mockProc); + assertFalse(queue.hasSynced()); + } + + @Test + public void testSync() throws Exception { + WorkQueue queue = new EventCache<>(new HasMetadataFieldExtractor<>()); + queue.replace(Arrays.asList(map("k1"), map("k2"), map("k3")), "33"); + assertFalse(queue.hasSynced()); + assertFalse(queue.list().isEmpty()); + + Processor mockProc = mock(Processor.class); + queue.pop(mockProc, 0, TimeUnit.SECONDS); + verify(mockProc).process(null); + assertTrue(queue.hasSynced()); + } + + public static ConfigMap map(String name) { + return new ConfigMapBuilder() + .editOrNewMetadata() + .withName(name) + .endMetadata() + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java new file mode 100644 index 0000000000..84c3c26e03 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/k8s-api/src/test/java/io/enmasse/k8s/api/cache/ReflectorTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.k8s.api.cache; + +import io.fabric8.kubernetes.api.model.ConfigMap; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.ConfigMapList; +import io.fabric8.kubernetes.api.model.ConfigMapListBuilder; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Collections; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.*; + +public class ReflectorTest { + Reflector reflector; + ListerWatcher testLister; + WorkQueue testStore; + Processor testProc; + + @Before + public void setup() { + testLister = mock(ListerWatcher.class); + testProc = mock(Processor.class); + testStore = new EventCache<>(new HasMetadataFieldExtractor<>()); + + Reflector.Config config = new Reflector.Config<>(); + config.setClock(Clock.fixed(Instant.now(), ZoneId.systemDefault())); + config.setListerWatcher(testLister); + config.setWorkQueue(testStore); + config.setExpectedType(ConfigMap.class); + config.setResyncInterval(Duration.ofSeconds(1)); + config.setProcessor(testProc); + reflector = new Reflector<>(config); + } + + @Test + public void testReflector() throws Exception { + when(testLister.list(any())).thenReturn(new ConfigMapListBuilder() + .editOrNewMetadata() + .withResourceVersion("3") + .endMetadata() + .addToItems(configMap("a1", "a2", "1")) + .addToItems(configMap("a1", "a3", "3")) + .addToItems(configMap("b1", "b2", "2")) + .build()); + + ArgumentCaptor> captor = ArgumentCaptor.forClass(io.fabric8.kubernetes.client.Watcher.class); + + reflector.run(); + verify(testProc, times(1)).process(any()); + reflector.run(); + verify(testProc, times(1)).process(any()); + assertStoreSize(2); + verify(testLister).watch(captor.capture(), any()); + verify(testLister).list(any()); + + assertConfigMap("a1", "a3"); + assertConfigMap("b1", "b2"); + + io.fabric8.kubernetes.client.Watcher watcher = captor.getValue(); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.MODIFIED, configMap("a1", "a4", "5")); + reflector.run(); + assertStoreSize(2); + assertConfigMap("a1", "a4"); + assertConfigMap("b1", "b2"); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.ADDED, configMap("c1", "c4", "5")); + reflector.run(); + assertStoreSize(3); + assertConfigMap("a1", "a4"); + assertConfigMap("b1", "b2"); + assertConfigMap("c1", "c4"); + watcher.eventReceived(io.fabric8.kubernetes.client.Watcher.Action.DELETED, configMap("b1", "b2", "6")); + reflector.run(); + assertStoreSize(2); + assertConfigMap("a1", "a4"); + assertConfigMap("c1", "c4"); + + reflector.run(); + reflector.run(); + reflector.run(); + reflector.run(); + verify(testProc, times(4)).process(any()); + reflector.run(); + verify(testProc, times(4)).process(any()); + } + + public void assertStoreSize(int expectedSize) throws InterruptedException { + assertThat("Store contains " + testStore.listKeys(), testStore.listKeys().size(), is(expectedSize)); + } + + private void assertConfigMap(String name, String expectedValue) throws InterruptedException { + String actual = findValue(testStore.list(), name); + assertNotNull(actual); + assertThat(actual, is(expectedValue)); + } + + private static String findValue(List list, String name) { + String found = null; + for (ConfigMap map : list) { + if (map.getMetadata().getName().equals(name)) { + found = map.getData().get("data"); + break; + } + } + return found; + } + + private static ConfigMap configMap(String name, String data, String resourceVersion) { + return new ConfigMapBuilder() + .editOrNewMetadata() + .withName(name) + .withResourceVersion(resourceVersion) + .endMetadata() + .withData(Collections.singletonMap("data", data)) + .build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java new file mode 100644 index 0000000000..483cbfb4ac --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakManagerTest.java @@ -0,0 +1,177 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.keycloak.controller; + +import io.enmasse.address.model.*; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.user.api.UserApi; +import io.enmasse.user.model.v1.User; +import io.enmasse.user.model.v1.UserList; +import org.junit.Before; +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class KeycloakManagerTest { + + private KeycloakManager manager; + private Set realms; + private List updatedRealms; + private Map realmAdminUsers; + private KubeApi mockKubeApi; + + @Before + public void setup() { + realms = new HashSet<>(); + updatedRealms = new LinkedList<>(); + realmAdminUsers = new HashMap<>(); + mockKubeApi = mock(KubeApi.class); + when(mockKubeApi.findUserId(any())).thenReturn(""); + when(mockKubeApi.getIdentityProviderParams()).thenReturn(new KeycloakRealmParams("http://example.com", "id", "secret", Collections.singletonMap("hdr1", "value1"))); + + manager = new KeycloakManager(new KeycloakApi() { + @Override + public Set getRealmNames() { + return new HashSet<>(realms); + } + + @Override + public void createRealm(String namespace, String realmName, String consoleRedirectURI, KeycloakRealmParams params) { + realms.add(realmName); + } + + @Override + public void updateRealm(String realmName, KeycloakRealmParams updated) { + updatedRealms.add(realmName); + } + + @Override + public void deleteRealm(String realmName) { + realms.remove(realmName); + } + }, mockKubeApi, new UserApi() { + @Override + public Optional getUserWithName(String realm, String name) { + return Optional.empty(); + } + + @Override + public void createUser(String realm, User user) { + realmAdminUsers.put(realm, user.getSpec().getUsername()); + } + + @Override + public boolean replaceUser(String realm, User user) { + return false; + } + + @Override + public void deleteUser(String realm, User user) { + + } + + @Override + public boolean realmExists(String realm) { + return true; + } + + @Override + public UserList listUsers(String realm) { + return null; + } + + @Override + public UserList listUsersWithLabels(String realm, Map labels) { + return null; + } + + @Override + public void deleteUsers(String namespace) { + + } + }); + } + + @Test + public void testAddAddressSpace() throws Exception { + manager.onUpdate(Collections.singletonList(createAddressSpace("a1", AuthenticationServiceType.NONE))); + assertTrue(realms.isEmpty()); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE), createAddressSpace("a2", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a2")); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE), createAddressSpace("a2", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a2")); + assertTrue(realms.contains("a3")); + assertEquals(2, realms.size()); + + assertTrue(realmAdminUsers.get("a2").length() > 0); + assertTrue(realmAdminUsers.get("a3").length() > 0); + } + + @Test + public void testRemoveAddressSpace() throws Exception { + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD), createAddressSpace("a2", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD), createAddressSpace("a3", AuthenticationServiceType.STANDARD))); + + assertTrue(realms.contains("a1")); + assertFalse(realms.contains("a2")); + assertTrue(realms.contains("a3")); + assertEquals(2, realms.size()); + } + + @Test + public void testAuthTypeChanged() throws Exception { + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.STANDARD))); + assertTrue(realms.contains("a1")); + assertEquals(1, realms.size()); + + manager.onUpdate(Arrays.asList(createAddressSpace("a1", AuthenticationServiceType.NONE))); + assertFalse(realms.contains("a1")); + assertEquals(0, realms.size()); + } + + @Test + public void testUpdateRealm() throws Exception { + List spaces = Collections.singletonList(createAddressSpace("a1", AuthenticationServiceType.STANDARD)); + manager.onUpdate(spaces); + assertTrue(realms.contains("a1")); + assertTrue(updatedRealms.isEmpty()); + + manager.onUpdate(spaces); + assertTrue(updatedRealms.isEmpty()); + + when(mockKubeApi.getIdentityProviderParams()).thenReturn(new KeycloakRealmParams("http://example.com", "id", "secret2", Collections.singletonMap("hdr1", "value1"))); + + manager.onUpdate(spaces); + assertEquals(1, updatedRealms.size()); + } + + private AddressSpace createAddressSpace(String name, AuthenticationServiceType authType) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace("myns") + .setPlan("myplan") + .setType("standard") + .putAnnotation(AnnotationKeys.CREATED_BY, "developer") + .appendEndpoint(new EndpointSpec.Builder() + .setName("console") + .setService("console") + .build()) + .setStatus(new AddressSpaceStatus(true) + .appendEndpointStatus(new EndpointStatus.Builder() + .setName("console") + .setServiceHost("console.svc") + .setExternalPorts(Collections.singletonMap("http", 443)) + .setExternalHost("console.example.com") + .build())) + .setAuthenticationService(new AuthenticationService.Builder().setType(authType).build()).build(); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java new file mode 100644 index 0000000000..6192433b24 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-controller/src/test/java/io/enmasse/keycloak/controller/KeycloakRealmParamsTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.keycloak.controller; + +import io.fabric8.kubernetes.client.KubernetesClient; +import io.fabric8.kubernetes.client.server.mock.KubernetesServer; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class KeycloakRealmParamsTest { + @Rule + public KubernetesServer server = new KubernetesServer(true, true); + + private KubernetesClient client; + + @Before + public void setup() { + client = server.getClient(); + } + + @Test + public void testRequiredEnvironment() { + client.configMaps().createNew() + .editOrNewMetadata() + .withName("myconfig") + .endMetadata() + .addToData("identityProviderUrl", "https://localhost:8443/auth") + .addToData("identityProviderClientId", "myclient") + .addToData("identityProviderClientSecret", "mysecret") + .done(); + + KeycloakRealmParams params = KeycloakRealmParams.fromKube(client, "myconfig"); + assertEquals("https://localhost:8443/auth", params.getIdentityProviderUrl()); + assertEquals("myclient", params.getIdentityProviderClientId()); + assertEquals("mysecret", params.getIdentityProviderClientSecret()); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java new file mode 100644 index 0000000000..4d101ef34f --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/AmqpServerTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.enmasse.keycloak.spi; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class AmqpServerTest { + + @Test + public void testEmptyGroupsGeneratesEmptyPermissions() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(Collections.emptySet()); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("foo")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("foo_bar")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + props = amqpServer.getPermissionsFromGroups(Collections.singleton("send")); + assertNotNull(props); + assertTrue(props.isEmpty()); + + } + + @Test + public void testMultiplePermissionsForSameAddress() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(new HashSet<>(Arrays.asList("send_foo", "consume_foo"))); + assertNotNull(props); + assertEquals(1, props.size()); + assertNotNull(props.get("foo")); + assertEquals(2, props.get("foo").length); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("send"))); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("recv"))); + } + + + + @Test + public void testMultiplePermissionsWithUrlEncoding() { + AmqpServer amqpServer = new AmqpServer(null, 0, null, false); + Map props = amqpServer.getPermissionsFromGroups(new HashSet<>(Arrays.asList("send_foo%2Fbar", "view_%66oo%2Fbar", "recv_foo"))); + assertNotNull(props); + assertEquals(2, props.size()); + assertNotNull(props.get("foo/bar")); + assertEquals(2, props.get("foo/bar").length); + assertTrue(Arrays.stream(props.get("foo/bar")).anyMatch(e -> e.equals("send"))); + assertEquals(2, props.get("foo/bar").length); + assertTrue(Arrays.stream(props.get("foo/bar")).anyMatch(e -> e.equals("view"))); + + assertNotNull(props.get("foo")); + assertEquals(1, props.get("foo").length); + assertTrue(Arrays.stream(props.get("foo")).anyMatch(e -> e.equals("recv"))); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java new file mode 100644 index 0000000000..2b3fc2828c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/PlainSaslServerMechanismTest.java @@ -0,0 +1,139 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import org.junit.Before; +import org.junit.Test; +import org.keycloak.Config; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.KeycloakTransactionManager; +import org.keycloak.models.RealmModel; +import org.keycloak.models.RealmProvider; +import org.keycloak.models.UserCredentialManager; +import org.keycloak.models.UserModel; +import org.keycloak.models.UserProvider; +import org.keycloak.models.credential.PasswordUserCredentialModel; +import org.mockito.ArgumentMatcher; + +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PlainSaslServerMechanismTest { + private KeycloakSessionFactory keycloakSessionFactory; + private KeycloakSession keycloakSession; + private Config.Scope config; + + @Before + public void setup() { + keycloakSessionFactory = mock(KeycloakSessionFactory.class); + keycloakSession = mock(KeycloakSession.class); + when(keycloakSessionFactory.create()).thenReturn(keycloakSession); + KeycloakTransactionManager txnManager = mock(KeycloakTransactionManager.class); + when(keycloakSession.getTransactionManager()).thenReturn(txnManager); + RealmProvider realms = mock(RealmProvider.class); + when(keycloakSession.realms()).thenReturn(realms); + RealmModel realm = mock(RealmModel.class); + when(realms.getRealmByName(eq("realm"))).thenReturn(realm); + UserProvider userProvider = mock(UserProvider.class); + UserModel user = mock(UserModel.class); + when(userProvider.getUserByUsername(eq("user"), eq(realm))).thenReturn(user); + when(keycloakSession.userStorageManager()).thenReturn(userProvider); + UserCredentialManager userCredentialManager = mock(UserCredentialManager.class); + when(keycloakSession.userCredentialManager()).thenReturn(userCredentialManager); + when(userCredentialManager.isValid(eq(realm), eq(user), argThat(new PasswordCredentialMatcher("password")))).thenReturn(true); + + config = mock(Config.Scope.class); + } + + private byte[] createInitialResponse(final String user, final String password) { + byte[] userBytes = user.getBytes(StandardCharsets.UTF_8); + byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8); + byte[] response = new byte[2 + userBytes.length + passwordBytes.length]; + System.arraycopy(userBytes,0,response, 1, userBytes.length); + System.arraycopy(passwordBytes,0,response, 2+userBytes.length, passwordBytes.length); + + return response; + } + + private static final class PasswordCredentialMatcher implements ArgumentMatcher + { + + private final String password; + + private PasswordCredentialMatcher(final String password) { + this.password = password; + } + + @Override + public boolean matches(final PasswordUserCredentialModel item) { + return item.getValue().equals(password); + } + } + + // unknown realm + @Test + public void testUnknownRealm() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "unknownRealm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known realm, unknown user + @Test + public void testUnknownUser() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("unknown", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known user, wrong password + @Test + public void testWrongPassword() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "wrong")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + // known user, correct password + @Test + public void testCorrectPassword() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "password")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertTrue(instance.isAuthenticated()); + } + + // incorrect sasl format + @Test(expected = IllegalArgumentException.class) + public void testBadInitialResponse() { + final SaslServerMechanism.Instance instance = + (new PlainSaslServerMechanism()).newInstance(keycloakSessionFactory, "realm", config); + instance.processResponse("potato".getBytes(StandardCharsets.UTF_8)); + } + + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java new file mode 100644 index 0000000000..a376cf772f --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/ScramPasswordHashProviderTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.keycloak.credential.CredentialModel; +import org.mockito.ArgumentCaptor; + +public class ScramPasswordHashProviderTest { + private ScramPasswordHashProvider hashprovider; + private CredentialModel credentialModel; + + @Before + public void setup() { + hashprovider = new ScramPasswordHashProvider("scramsha1", 10000, "HmacSHA1", "SHA-1"); + credentialModel = mock(CredentialModel.class); + + ArgumentCaptor saltCaptor = ArgumentCaptor.forClass(byte[].class); + doAnswer(invocation -> { + when(credentialModel.getSalt()).thenReturn(saltCaptor.getValue()); + return null; + }).when(credentialModel).setSalt(saltCaptor.capture()); + + ArgumentCaptor passwordCaptor = ArgumentCaptor.forClass(String.class); + doAnswer(invocation -> { + when(credentialModel.getValue()).thenReturn(passwordCaptor.getValue()); + return null; + }).when(credentialModel).setValue(passwordCaptor.capture()); + + + ArgumentCaptor iterationsCaptor = ArgumentCaptor.forClass(Integer.class); + doAnswer(invocation -> { + when(credentialModel.getHashIterations()).thenReturn(iterationsCaptor.getValue()); + return null; + }).when(credentialModel).setHashIterations(iterationsCaptor.capture()); + } + + @Test + public void testProviderVerifiesCorrect() { + hashprovider.encode("testpassword", 25000, credentialModel); + assertTrue(hashprovider.verify("testpassword", credentialModel)); + } + + @Test + public void testProviderFailsIncorrect() { + hashprovider.encode("testpassword", 25000, credentialModel); + assertFalse(hashprovider.verify("wrongpassword", credentialModel)); + } + + @Test + public void testSameValueEncodedDifferently() { + Set encoded = new HashSet<>(); + for(int i = 0; i < 100; i++) { + hashprovider.encode("testpassword", 25000, credentialModel); + if(!encoded.add(credentialModel.getValue())) { + fail("Duplicate encoding of the password"); + } + } + + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java new file mode 100644 index 0000000000..56b2878ddc --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/keycloak-plugin/sasl-plugin/src/test/java/io/enmasse/keycloak/spi/XOAUTH2SaslServerMechanismTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.keycloak.spi; + +import org.junit.Before; +import org.junit.Test; +import org.keycloak.Config; +import org.keycloak.common.VerificationException; +import org.keycloak.common.util.Time; +import org.keycloak.models.*; +import org.keycloak.representations.AccessToken; + +import java.net.URI; +import java.nio.charset.StandardCharsets; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class XOAUTH2SaslServerMechanismTest implements XOAUTH2SaslServerMechanism.TokenVerifier { + private KeycloakSession keycloakSession; + private Config.Scope config; + private boolean verifyToken; + private KeycloakSessionFactory keycloakSessionFactory; + + @Before + public void setup() { + keycloakSession = mock(KeycloakSession.class); + keycloakSessionFactory = mock(KeycloakSessionFactory.class); + when(keycloakSessionFactory.create()).thenReturn(keycloakSession); + KeycloakTransactionManager txnManager = mock(KeycloakTransactionManager.class); + when(keycloakSession.getTransactionManager()).thenReturn(txnManager); + RealmProvider realms = mock(RealmProvider.class); + when(keycloakSession.realms()).thenReturn(realms); + RealmModel realm = mock(RealmModel.class); + when(realm.getName()).thenReturn("realm"); + when(realms.getRealmByName(eq("realm"))).thenReturn(realm); + ClientModel clientModel = mock(ClientModel.class); + when(clientModel.isEnabled()).thenReturn(true); + when(realm.getClientByClientId("client")).thenReturn(clientModel); + UserProvider userProvider = mock(UserProvider.class); + UserModel user = mock(UserModel.class); + when(userProvider.getUserByUsername(eq("user"), eq(realm))).thenReturn(user); + when(keycloakSession.userStorageManager()).thenReturn(userProvider); + UserCredentialManager userCredentialManager = mock(UserCredentialManager.class); + when(keycloakSession.userCredentialManager()).thenReturn(userCredentialManager); + + UserSessionProvider userSessionProvider = mock(UserSessionProvider.class); + when(keycloakSession.sessions()).thenReturn(userSessionProvider); + UserSessionModel userSessionModel = mock(UserSessionModel.class); + when(userSessionProvider.getUserSessionWithPredicate(any(), any(), anyBoolean(), any())).thenReturn(userSessionModel); + when(userSessionModel.getStarted()).thenReturn(Time.currentTime()); + when(userSessionModel.getLastSessionRefresh()).thenReturn(Time.currentTime()); + when(realm.getSsoSessionMaxLifespan()).thenReturn(36000); + when(realm.getSsoSessionIdleTimeout()).thenReturn(36000); + when(userSessionModel.getUser()).thenReturn(user); + + config = mock(Config.Scope.class); + when(config.get(eq("baseUri"), anyString())).thenReturn("https://localhost:8443/auth"); + } + + private byte[] createInitialResponse(final String user, final String token) { + String initialResponseString="user="+user+"\1auth=Bearer "+token+"\1\1"; + return initialResponseString.getBytes(StandardCharsets.US_ASCII); + } + + // unknown realm + @Test + public void testUnknownRealm() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "unknownRealm", config); + byte[] response = instance.processResponse(createInitialResponse("user", "token")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + + } + + + // Invalid token + @Test + public void testWrongPassword() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + this.verifyToken = false; + byte[] response = instance.processResponse(createInitialResponse("user", "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3N0xUZ3BvbFJmU1NqQkNEeTljU3VEeFpkM2hmMTEyN3R5ZzNweU52LVRBIn0.eyJqdGkiOiJmM2E3ZjFhNS0zZGM2LTQ1YjEtOWIyYi1hZjIzYmYxYTc5NTUiLCJleHAiOjE1MjAwODI2NTMsIm5iZiI6MCwiaWF0IjoxNTIwMDgyMzUzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvYW1xcCIsImF1ZCI6ImFtcXAiLCJzdWIiOiI4NjA2NDJiMy0wZmE1LTRiYjctOGI0YS0xZGNiOTdlZjhmZDgiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhbXFwIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiY2Y5Njc0YTAtN2FiNy00YmZiLWI4ZTktZjk3MzM5NTY4NzYwIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInByZWZlcnJlZF91c2VybmFtZSI6Imd1ZXN0In0.Ul33UaC4EXdxtMqv6fLyOHRvHNkA3U1F2FDKxo4Rs4gIvmrbyjK_RN_AciVZjtphYM4xXDn3E9acchyLcQB690NCneDVwqUUj5c2ZU5LcZsAARtBC8MPk8ekDhfmm3ppsRnnSYzucDC1Qe-iLtmhj-v3NzdkgxIwzbgL2E7QzUuf8KFSj2Ue322r27tPhKLm2ay3lcauKe_u3LziA6S1sgxdABWzTBP8UhSeKtqY0j6JT50LA7mvVgmEZvdzqgt6EVYmU0ALzbdjQuOJhmlTDH68cPqQI1-MLAreHt7BDLTN0YuthzoFKheZBaIpBvdDuSI_iV0iAe_AlT16ka4rUg")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertFalse(instance.isAuthenticated()); + } + + // Validated token + @Test + public void testValidatedToken() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + this.verifyToken = true; + byte[] response = instance.processResponse(createInitialResponse("user", "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ3N0xUZ3BvbFJmU1NqQkNEeTljU3VEeFpkM2hmMTEyN3R5ZzNweU52LVRBIn0.eyJqdGkiOiJmM2E3ZjFhNS0zZGM2LTQ1YjEtOWIyYi1hZjIzYmYxYTc5NTUiLCJleHAiOjE1MjAwODI2NTMsIm5iZiI6MCwiaWF0IjoxNTIwMDgyMzUzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvYW1xcCIsImF1ZCI6ImFtcXAiLCJzdWIiOiI4NjA2NDJiMy0wZmE1LTRiYjctOGI0YS0xZGNiOTdlZjhmZDgiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhbXFwIiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiY2Y5Njc0YTAtN2FiNy00YmZiLWI4ZTktZjk3MzM5NTY4NzYwIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInByZWZlcnJlZF91c2VybmFtZSI6Imd1ZXN0In0.Ul33UaC4EXdxtMqv6fLyOHRvHNkA3U1F2FDKxo4Rs4gIvmrbyjK_RN_AciVZjtphYM4xXDn3E9acchyLcQB690NCneDVwqUUj5c2ZU5LcZsAARtBC8MPk8ekDhfmm3ppsRnnSYzucDC1Qe-iLtmhj-v3NzdkgxIwzbgL2E7QzUuf8KFSj2Ue322r27tPhKLm2ay3lcauKe_u3LziA6S1sgxdABWzTBP8UhSeKtqY0j6JT50LA7mvVgmEZvdzqgt6EVYmU0ALzbdjQuOJhmlTDH68cPqQI1-MLAreHt7BDLTN0YuthzoFKheZBaIpBvdDuSI_iV0iAe_AlT16ka4rUg")); + assertTrue(response == null || response.length == 0); + assertTrue(instance.isComplete()); + assertTrue(instance.isAuthenticated()); + } + + // incorrect sasl format + @Test(expected = IllegalArgumentException.class) + public void testBadInitialResponse() { + final SaslServerMechanism.Instance instance = + (new XOAUTH2SaslServerMechanism(this)).newInstance(keycloakSessionFactory, "realm", config); + instance.processResponse("potato".getBytes(StandardCharsets.UTF_8)); + } + + + @Override + public AccessToken verifyTokenString(RealmModel realm, String tokenString, URI baseUri, KeycloakSession keycloakSession) throws VerificationException { + if(verifyToken) { + AccessToken accessToken = new AccessToken(); + accessToken.issuedFor("client"); + return accessToken; + } else { + throw new VerificationException(); + } + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java new file mode 100644 index 0000000000..65ca7e2789 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-gateway/src/test/java/enmasse/mqtt/TopicMatcherTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.mqtt; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Tests related to topic wildcards matches + */ +public class TopicMatcherTest { + + @Test + public void testFixedTopicMatch() { + + String subTopic = "mytopic/foo"; + String pubTopic = "mytopic/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testFixedTopicNotMatch() { + + String subTopic = "mytopic/foo"; + String pubTopic = "mytopic/bar"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicSharpWildcardMatch() { + + String subTopic = "mytopic/#"; + String pubTopic = "mytopic/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicSharpWildcardNotMatch() { + + String subTopic = "mytopic/#"; + String pubTopic = "mytopic"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicPlusWildcardMatch() { + + String subTopic = "mytopic/+/bar"; + String pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + pubTopic = "mytopic/another/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/foo/+"; + pubTopic = "mytopic/foo/bar"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/+/bar/+/foo"; + pubTopic = "mytopic/a/bar/b/foo"; + + assertTrue(TopicMatcher.isMatch(subTopic, pubTopic)); + } + + @Test + public void testTopicPlusWildcardNotMatch() { + + String subTopic = "mytopic/+/bar"; + String pubTopic = "mytopic/bar"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/foo/+"; + pubTopic = "mytopic/foo"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + + subTopic = "mytopic/+/bar/+/foo"; + pubTopic = "mytopic/a/bar/b/foo/c"; + + assertFalse(TopicMatcher.isMatch(subTopic, pubTopic)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java new file mode 100644 index 0000000000..bf5fc93e8d --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/mqtt-lwt/src/test/java/enmasse/mqtt/InMemoryLwtStorageTest.java @@ -0,0 +1,195 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.mqtt; + +import enmasse.mqtt.messages.AmqpWillMessage; +import enmasse.mqtt.storage.LwtStorage; +import enmasse.mqtt.storage.impl.InMemoryLwtStorage; +import io.netty.handler.codec.mqtt.MqttQoS; +import io.vertx.core.buffer.Buffer; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Tests related to the LWT storage service only + */ +@RunWith(VertxUnitRunner.class) +public class InMemoryLwtStorageTest { + + protected final Logger LOG = LoggerFactory.getLogger(InMemoryLwtStorageTest.class); + + private static final AmqpWillMessage WILL_MESSAGE = + new AmqpWillMessage(true, "will_topic", MqttQoS.AT_MOST_ONCE, Buffer.buffer("Hello")); + + private static final String CLIENT_ID = "client_id"; + + private LwtStorage lwtStorage; + + @Before + public void before(TestContext context) { + + this.lwtStorage = new InMemoryLwtStorage(); + this.lwtStorage.open(context.asyncAssertSuccess()); + } + + @After + public void after(TestContext context) { + this.lwtStorage.close(); + } + + @Test + public void addNotExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + + if (done.succeeded()) { + + this.lwtStorage.get(CLIENT_ID, done1 -> { + + if (done1.succeeded()) { + + AmqpWillMessage willMessage1 = done1.result(); + context.assertTrue(willMessage1.equals(WILL_MESSAGE)); + LOG.info("Added a not existing will"); + + } else { + context.assertTrue(false); + } + async.complete(); + }); + + } else { + context.assertTrue(false); + async.complete(); + } + }); + } + + @Test + public void addExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + + if (done.succeeded()) { + + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done1 -> { + + context.assertTrue(!done1.succeeded()); + LOG.info("Will to add already exists"); + async.complete(); + }); + + } else { + context.assertTrue(false); + async.complete(); + } + }); + } + + @Test + public void updateExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + + if (done.succeeded()) { + + AmqpWillMessage willMessage1 = new AmqpWillMessage(false, "will_topic_1", MqttQoS.AT_LEAST_ONCE, Buffer.buffer("Hello_1")); + this.lwtStorage.update(CLIENT_ID, willMessage1, done1 -> { + + if (done1.succeeded()) { + + this.lwtStorage.get(CLIENT_ID, done2 -> { + + if (done2.succeeded()) { + + AmqpWillMessage willMessage2 = done2.result(); + // updated message not equals to the original one but to the one got from the storage + context.assertTrue(!willMessage1.equals(WILL_MESSAGE) && willMessage1.equals(willMessage2)); + LOG.info("Existing will updated"); + + } else { + context.assertTrue(false); + } + async.complete(); + }); + + } else { + context.assertTrue(false); + async.complete(); + } + + }); + + } else { + context.assertTrue(false); + async.complete(); + } + }); + } + + @Test + public void updateNotExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.update(CLIENT_ID, WILL_MESSAGE, done -> { + + context.assertTrue(!done.succeeded()); + LOG.info("Trying to update a not existing will"); + async.complete(); + }); + } + + @Test + public void deleteExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.add(CLIENT_ID, WILL_MESSAGE, done -> { + + if (done.succeeded()) { + + this.lwtStorage.delete(CLIENT_ID, done1 -> { + + context.assertTrue(done1.succeeded()); + LOG.info("Existing will deleted"); + async.complete(); + }); + + } else { + context.assertTrue(false); + async.complete(); + } + }); + } + + @Test + public void deleteNotExistingWill(TestContext context) { + + Async async = context.async(); + + this.lwtStorage.delete(CLIENT_ID, done -> { + + context.assertTrue(!done.succeeded()); + LOG.info("Trying to delete a not existing will"); + async.complete(); + }); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java new file mode 100644 index 0000000000..aca96f7baa --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/HTTPServerTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.address.model.AddressSpaceStatus; +import io.enmasse.address.model.EndpointSpec; +import io.enmasse.api.auth.AuthApi; +import io.enmasse.api.auth.SubjectAccessReview; +import io.enmasse.api.auth.TokenReview; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import io.enmasse.osb.api.provision.ConsoleProxy; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpClientOptions; +import io.vertx.core.http.HttpClientRequest; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@RunWith(VertxUnitRunner.class) +public class HTTPServerTest { + + private Vertx vertx; + private TestAddressSpaceApi instanceApi; + private AddressSpace addressSpace; + private HTTPServer httpServer; + + @Before + public void setup(TestContext context) { + vertx = Vertx.vertx(); + instanceApi = new TestAddressSpaceApi(); + String addressSpaceName = "myinstance"; + addressSpace = createAddressSpace(addressSpaceName); + instanceApi.createAddressSpace(addressSpace); + + AuthApi authApi = mock(AuthApi.class); + when(authApi.getNamespace()).thenReturn("controller"); + when(authApi.performTokenReview(eq("mytoken"))).thenReturn(new TokenReview("foo", "myid", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + when(authApi.performSubjectAccessReviewResource(eq("foo"), any(), any(), any(), anyString())).thenReturn(new SubjectAccessReview("foo", true)); + httpServer = new HTTPServer(instanceApi, new TestSchemaProvider(), authApi, null, false, null, 0, new ConsoleProxy() { + @Override + public String getConsoleUrl(AddressSpace addressSpace) { + return "http://localhost/console/" + addressSpaceName; + } + }); + vertx.deployVerticle(httpServer, context.asyncAssertSuccess()); + } + + @After + public void teardown(TestContext context) { + vertx.close(context.asyncAssertSuccess()); + } + + private AddressSpace createAddressSpace(String name) { + return new AddressSpace.Builder() + .setName(name) + .setNamespace(name) + .setType("mytype") + .setPlan("myplan") + .setStatus(new AddressSpaceStatus(false)) + .appendEndpoint(new EndpointSpec.Builder() + .setName("foo") + .setService("messaging") + .build()) + .build(); + } + + @Test + public void testOpenServiceBrokerAPI(TestContext context) { + HttpClientOptions options = new HttpClientOptions(); + HttpClient client = vertx.createHttpClient(options); + try { + Async async = context.async(); + HttpClientRequest request = client.get(httpServer.getActualPort(), "localhost", "/osbapi/v2/catalog", response -> { + response.bodyHandler(buffer -> { + JsonObject data = buffer.toJsonObject(); + context.assertTrue(data.containsKey("services")); + async.complete(); + }); + }); + putAuthzToken(request); + request.end(); + async.awaitSuccess(60_000); + } finally { + client.close(); + } + } + + private static HttpClientRequest putAuthzToken(HttpClientRequest request) { + request.putHeader("Authorization", "Bearer mytoken"); + return request; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java new file mode 100644 index 0000000000..9882bc49a1 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/BindingServiceTest.java @@ -0,0 +1,139 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; + +import io.enmasse.api.common.ConflictException; +import io.enmasse.api.common.GoneException; +import io.enmasse.api.common.UnprocessableEntityException; +import io.enmasse.osb.api.bind.BindRequest; +import io.enmasse.osb.api.bind.BindResponse; +import io.enmasse.osb.api.provision.ProvisionRequest; +import org.jboss.resteasy.util.HttpResponseCodes; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.UUID; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +@Ignore +public class BindingServiceTest extends OSBTestBase { + + public static final String BINDING_ID = UUID.randomUUID().toString(); + + @Override + public void setup() throws Exception { + super.setup(); + provisionService(SERVICE_INSTANCE_ID); + } + + @Test(expected = UnprocessableEntityException.class) + public void testSyncProvisioningRequest() throws Exception { + UriInfo uriInfo = mock(UriInfo.class); + provisioningService.provisionService(getSecurityContext(), null, "123", false, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test + @Ignore + public void testBind() throws Exception { + Response response = bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + BindResponse bindResponse = (BindResponse) response.getEntity(); + + assertThat(response.getStatus(), is(HttpResponseCodes.SC_CREATED)); + assertThat(bindResponse.getCredentials().get("namespace"), notNullValue()); + assertThat(bindResponse.getCredentials().get("destination-address"), notNullValue()); + // TODO: Set fake hosts +// assertThat(bindResponse.getCredentials().get("internal-messaging-host"), notNullValue()); +// assertThat(bindResponse.getCredentials().get("internal-mqtt-host"), notNullValue()); + } + + @Test + public void testInvalidBindingUuid() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, "123", new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + } + + @Test(expected = NotFoundException.class) + @Ignore + public void testBindOnNonexistentService() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), UUID.randomUUID().toString(), BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + } + + @Test(expected = BadRequestException.class) + @Ignore + public void testBindWithoutServiceId() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(null, QUEUE_PLAN_ID)); + } + + @Test(expected = BadRequestException.class) + public void testBindWithoutPlanId() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, null)); + } + + @Ignore("Not implemented yet") + @Test(expected = BadRequestException.class) + public void testWrongServiceId() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(UUID.randomUUID(), QUEUE_PLAN_ID)); + } + + @Ignore("Not implemented yet") + @Test(expected = BadRequestException.class) + public void testWrongPlanId() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, UUID.randomUUID())); + } + + @Ignore("bindings aren't persisted yet, so we can't do this yet") + @Test + public void testBindTwiceWithDifferentPrameters() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + String otherServiceId = UUID.randomUUID().toString(); + provisionService(otherServiceId); + + exceptionGrabber.expect(ConflictException.class); + bindingService.bindServiceInstance(getSecurityContext(), otherServiceId, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + } + + @Ignore("bindings aren't persisted yet, so we can't do this yet") + @Test + public void testBindTwiceWithSameParameters() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + Response response = bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Test + public void testUnbind() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + + Response response = bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Ignore("bindings aren't persisted yet, so we can't do this yet. OSB spec mandates the broker MUST return Gone, when binding doesn't exist") + @Test(expected = GoneException.class) + public void testUnbindNonexistingBinding() throws Exception { + bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, UUID.randomUUID().toString()); + } + + @Ignore("bindings aren't persisted yet, so we can't do this yet. OSB spec mandates the broker MUST return Gone, when binding doesn't exist") + @Test + public void testUnbindTwice() throws Exception { + bindingService.bindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID, new BindRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID)); + bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + + exceptionGrabber.expect(GoneException.class); + bindingService.unbindServiceInstance(getSecurityContext(), SERVICE_INSTANCE_ID, BINDING_ID); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java new file mode 100644 index 0000000000..2c988ae2e6 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/CatalogServiceTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import org.junit.Ignore; + +@Ignore +public class CatalogServiceTest extends OSBTestBase { +/* + @Test + public void testCatalog() throws IOException { + OSBCatalogService catalogService = new OSBCatalogService(new TestAddressSpaceApi(), schemaProvider, "controller"); + + Response response = catalogService.getCatalog(getSecurityContext()); + CatalogResponse catalogResponse = (CatalogResponse) response.getEntity(); + List services = catalogResponse.getServices(); + + assertThat(services.size(), is(4)); + assertService(services.get(0), "enmasse-anycast", "standard"); + assertService(services.get(1), "enmasse-multicast", "standard"); + assertService(services.get(2), "enmasse-queue", "inmemory", "persisted", "pooled-inmemory", "pooled-persisted"); + assertService(services.get(3), "enmasse-topic", "inmemory", "persisted"); + + Service service = services.get(2); + Plan plan = service.getPlans().get(0); + assertThat(plan.getMetadata().get("displayName"), is("In-memory")); + assertThat(plan.getDescription(), is("Creates a standalone broker cluster for queues. Messages are not persisted on stable storage.")); + } + + private void assertService(Service service, String name, String... planNames) { + assertThat(service.getName(), is(name)); + assertThat(service.getPlans().size(), is(planNames.length)); + for (int i = 0; i < planNames.length; i++) { + String planName = planNames[i]; + Plan plan = service.getPlans().get(i); + assertThat(plan.getName(), is(planName)); + } + } + */ +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java new file mode 100644 index 0000000000..b69c4eba80 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/DeserializationTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.enmasse.osb.api.bind.BindRequest; +import io.enmasse.osb.api.provision.ProvisionRequest; +import org.junit.Test; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * + */ +public class DeserializationTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testProvisionRequest() throws IOException { + UUID serviceUuid = UUID.randomUUID(); + UUID planUuid = UUID.randomUUID(); + UUID organizationUuid = UUID.randomUUID(); + UUID spaceUuid = UUID.randomUUID(); + + Map map = new HashMap<>(); + map.put("service_id", serviceUuid.toString()); + map.put("plan_id", planUuid.toString()); + map.put("organization_guid", organizationUuid.toString()); + map.put("space_guid", spaceUuid.toString()); + + Map parameters = new HashMap<>(); + parameters.put("foo", "bar"); + parameters.put("baz", "qux"); + map.put("parameters", parameters); + + String serialized = mapper.writeValueAsString(map); + + ProvisionRequest request = mapper.readValue(serialized, ProvisionRequest.class); + assertThat(request.getServiceId(), is(serviceUuid)); + assertThat(request.getPlanId(), is(planUuid)); + assertThat(request.getOrganizationId(), is(organizationUuid.toString())); + assertThat(request.getSpaceId(), is(spaceUuid.toString())); + assertThat(request.getParameters(), is(parameters)); + } + + @Test + public void testBindRequest() throws IOException { + UUID serviceUuid = UUID.randomUUID(); + UUID planUuid = UUID.randomUUID(); + UUID appUuid = UUID.randomUUID(); + + Map map = new HashMap<>(); + map.put("service_id", serviceUuid.toString()); + map.put("plan_id", planUuid.toString()); + + Map bindResource = new HashMap<>(); + bindResource.put("app_guid", appUuid.toString()); + bindResource.put("route", "some-address"); + map.put("bind_resource", bindResource); + + Map parameters = new HashMap<>(); + parameters.put("foo", "bar"); + parameters.put("baz", "qux"); + map.put("parameters", parameters); + + + String serialized = mapper.writeValueAsString(map); + + BindRequest request = mapper.readValue(serialized, BindRequest.class); + assertThat(request.getServiceId(), is(serviceUuid)); + assertThat(request.getPlanId(), is(planUuid)); + assertThat(request.getBindResource().getAppId(), is(appUuid.toString())); + assertThat(request.getBindResource().getRoute(), is("some-address")); + assertThat(request.getParameters(), is(parameters)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java new file mode 100644 index 0000000000..645d8c5cfc --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/OSBTestBase.java @@ -0,0 +1,83 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import io.enmasse.address.model.AddressSpace; +import io.enmasse.osb.api.bind.OSBBindingService; +import io.enmasse.osb.api.lastoperation.OSBLastOperationService; +import io.enmasse.osb.api.provision.ConsoleProxy; +import io.enmasse.osb.api.provision.OSBProvisioningService; +import io.enmasse.osb.api.provision.ProvisionRequest; +import io.enmasse.k8s.api.TestAddressSpaceApi; +import org.apache.http.auth.BasicUserPrincipal; +import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.ExpectedException; + +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.core.UriInfo; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * + */ +public class OSBTestBase { + protected static final UUID QUEUE_SERVICE_ID = ServiceType.QUEUE.uuid(); + protected static final UUID TOPIC_SERVICE_ID = ServiceType.TOPIC.uuid(); + protected static final UUID QUEUE_PLAN_ID = UUID.fromString("3c7f4fdc-0597-11e8-abdb-507b9def37d9"); + protected static final UUID TOPIC_PLAN_ID = UUID.fromString("48837510-0597-11e8-8517-507b9def37d9"); + protected static final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + protected static final String ORGANIZATION_ID = UUID.randomUUID().toString(); + protected static final String SPACE_ID = UUID.randomUUID().toString(); + + @Rule + public ExpectedException exceptionGrabber = ExpectedException.none(); + + protected OSBProvisioningService provisioningService; + protected TestAddressSpaceApi addressSpaceApi; + protected OSBBindingService bindingService; + protected OSBLastOperationService lastOperationService; + + @Before + public void setup() throws Exception { + addressSpaceApi = new TestAddressSpaceApi(); + String brokerId = "myspace"; + provisioningService = new OSBProvisioningService(addressSpaceApi, null, null, new ConsoleProxy() { + @Override + public String getConsoleUrl(AddressSpace addressSpace) { + return "http://localhost/console/" + addressSpace.getName(); + } + }); + bindingService = new OSBBindingService(addressSpaceApi, null, null, null); + lastOperationService = new OSBLastOperationService(addressSpaceApi, null, null); + } + + protected void provisionService(String serviceInstanceId) throws Exception { + provisionService(serviceInstanceId, ORGANIZATION_ID, SPACE_ID); + } + + protected SecurityContext getSecurityContext() { + SecurityContext securityContext = mock(SecurityContext.class); + when(securityContext.isUserInRole(any())).thenReturn(true); + when(securityContext.isSecure()).thenReturn(true); + when(securityContext.getUserPrincipal()).thenReturn(new BasicUserPrincipal("myuser")); + return securityContext; + } + + protected String provisionService(String serviceInstanceId, String organizationId, String spaceId) throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, organizationId, spaceId); + provisionRequest.putParameter("name", "my-queue"); + provisionRequest.putParameter("group", "my-group"); + + UriInfo uriInfo = mock(UriInfo.class); + provisioningService.provisionService(getSecurityContext(), null, serviceInstanceId, true, provisionRequest); + // TODO: wait for provisioning to finish (poll lastOperation endpoint) + return serviceInstanceId; + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java new file mode 100644 index 0000000000..af1ba98e63 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ProvisionServiceTest.java @@ -0,0 +1,185 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.osb.api; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; + +import io.enmasse.api.common.ConflictException; +import io.enmasse.api.common.GoneException; +import io.enmasse.api.common.UnprocessableEntityException; +import io.enmasse.osb.api.lastoperation.LastOperationResponse; +import io.enmasse.osb.api.lastoperation.LastOperationState; +import io.enmasse.osb.api.provision.ProvisionRequest; +import io.enmasse.osb.api.provision.ProvisionResponse; +import io.enmasse.address.model.Address; +import io.enmasse.address.model.Status; +import org.jboss.resteasy.util.HttpResponseCodes; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.UUID; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +@Ignore +public class ProvisionServiceTest extends OSBTestBase { + + public static final String QUEUE_SERVICE_ID_STRING = QUEUE_SERVICE_ID.toString(); + public static final String QUEUE_PLAN_ID_STRING = QUEUE_PLAN_ID.toString(); + + public static final String ADDRESS = "my-queue"; + public static final String TRANSACTIONAL = "transactional"; + private UriInfo uriInfo = mock(UriInfo.class); + + @Test(expected = UnprocessableEntityException.class) + public void testSyncProvisioningRequest() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, "123", false, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test(expected = BadRequestException.class) + public void testInvalidServiceUuid() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test(expected = BadRequestException.class) + public void testInvalidPlan() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, TOPIC_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test(expected = BadRequestException.class) + public void testInvalidServiceInstandeUuid() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, "123", true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test + public void testProvision() throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID); + provisionRequest.putParameter("name", ADDRESS); + provisionRequest.putParameter("transactional", "true"); + Response response = provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + ProvisionResponse provisionResponse = (ProvisionResponse) response.getEntity(); + + assertThat(response.getStatus(), is(HttpResponseCodes.SC_ACCEPTED)); +// assertThat(provisionResponse.getDashboardUrl(), notNullValue()); + assertThat(provisionResponse.getOperation(), notNullValue()); + + Address destination = new Address.Builder() + .setName(ADDRESS) + .setAddress(ADDRESS) + .setAddressSpace("unknown") + .setStatus(new Status(false)) + .setType("queue") + .setPlan("myplan") + .build(); + //assertThat(addressSpaceApi.getAddresses(), is(new HashSet<>(Collections.singletonList(destination)))); + + LastOperationResponse lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.IN_PROGRESS)); + + addressSpaceApi.setAllInstancesReady(true); + + lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.IN_PROGRESS)); + + addressSpaceApi.getAddressApis().iterator().next().setAllAddressesReady(true); + + lastOperationResponse = getLastOperationResponse(SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING, provisionResponse.getOperation()); + assertThat(lastOperationResponse.getState(), is(LastOperationState.SUCCEEDED)); + + destination = new Address.Builder() + .setName(ADDRESS) + .setAddress(ADDRESS) + .setAddressSpace("unknown") + .setStatus(new Status(true)) + .setType("queue") + .setPlan("myplan") + .build(); + + //assertThat(addressSpaceApi.getAddresses(), is(new HashSet<>(Collections.singletonList(destination)))); + } + + private LastOperationResponse getLastOperationResponse(String serviceInstanceId, String serviceId, String planId, String operation) throws Exception { + Response response = lastOperationService.getLastOperationStatus(getSecurityContext(), serviceInstanceId, serviceId, planId, operation); + return (LastOperationResponse) response.getEntity(); + } + + + @Test + public void testProvisionTwiceWithDifferentPrameters() throws Exception { + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + exceptionGrabber.expect(ConflictException.class); + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, new ProvisionRequest(ServiceType.TOPIC.uuid(), TOPIC_PLAN_ID, ORGANIZATION_ID, SPACE_ID)); + } + + @Test + public void testProvisionTwiceWithSameParameters() throws Exception { + ProvisionRequest provisionRequest = new ProvisionRequest(QUEUE_SERVICE_ID, QUEUE_PLAN_ID, ORGANIZATION_ID, SPACE_ID); + provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + Response response = provisioningService.provisionService(getSecurityContext(), null, SERVICE_INSTANCE_ID, true, provisionRequest); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + } + + @Test(expected = GoneException.class) + public void testDeprovisionNonexistingServiceInstance() throws Exception { + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + } + + @Test(expected = BadRequestException.class) + public void testDeprovisionWithoutServiceId() throws Exception { + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, null, QUEUE_PLAN_ID_STRING); + } + + @Test(expected = BadRequestException.class) + public void testDeprovisionWithoutPlanId() throws Exception { + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, null); + } + + @Test + public void testDeprovision() throws Exception { + provisionService(SERVICE_INSTANCE_ID); + Response response = provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddresses(), is(Collections.EMPTY_SET)); + } + + @Test + public void testDeprovisionTwice() throws Exception { + provisionService(SERVICE_INSTANCE_ID); + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + + exceptionGrabber.expect(GoneException.class); + provisioningService.deprovisionService(getSecurityContext(), SERVICE_INSTANCE_ID, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + } + + @Test + public void testDeprovisionGivenMultipleOrganizations() throws Exception { + String serviceId11 = provisionService(randomUUID(), ORGANIZATION_ID, SPACE_ID); + provisionService(randomUUID(), ORGANIZATION_ID, SPACE_ID); + + String organizationId2 = randomUUID(); + String spaceId2 = randomUUID(); + String serviceId21 = provisionService(randomUUID(), organizationId2, spaceId2); + provisionService(randomUUID(), organizationId2, spaceId2); + + Response response = provisioningService.deprovisionService(getSecurityContext(), serviceId21, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddressUuids(), not(hasItem(serviceId21))); + + response = provisioningService.deprovisionService(getSecurityContext(), serviceId11, QUEUE_SERVICE_ID_STRING, QUEUE_PLAN_ID_STRING); + assertThat(response.getStatus(), is(HttpResponseCodes.SC_OK)); + //assertThat(addressSpaceApi.getAddressUuids(), not(hasItem(serviceId11))); + } + + private String randomUUID() { + return UUID.randomUUID().toString(); + } + + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java new file mode 100644 index 0000000000..5eb4913847 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/SerializationTest.java @@ -0,0 +1,126 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.jsonSchema.types.ObjectSchema; +import io.enmasse.osb.api.bind.BindResponse; +import io.enmasse.osb.api.catalog.CatalogResponse; +import io.enmasse.osb.api.catalog.InputParameters; +import io.enmasse.osb.api.catalog.Plan; +import io.enmasse.osb.api.catalog.Schemas; +import io.enmasse.osb.api.catalog.Service; +import io.enmasse.osb.api.catalog.ServiceInstanceSchema; +import io.enmasse.osb.api.lastoperation.LastOperationResponse; +import io.enmasse.osb.api.lastoperation.LastOperationState; +import io.enmasse.osb.api.provision.ProvisionResponse; +import org.junit.Test; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * + */ +public class SerializationTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testCatalogResponse() throws IOException { + UUID serviceId = UUID.randomUUID(); + Service service = new Service(serviceId, "test-service", "test-description", true); + service.setPlanUpdatable(false); + + UUID planId = UUID.randomUUID(); + Plan plan = new Plan(planId, "test-plan", "test-plan-description", true, true); + plan.setSchemas(new Schemas(new ServiceInstanceSchema(new InputParameters(new ObjectSchema()), null), null)); + service.getPlans().add(plan); + + CatalogResponse response = new CatalogResponse(Collections.singletonList(service)); + + String serialized = mapper.writeValueAsString(response); + Map map = mapper.readValue(serialized, Map.class); + + List services = (List) map.get("services"); + assertThat(services.size(), is(1)); + + Map serviceMap = (Map) services.get(0); + assertThat(serviceMap.get("name"), is("test-service")); + assertThat(serviceMap.get("id"), is(serviceId.toString())); + assertThat(serviceMap.get("description"), is("test-description")); + assertThat(serviceMap.get("tags"), is(Collections.EMPTY_LIST)); + assertThat(serviceMap.get("requires"), is(Collections.EMPTY_LIST)); + assertThat(serviceMap.get("bindable"), is(true)); + assertThat(serviceMap.get("metadata"), notNullValue()); + assertThat(serviceMap.get("dashboard_client"), nullValue()); + assertThat(serviceMap.get("plan_updateable"), is(false)); + + List plans = (List) serviceMap.get("plans"); + assertThat(plans.size(), is(1)); + + Map planMap = (Map)plans.get(0); + assertThat(planMap.get("id"), is(planId.toString())); + assertThat(planMap.get("name"), is("test-plan")); + assertThat(planMap.get("description"), is("test-plan-description")); + assertThat(planMap.get("metadata"), notNullValue()); + assertThat(planMap.get("free"), is(true)); + assertThat(planMap.get("bindable"), is(true)); + + assertThat(planMap.get("schemas"), notNullValue()); // TODO: expand this + } + + @Test + public void testProvisionResponse() throws IOException { + ProvisionResponse response = new ProvisionResponse("dashboard-url", "some-operation"); + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + + assertThat(map.get("dashboard_url"), is("dashboard-url")); + assertThat(map.get("operation"), is("some-operation")); + } + + @Test + public void testBindResponse() throws IOException { + Map credentials = new HashMap<>(); + credentials.put("foo", "bar"); + credentials.put("baz", "qux"); + BindResponse response = new BindResponse(credentials); + response.setRouteServiceUrl("route-service-url"); + response.setSyslogDrainUrl("syslog-drain-url"); + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + assertThat(map.get("route_service_url"), is("route-service-url")); + assertThat(map.get("syslog_drain_url"), is("syslog-drain-url")); + assertThat(map.get("credentials"), is(credentials)); + } + + @Test + public void testLastOperationResponse() throws IOException { + assertLastOperationResponse(new LastOperationResponse(LastOperationState.IN_PROGRESS, "operation-in-progress"), "in progress"); + assertLastOperationResponse(new LastOperationResponse(LastOperationState.SUCCEEDED, "operation-succeeded"), "succeeded"); + assertLastOperationResponse(new LastOperationResponse(LastOperationState.FAILED, "operation-failed"), "failed"); + } + + private void assertLastOperationResponse(LastOperationResponse response, String expectedState) throws IOException { + String serialized = mapper.writeValueAsString(response); + + Map map = mapper.readValue(serialized, Map.class); + assertThat(map.get("state"), is(expectedState)); + assertThat(map.get("description"), is(response.getDescription())); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java new file mode 100644 index 0000000000..fabfa1cc68 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/service-broker/src/test/java/io/enmasse/osb/api/ServiceMappingTest.java @@ -0,0 +1,25 @@ +/* + * Copyright 2017-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.osb.api; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ServiceMappingTest { + @Test + public void testRegexp() { + String regexp = ServiceMapping.addressRegexp; + assertTrue("foobar".matches(regexp)); + assertFalse("/foobar".matches(regexp)); + assertFalse("/foobar/".matches(regexp)); + assertFalse("foobar/".matches(regexp)); + assertTrue("foo.bar".matches(regexp)); + assertTrue("foo/bar".matches(regexp)); + assertTrue("foo/bar/baz".matches(regexp)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java new file mode 100644 index 0000000000..15b677f02c --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressControllerTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.controller.standard; + +import io.enmasse.address.model.Address; +import io.enmasse.address.model.Status; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.AddressApi; +import io.enmasse.k8s.api.EventLogger; +import io.enmasse.metrics.api.Metrics; +import io.fabric8.kubernetes.api.model.ConfigMapBuilder; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.openshift.client.OpenShiftClient; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.time.Duration; +import java.util.*; + +import static org.mockito.Mockito.*; + +public class AddressControllerTest { + private Kubernetes mockHelper; + private AddressApi mockApi; + private AddressController controller; + private OpenShiftClient mockClient; + private BrokerSetGenerator mockGenerator; + + @Before + public void setUp() throws IOException { + mockHelper = mock(Kubernetes.class); + mockGenerator = mock(BrokerSetGenerator.class); + mockApi = mock(AddressApi.class); + mockClient = mock(OpenShiftClient.class); + EventLogger eventLogger = mock(EventLogger.class); + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(); + when(mockHelper.getRouterCluster()).thenReturn(new RouterCluster("qdrouterd", 1, null)); + StandardControllerOptions options = new StandardControllerOptions(); + options.setAddressSpace("me1"); + options.setAddressSpacePlanName("plan1"); + options.setResyncInterval(Duration.ofSeconds(5)); + options.setVersion("1.0"); + controller = new AddressController(options, mockApi, mockHelper, mockGenerator, eventLogger, standardControllerSchema, new Metrics()); + } + + @Test + public void testAddressGarbageCollection() throws Exception { + Address alive = new Address.Builder() + .setName("q1") + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .setStatus(new Status(true).setPhase(Status.Phase.Active)) + .build(); + Address terminating = new Address.Builder() + .setName("q2") + .setAddress("q2") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .setStatus(new Status(false).setPhase(Status.Phase.Terminating)) + .build(); + when(mockHelper.listClusters()).thenReturn(Arrays.asList(new BrokerCluster("broker", new KubernetesList()))); + controller.onUpdate(Arrays.asList(alive, terminating)); + verify(mockApi).deleteAddress(any()); + verify(mockApi).deleteAddress(eq(terminating)); + } + + @Test + public void testDeleteUnusedClusters() throws Exception { + Address alive = new Address.Builder() + .setName("q1") + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setType("queue") + .setPlan("small-queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .putAnnotation(AnnotationKeys.CLUSTER_ID, "broker") + .setStatus(new Status(true).setPhase(Status.Phase.Active)) + .build(); + + KubernetesList oldList = new KubernetesListBuilder() + .addToConfigMapItems(new ConfigMapBuilder() + .withNewMetadata() + .withName("mymap") + .endMetadata() + .build()) + .build(); + when(mockHelper.listClusters()).thenReturn(Arrays.asList( + new BrokerCluster("broker", new KubernetesList()), + new BrokerCluster("unused", oldList))); + + controller.onUpdate(Arrays.asList(alive)); + + verify(mockHelper).delete(any()); + verify(mockHelper).delete(eq(oldList)); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java new file mode 100644 index 0000000000..e8f3817452 --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/AddressProvisionerTest.java @@ -0,0 +1,543 @@ +/* + * Copyright 2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ +package io.enmasse.controller.standard; + +import io.enmasse.address.model.*; +import io.enmasse.admin.model.v1.ResourceAllowance; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.k8s.api.EventLogger; +import io.fabric8.kubernetes.api.model.KubernetesList; +import io.fabric8.kubernetes.api.model.KubernetesListBuilder; +import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder; +import org.junit.Before; +import org.junit.Test; +import org.mockito.internal.util.collections.Sets; + +import java.util.*; +import java.util.function.Consumer; + +import static io.enmasse.address.model.Status.Phase.Configuring; +import static io.enmasse.address.model.Status.Phase.Pending; +import static java.util.Collections.singleton; +import static junit.framework.TestCase.assertTrue; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +public class AddressProvisionerTest { + private BrokerSetGenerator generator; + private Kubernetes kubernetes; + + @Before + public void setup() { + generator = mock(BrokerSetGenerator.class); + kubernetes = mock(Kubernetes.class); + } + + private AddressProvisioner createProvisioner() { + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(); + AddressResolver resolver = new AddressResolver(standardControllerSchema.getType()); + AddressSpaceResolver addressSpaceResolver = new AddressSpaceResolver(standardControllerSchema.getSchema()); + EventLogger logger = mock(EventLogger.class); + + return new AddressProvisioner(addressSpaceResolver, resolver, standardControllerSchema.getPlan(), generator, kubernetes, logger, "1234"); + } + + private AddressProvisioner createProvisioner(List resourceAllowances) { + StandardControllerSchema standardControllerSchema = new StandardControllerSchema(resourceAllowances); + AddressResolver resolver = new AddressResolver(standardControllerSchema.getType()); + AddressSpaceResolver addressSpaceResolver = new AddressSpaceResolver(standardControllerSchema.getSchema()); + EventLogger logger = mock(EventLogger.class); + + return new AddressProvisioner(addressSpaceResolver, resolver, standardControllerSchema.getPlan(), generator, kubernetes, logger, "1234"); + } + + @Test + public void testUsageCheck() { + Set
addresses = new HashSet<>(); + addresses.add(new Address.Builder() + .setAddress("a1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-anycast") + .setType("anycast") + .build()); + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(1)); + assertThat(usageMap.get("router").size(), is(1)); + assertEquals(0.2, usageMap.get("router").get("all").getUsed(), 0.01); + + addresses.add(new Address.Builder() + .setAddress("q1") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-queue") + .setType("queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .build()); + + usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(2)); + assertThat(usageMap.get("router").size(), is(1)); + assertThat(usageMap.get("broker").size(), is(1)); + assertEquals(0.4, usageMap.get("router").get("all").getUsed(), 0.01); + assertEquals(0.4, usageMap.get("broker").get("broker-0").getUsed(), 0.01); + + addresses.add(new Address.Builder() + .setAddress("q2") + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan("small-queue") + .setType("queue") + .putAnnotation(AnnotationKeys.BROKER_ID, "broker-0") + .build()); + + usageMap = provisioner.checkUsage(addresses); + + assertThat(usageMap.size(), is(2)); + assertThat(usageMap.get("router").size(), is(1)); + assertThat(usageMap.get("broker").size(), is(1)); + assertEquals(0.6, usageMap.get("router").get("all").getUsed(), 0.01); + assertEquals(0.8, usageMap.get("broker").get("broker-0").getUsed(), 0.01); + } + + @Test + public void testQuotaCheck() { + Set
addresses = new HashSet<>(); + addresses.add(createQueue("q1", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createQueue("q2", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createQueue("q3", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-1")); + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address largeQueue = createQueue("q4", "xlarge-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(largeQueue), Sets.newSet(largeQueue)); + + assertThat(neededMap, is(usageMap)); + assertThat(largeQueue.getStatus().getPhase(), is(Pending)); + + Address smallQueue = createQueue("q4", "small-queue"); + neededMap = provisioner.checkQuota(usageMap, Sets.newSet(smallQueue), Sets.newSet(smallQueue)); + + assertThat(neededMap, is(not(usageMap))); + } + + @Test + public void testQuotaCheckMany() { + Map addresses = new HashMap<>(); + for (int i = 0; i < 200; i++) { + addresses.put("a" + i, createAddress("a" + i, "anycast", "small-anycast")); + } + + + AddressProvisioner provisioner = createProvisioner(); + + Map> usageMap = new HashMap<>(); + Map> provisionMap = provisioner.checkQuota(usageMap, new LinkedHashSet<>(addresses.values()), new LinkedHashSet<>(addresses.values())); + + assertThat(provisionMap.get("router").get("all").getNeeded(), is(1)); + int numConfiguring = 0; + for (Address address : addresses.values()) { + if (address.getStatus().getPhase().equals(Configuring)) { + numConfiguring++; + } + } + assertThat(numConfiguring, is(5)); + } + + @Test + public void testProvisioningColocated() { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + addresses.add(createAddress("q1", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-0")); + + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address queue = createAddress("q2", "queue", "small-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(queue), Sets.newSet(queue)); + + List clusterList = Arrays.asList(new BrokerCluster("broker-pooled-1234", new KubernetesList())); + provisioner.provisionResources(createDeployment(1), clusterList, neededMap, Sets.newSet(queue)); + + assertThat(clusterList.get(0).getResources().getItems().size(), is(0)); + assertTrue(queue.getStatus().getMessages().toString(), queue.getStatus().getMessages().isEmpty()); + assertThat(queue.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertThat(queue.getAnnotations().get(AnnotationKeys.BROKER_ID), is("broker-pooled-1234-0")); + } + + private static RouterCluster createDeployment(int replicas) { + return new RouterCluster("router", replicas, null); + } + + @Test + public void testScalingColocated() { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + addresses.add(createAddress("q1", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + addresses.add(createAddress("q2", "queue", "small-queue").putAnnotation(AnnotationKeys.BROKER_ID, "broker-pooled-1234-0")); + + AddressProvisioner provisioner = createProvisioner(); + Map> usageMap = provisioner.checkUsage(addresses); + + Address queue = createAddress("q3", "queue", "small-queue"); + Map> provisionMap = provisioner.checkQuota(usageMap, Sets.newSet(queue), Sets.newSet(queue)); + + List clusterList = Arrays.asList(new BrokerCluster("broker-pooled-1234", new KubernetesList())); + provisioner.provisionResources(createDeployment(1), clusterList, provisionMap, Sets.newSet(queue)); + verify(kubernetes).scaleStatefulSet(eq("broker-pooled-1234"), eq(2)); + + assertTrue(queue.getStatus().getMessages().toString(), queue.getStatus().getMessages().isEmpty()); + assertThat(queue.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertThat(queue.getAnnotations().get(AnnotationKeys.BROKER_ID), is("broker-pooled-1234-1")); + } + + @Test + public void testProvisionColocated() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 2))); + + Set
addressSet = Sets.newSet( + createQueue("q9", "pooled-queue-tiny"), + createQueue("q8", "pooled-queue-tiny"), + createQueue("q11", "pooled-queue-tiny"), + createQueue("q12", "pooled-queue-tiny"), + createQueue("q10", "pooled-queue-tiny"), + createQueue("q1", "pooled-queue-large"), + createQueue("q7", "pooled-queue-tiny"), + createQueue("q6", "pooled-queue-small"), + createQueue("q5", "pooled-queue-small"), + createQueue("q4", "pooled-queue-small"), + createQueue("q3", "pooled-queue-small"), + createQueue("q2", "pooled-queue-large")); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(1)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + + List brokerClusters = Arrays.asList( + createCluster("broker-pooled-1234", 2)); + + provisioner.provisionResources(new RouterCluster("router", 1, null), brokerClusters, neededMap, addressSet); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + } + + private BrokerCluster createCluster(String clusterId, int replicas) { + KubernetesListBuilder builder = new KubernetesListBuilder(); + builder.addToStatefulSetItems(new StatefulSetBuilder() + .editOrNewMetadata() + .withName(clusterId) + .endMetadata() + .editOrNewSpec() + .withReplicas(replicas) + .endSpec() + .build()); + return new BrokerCluster(clusterId, builder.build()); + } + + private Address createQueue(String address, String plan) { + return createQueue(address, plan, null); + } + + private Address createQueue(String address, String plan, Consumer> customizeAnnotations) { + return createAddress(address, "queue", plan, customizeAnnotations); + } + + private static Address createAddress(String address, String type, String plan) { + return createAddress(address, type, plan, null); + } + + private static Address createAddress(String address, String type, String plan, Consumer> customizeAnnotations) { + final Address.Builder addressBuilder = new Address.Builder() + .setName(address) + .setAddress(address) + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan(plan) + .setType(type); + + if ( customizeAnnotations != null ) { + final Map annotations = new HashMap<>(); + customizeAnnotations.accept(annotations); + addressBuilder.setAnnotations(annotations); + } + + return addressBuilder.build(); + } + + private Address createSubscription(String address, String topic, String plan) { + return new Address.Builder() + .setAddress(address) + .setAddressSpace("myspace") + .setNamespace("ns") + .setPlan(plan) + .setType("subscription") + .setTopic(topic) + .build(); + } + + + @Test + public void testProvisioningSharded() throws Exception { + Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 3), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 4))); + Map> usageMap = provisioner.checkUsage(addresses); + + Address q1 = createQueue("q1", "xlarge-queue"); + Address q2 = createQueue("q2", "large-queue"); + Map> neededMap = provisioner.checkQuota(usageMap, Sets.newSet(q1, q2), Sets.newSet(q1, q2)); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q1)), anyInt(), eq(q1), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q1), new KubernetesList())); + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q2)), anyInt(), eq(q2), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q2), new KubernetesList())); + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, Sets.newSet(q1, q2)); + + assertTrue(q1.getStatus().getMessages().toString(), q1.getStatus().getMessages().isEmpty()); + assertThat(q1.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q1.getAnnotations().get(AnnotationKeys.BROKER_ID)); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(q1)), eq(2), eq(q1), any(), any()); + + assertTrue(q2.getStatus().getMessages().toString(), q2.getStatus().getMessages().isEmpty()); + assertThat(q2.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q2.getAnnotations().get(AnnotationKeys.BROKER_ID)); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(q2)), eq(1), eq(q2), any(), any()); + } + + @Test + public void testProvisioningShardedWithClusterId() throws Exception { + final Set
addresses = new HashSet<>(); + addresses.add(createAddress("a1", "anycast", "small-anycast")); + + final AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 3), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 4))); + final Map> usageMap = provisioner.checkUsage(addresses); + + final String manualClusterId = "foobar"; + + final Address q = createQueue("q1", "xlarge-queue", annotations -> { + annotations.put(AnnotationKeys.CLUSTER_ID, manualClusterId); + }); + + final Map> neededMap = provisioner.checkQuota(usageMap, singleton(q), singleton(q)); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(q)), anyInt(), eq(q), any(), any())) + .thenReturn(new BrokerCluster(provisioner.getShardedClusterId(q), new KubernetesList())); + + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, singleton(q)); + + assertTrue(q.getStatus().getMessages().toString(), q.getStatus().getMessages().isEmpty()); + assertThat(q.getStatus().getPhase(), is(Status.Phase.Configuring)); + assertNull(q.getAnnotations().get(AnnotationKeys.BROKER_ID)); + + verify(generator) + .generateCluster(eq(manualClusterId), eq(2), eq(q), any(), any()); + } + + @Test + public void testScalingRouter() { + Set
addresses = new HashSet<>(); + for (int i = 0; i < 199; i++) { + addresses.add(createAddress("a" + i, "anycast", "small-anycast")); + } + + + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 0), + new ResourceAllowance("router", 100000), + new ResourceAllowance("aggregate", 100000))); + + Map> usageMap = new HashMap<>(); + Map> neededMap = provisioner.checkQuota(usageMap, addresses, addresses); + + provisioner.provisionResources(createDeployment(1), new ArrayList<>(), neededMap, addresses); + + verify(kubernetes, atLeast(1)).scaleStatefulSet(eq("router"), eq(40)); + verify(kubernetes, never()).scaleStatefulSet(eq("router"), eq(41)); + } + + @Test + public void testDurableSubscriptionsColocated() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Set
addressSet = Sets.newSet( + createAddress("t1", "topic", "small-topic"), + createAddress("t2", "topic", "small-topic"), + createSubscription("s1", "t1", "small-subscription")); + + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + } + + @Test + public void testDurableSubscriptionsColocatedStaysOnTopicBroker() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Set
addressSet = Sets.newSet( + createAddress("t1", "topic", "small-topic"), + createSubscription("s1", "t1", "small-subscription"), + createSubscription("s2", "t1", "small-subscription"), + createSubscription("s3", "t1", "small-subscription"), + createSubscription("s4", "t1", "small-subscription"), + createSubscription("s5", "t1", "small-subscription"), + createSubscription("s6", "t1", "small-subscription"), + createSubscription("s7", "t1", "small-subscription"), + createSubscription("s8", "t1", "small-subscription"), + createSubscription("s9", "t1", "small-subscription"), + createSubscription("s10", "t1", "small-subscription"), + createSubscription("s11", "t1", "small-subscription"), + createSubscription("s12", "t1", "small-subscription")); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + Set
configured = new HashSet
(); + Set
unConfigured = new HashSet
(); + + + for (Address address : addressSet) { + if (address.getStatus().getPhase().equals(Pending)) { + unConfigured.add(address); + } else if (address.getStatus().getPhase().equals(Configuring)) { + configured.add(address); + } + } + assertEquals(2, unConfigured.size()); + assertEquals("contains topic + 10 subscriptions", 11, configured.size()); + Iterator
unconfiguredIterator = unConfigured.iterator(); + assertFalse(configured.contains(unconfiguredIterator.next())); + assertFalse(configured.contains(unconfiguredIterator.next())); + } + + @Test + public void testDurableSubscriptionsSharded() throws Exception { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Address t1 = createAddress("t1", "topic", "xlarge-topic"); + Address t2 = createAddress("t2", "topic", "xlarge-topic"); + Address s1 = createSubscription("s1", "t1", "small-subscription"); + Set
addressSet = Sets.newSet( + t1, + t2, + s1); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(3)); + + List brokerClusters = new ArrayList(Arrays.asList(createCluster("broker", 1))); + + when(generator.generateCluster(eq(provisioner.getShardedClusterId(t1)), anyInt(), eq(t1), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(t1), new KubernetesList())); + when(generator.generateCluster(eq(provisioner.getShardedClusterId(t2)), anyInt(), eq(t2), any(), any())).thenReturn(new BrokerCluster(provisioner.getShardedClusterId(t2), new KubernetesList())); + provisioner.provisionResources(createDeployment(1), brokerClusters, neededMap, addressSet); + + for (Address address : addressSet) { + assertThat(address.getStatus().getPhase(), is(Configuring)); + } + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(t2)), eq(1), eq(t2), any(), any()); + verify(generator).generateCluster(eq(provisioner.getShardedClusterId(t1)), eq(1), eq(t1), any(), any()); + } + + @Test + public void testDurableSubscriptionsShardedStaysOnTopicBroker() { + AddressProvisioner provisioner = createProvisioner(Arrays.asList( + new ResourceAllowance("broker", 2), + new ResourceAllowance("router", 1), + new ResourceAllowance("aggregate", 3))); + + Address t1 = createAddress("t1", "topic", "small-topic"); + Address t2 = createAddress("t2", "topic", "small-topic"); + + Set
addressSet = Sets.newSet( + t1, + createSubscription("s1", "t1", "small-subscription"), + createSubscription("s2", "t1", "small-subscription"), + createSubscription("s3", "t1", "small-subscription"), + createSubscription("s4", "t1", "small-subscription"), + createSubscription("s5", "t1", "small-subscription"), + createSubscription("s6", "t1", "small-subscription"), + createSubscription("s7", "t1", "small-subscription"), + createSubscription("s8", "t1", "small-subscription"), + createSubscription("s9", "t1", "small-subscription"), + createSubscription("s10", "t1", "small-subscription"), + createSubscription("s11", "t1", "small-subscription"), + createSubscription("s12", "t1", "small-subscription"), + t2); + + Map> usageMap = provisioner.checkUsage(Collections.emptySet()); + Map> neededMap = provisioner.checkQuota(usageMap, addressSet, addressSet); + + assertThat(neededMap.keySet().size(), is(3)); + assertThat(AddressProvisioner.sumTotalNeeded(neededMap), is(2)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("router")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("broker")), is(1)); + assertThat(AddressProvisioner.sumNeeded(neededMap.get("subscription")), is(1)); + + Set
configured = new HashSet
(); + Set
unConfigured = new HashSet
(); + + for (Address address : addressSet) { + if (address.getStatus().getPhase().equals(Pending)) { + unConfigured.add(address); + } else if (address.getStatus().getPhase().equals(Configuring)) { + configured.add(address); + } + } + assertEquals(2, unConfigured.size()); + assertTrue(configured.contains(t1)); + assertTrue(configured.contains(t2)); + assertEquals("contains 2 topic + 10 subscriptions", 12, configured.size()); + Iterator
unconfiguredIterator = unConfigured.iterator(); + assertFalse(configured.contains(unconfiguredIterator.next())); + assertFalse(configured.contains(unconfiguredIterator.next())); + } +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java new file mode 100644 index 0000000000..1e7705ba4e --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/standard-controller/src/test/java/io/enmasse/controller/standard/TemplateBrokerSetGeneratorTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package io.enmasse.controller.standard; + +import io.enmasse.admin.model.v1.StandardInfraConfig; +import io.enmasse.config.AnnotationKeys; +import io.enmasse.address.model.*; +import io.fabric8.kubernetes.api.model.*; +import io.fabric8.openshift.client.ParameterValue; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.util.*; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.*; + +public class TemplateBrokerSetGeneratorTest { + private Kubernetes kubernetes; + private StandardControllerSchema standardControllerSchema; + private BrokerSetGenerator generator; + + @Before + public void setUp() { + kubernetes = mock(Kubernetes.class); + + standardControllerSchema = new StandardControllerSchema(); + generator = new TemplateBrokerSetGenerator(kubernetes, new StandardControllerOptions()); + } + + @Test + public void testDirect() throws Exception { + Address dest = createAddress("foo_bar_FOO", "anycast"); + ArgumentCaptor captor = ArgumentCaptor.forClass(ParameterValue.class); + BrokerCluster clusterList = generateCluster(dest, captor); + List resources = clusterList.getResources().getItems(); + assertThat(resources.size(), is(1)); + List parameters = captor.getAllValues(); + assertThat(parameters.size(), is(13)); + } + + @Test + public void testStoreAndForward() throws Exception { + Address dest = createAddress("foo.bar", "queue"); + ArgumentCaptor captor = ArgumentCaptor.forClass(ParameterValue.class); + BrokerCluster clusterList = generateCluster(dest, captor); + List resources = clusterList.getResources().getItems(); + assertThat(resources.size(), is(1)); + for (HasMetadata resource : resources) { + Map annotations = resource.getMetadata().getAnnotations(); + assertNotNull(annotations.get(AnnotationKeys.CLUSTER_ID)); + assertThat(annotations.get(AnnotationKeys.CLUSTER_ID), is(dest.getName())); + } + List parameters = captor.getAllValues(); + assertThat(parameters.size(), is(13)); + } + + private Address createAddress(String address, String type) { + return new Address.Builder() + .setName(address) + .setAddress(address) + .setAddressSpace("myinstance") + .setType(type) + .setPlan("plan1") + .build(); + } + + private BrokerCluster generateCluster(Address address, ArgumentCaptor captor) throws Exception { + when(kubernetes.processTemplate(anyString(), captor.capture())).thenReturn(new KubernetesListBuilder().addNewConfigMapItem().withNewMetadata().withName("testmap").endMetadata().endConfigMapItem().build()); + + return generator.generateCluster(address.getName(), 1, address, null, + standardControllerSchema.getSchema().findAddressSpaceType("standard").map(type -> (StandardInfraConfig)type.findInfraConfig("cfg1").orElse(null)).orElse(null)); + } + +} diff --git a/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java new file mode 100644 index 0000000000..09c9e2e9aa --- /dev/null +++ b/src/test/resources/oracle/commits/enmasse-86fdd8d01b38b2754c9720094dbc52f527c93ae0/topic-forwarder/src/test/java/enmasse/broker/forwarder/ForwarderControllerTest.java @@ -0,0 +1,119 @@ +/* + * Copyright 2016-2018, EnMasse authors. + * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). + */ + +package enmasse.broker.forwarder; + +import enmasse.discovery.Host; +import io.vertx.core.Vertx; +import io.vertx.core.VertxOptions; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.*; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(VertxUnitRunner.class) +public class ForwarderControllerTest { + private static final Logger log = LoggerFactory.getLogger(ForwarderControllerTest.class.getName()); + private Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(10)); + private String localHost = "127.0.0.1"; + private final String address = "mytopic"; + private TestBroker serverA; + private TestBroker serverB; + private TestBroker serverC; + + @Before + public void setup(TestContext testContext) throws Exception { + serverA = new TestBroker(1, address); + serverB = new TestBroker(2, address); + serverC = new TestBroker(3, address); + vertx.deployVerticle(serverA, testContext.asyncAssertSuccess()); + vertx.deployVerticle(serverB, testContext.asyncAssertSuccess()); + vertx.deployVerticle(serverC, testContext.asyncAssertSuccess()); + } + + @After + public void teardown() throws Exception { + vertx.close(); + } + + @Test + public void testBrokerReplicator() throws InterruptedException, TimeoutException, ExecutionException { + Host hostA = new Host(localHost, Collections.singletonMap("amqp", serverA.getPort())); + Host hostB = new Host(localHost, Collections.singletonMap("amqp", serverB.getPort())); + Host hostC = new Host(localHost, Collections.singletonMap("amqp", serverC.getPort())); + + ForwarderController replicator = new ForwarderController(hostA, address, null); + CountDownLatch latch = new CountDownLatch(1); + vertx.deployVerticle(replicator, id -> latch.countDown()); + latch.await(1, TimeUnit.MINUTES); + + Set hosts = new LinkedHashSet<>(); + hosts.add(hostB); + replicator.hostsChanged(hosts); + Thread.sleep(5000); + hosts.add(hostC); + replicator.hostsChanged(hosts); + + long timeout = 60_000; + waitForConnections(serverA, 2, timeout); + waitForConnections(serverB, 1, timeout); + waitForConnections(serverC, 1, timeout); + + CompletableFuture> resultB = serverB.recvMessages(2, 60, TimeUnit.SECONDS); + CompletableFuture> resultC = serverC.recvMessages(2, 60, TimeUnit.SECONDS); + + serverA.sendMessage("Hello 1", 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 2", 60, TimeUnit.SECONDS); + + assertMessages(resultB.get(120, TimeUnit.SECONDS), "Hello 1", "Hello 2"); + assertMessages(resultC.get(120, TimeUnit.SECONDS), "Hello 1", "Hello 2"); + + hosts.remove(hostB); + replicator.hostsChanged(hosts); + + waitForConnections(serverA, 2, timeout); + waitForConnections(serverB, 0, timeout); + waitForConnections(serverC, 1, timeout); + + resultC = serverC.recvMessages(2, 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 3", 60, TimeUnit.SECONDS); + serverA.sendMessage("Hello 4", 60, TimeUnit.SECONDS); + assertMessages(resultC.get(120, TimeUnit.SECONDS), "Hello 3", "Hello 4"); + } + + private void assertMessages(List result, String...messages) { + assertThat(messages.length, is(2)); + for (String message : messages) { + assertThat(result, hasItem(message)); + } + } + + private static void waitForConnections(TestBroker server, int num, long timeout) throws InterruptedException { + long endTime = System.currentTimeMillis() + timeout; + while (System.currentTimeMillis() < endTime) { + log.info("Num connected on " + server.getId() + " is : " + server.numConnected()); + if (server.numConnected() >= num) { + break; + } + Thread.sleep(1000); + } + assertTrue(server.numConnected() >= num); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.json b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.json new file mode 100644 index 0000000000..a78e88f39c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef.json @@ -0,0 +1 @@ +{"parentCommitId":"a20e54d0a7aceeffee5a96523ac7f3b8140b0def","currentCommitId":"6694d742a370e0f181530734481284de8d5dd8ef","filesBefore":["abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java","abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java","abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java","abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java","abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java","adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java","adapter/src/test/java/com/iluwatar/adapter/AppTest.java","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java","api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java","api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java","balking/src/test/java/com/iluwatar/balking/AppTest.java","balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java","bridge/src/test/java/com/iluwatar/bridge/AppTest.java","bridge/src/test/java/com/iluwatar/bridge/HammerTest.java","bridge/src/test/java/com/iluwatar/bridge/SwordTest.java","bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java","builder/src/test/java/com/iluwatar/builder/AppTest.java","builder/src/test/java/com/iluwatar/builder/HeroTest.java","business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java","business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java","caching/src/test/java/com/iluwatar/caching/AppTest.java","caching/src/test/java/com/iluwatar/caching/CachingTest.java","callback/src/test/java/com/iluwatar/callback/AppTest.java","callback/src/test/java/com/iluwatar/callback/CallbackTest.java","chain/src/test/java/com/iluwatar/chain/AppTest.java","chain/src/test/java/com/iluwatar/chain/OrcKingTest.java","command/src/test/java/com/iluwatar/command/AppTest.java","command/src/test/java/com/iluwatar/command/CommandTest.java","composite/src/test/java/com/iluwatar/composite/AppTest.java","composite/src/test/java/com/iluwatar/composite/MessengerTest.java","converter/src/test/java/com/iluwatar/converter/AppTest.java","converter/src/test/java/com/iluwatar/converter/ConverterTest.java","cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java","dao/src/test/java/com/iluwatar/dao/AppTest.java","dao/src/test/java/com/iluwatar/dao/CustomerTest.java","dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java","dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java","data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java","data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java","data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java","data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java","decorator/src/test/java/com/iluwatar/decorator/AppTest.java","decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java","decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java","delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java","delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java","eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java","eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java","event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java","event-sourcing/src/test/java/IntegrationTest.java","execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java","execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java","extension-objects/src/test/java/AppTest.java","extension-objects/src/test/java/concreteextensions/CommanderTest.java","extension-objects/src/test/java/concreteextensions/SergeantTest.java","extension-objects/src/test/java/concreteextensions/SoldierTest.java","extension-objects/src/test/java/units/CommanderUnitTest.java","extension-objects/src/test/java/units/SergeantUnitTest.java","extension-objects/src/test/java/units/SoldierUnitTest.java","extension-objects/src/test/java/units/UnitTest.java","facade/src/test/java/com/iluwatar/facade/AppTest.java","facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java","factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java","factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java","factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java","factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java","fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java","fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java","flux/src/test/java/com/iluwatar/flux/action/ContentTest.java","flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java","flux/src/test/java/com/iluwatar/flux/app/AppTest.java","flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java","flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java","flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java","flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java","flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java","flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java","flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java","front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java","front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java","front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java","front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java","front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java","guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java","interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java","interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java","iterator/src/test/java/com/iluwatar/iterator/AppTest.java","iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java","layers/src/test/java/com/iluwatar/layers/AppTest.java","layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java","layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java","layers/src/test/java/com/iluwatar/layers/CakeTest.java","layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java","lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java","lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java","marker/src/test/java/AppTest.java","marker/src/test/java/GuardTest.java","marker/src/test/java/ThiefTest.java","mediator/src/test/java/com/iluwatar/mediator/AppTest.java","mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java","mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java","memento/src/test/java/com/iluwatar/memento/AppTest.java","memento/src/test/java/com/iluwatar/memento/StarTest.java","message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java","module/src/test/java/com/iluwatar/module/AppTest.java","module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java","monad/src/test/java/com/iluwatar/monad/AppTest.java","monad/src/test/java/com/iluwatar/monad/MonadTest.java","monostate/src/test/java/com/iluwatar/monostate/AppTest.java","monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java","multiton/src/test/java/com/iluwatar/multiton/AppTest.java","multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java","mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java","mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java","mutex/src/test/java/com/iluwatar/mutex/AppTest.java","mutex/src/test/java/com/iluwatar/mutex/JarTest.java","mutex/src/test/java/com/iluwatar/mutex/MutexTest.java","null-object/src/test/java/com/iluwatar/nullobject/AppTest.java","null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java","null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java","object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java","object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java","object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java","observer/src/test/java/com/iluwatar/observer/AppTest.java","observer/src/test/java/com/iluwatar/observer/HobbitsTest.java","observer/src/test/java/com/iluwatar/observer/OrcsTest.java","observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java","observer/src/test/java/com/iluwatar/observer/WeatherTest.java","observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java","observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java","observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java","observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java","page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java","page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java","page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java","promise/src/test/java/com/iluwatar/promise/AppTest.java","promise/src/test/java/com/iluwatar/promise/PromiseTest.java","property/src/test/java/com/iluwatar/property/AppTest.java","property/src/test/java/com/iluwatar/property/CharacterTest.java","prototype/src/test/java/com/iluwatar/prototype/AppTest.java","prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java","prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java","proxy/src/test/java/com/iluwatar/proxy/AppTest.java","proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java","proxy/src/test/java/com/iluwatar/proxy/WizardTest.java","proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java","publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java","reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java","repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java","repository/src/test/java/com/iluwatar/repository/AppConfigTest.java","repository/src/test/java/com/iluwatar/repository/AppTest.java","repository/src/test/java/com/iluwatar/repository/RepositoryTest.java","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java","retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java","retry/src/test/java/com/iluwatar/retry/RetryTest.java","semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java","semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java","semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java","servant/src/test/java/com/iluwatar/servant/AppTest.java","servant/src/test/java/com/iluwatar/servant/KingTest.java","servant/src/test/java/com/iluwatar/servant/QueenTest.java","servant/src/test/java/com/iluwatar/servant/ServantTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java","service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java","service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java","singleton/src/test/java/com/iluwatar/singleton/AppTest.java","singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java","specification/src/test/java/com/iluwatar/specification/app/AppTest.java","specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java","specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java","specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java","specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java","state/src/test/java/com/iluwatar/state/AppTest.java","state/src/test/java/com/iluwatar/state/MammothTest.java","step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java","step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java","strategy/src/test/java/com/iluwatar/strategy/AppTest.java","strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java","strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java","template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java","template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java","template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java","throttling/src/test/java/com/iluwatar/throttling/AppTest.java","throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java","throttling/src/test/java/com/iluwatar/throttling/TenantTest.java","tls/src/test/java/com/iluwatar/tls/AppTest.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java","tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java","tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java","twin/src/test/java/com/iluwatar/twin/AppTest.java","twin/src/test/java/com/iluwatar/twin/BallItemTest.java","twin/src/test/java/com/iluwatar/twin/BallThreadTest.java","value-object/src/test/java/com/iluwatar/value/object/AppTest.java","value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java","visitor/src/test/java/com/iluwatar/visitor/AppTest.java","visitor/src/test/java/com/iluwatar/visitor/UnitTest.java","visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java"],"filesCurrent":["abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java","abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java","abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java","abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java","abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java","adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java","adapter/src/test/java/com/iluwatar/adapter/AppTest.java","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java","api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java","api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java","balking/src/test/java/com/iluwatar/balking/AppTest.java","balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java","bridge/src/test/java/com/iluwatar/bridge/AppTest.java","bridge/src/test/java/com/iluwatar/bridge/HammerTest.java","bridge/src/test/java/com/iluwatar/bridge/SwordTest.java","bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java","builder/src/test/java/com/iluwatar/builder/AppTest.java","builder/src/test/java/com/iluwatar/builder/HeroTest.java","business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java","business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java","caching/src/test/java/com/iluwatar/caching/AppTest.java","caching/src/test/java/com/iluwatar/caching/CachingTest.java","callback/src/test/java/com/iluwatar/callback/AppTest.java","callback/src/test/java/com/iluwatar/callback/CallbackTest.java","chain/src/test/java/com/iluwatar/chain/AppTest.java","chain/src/test/java/com/iluwatar/chain/OrcKingTest.java","command/src/test/java/com/iluwatar/command/AppTest.java","command/src/test/java/com/iluwatar/command/CommandTest.java","composite/src/test/java/com/iluwatar/composite/AppTest.java","composite/src/test/java/com/iluwatar/composite/MessengerTest.java","converter/src/test/java/com/iluwatar/converter/AppTest.java","converter/src/test/java/com/iluwatar/converter/ConverterTest.java","cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java","dao/src/test/java/com/iluwatar/dao/AppTest.java","dao/src/test/java/com/iluwatar/dao/CustomerTest.java","dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java","dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java","data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java","data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java","data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java","data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java","data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java","decorator/src/test/java/com/iluwatar/decorator/AppTest.java","decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java","decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java","delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java","delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java","dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java","double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java","eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java","eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java","event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java","event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java","event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java","event-sourcing/src/test/java/IntegrationTest.java","execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java","execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java","extension-objects/src/test/java/AppTest.java","extension-objects/src/test/java/concreteextensions/CommanderTest.java","extension-objects/src/test/java/concreteextensions/SergeantTest.java","extension-objects/src/test/java/concreteextensions/SoldierTest.java","extension-objects/src/test/java/units/CommanderUnitTest.java","extension-objects/src/test/java/units/SergeantUnitTest.java","extension-objects/src/test/java/units/SoldierUnitTest.java","extension-objects/src/test/java/units/UnitTest.java","facade/src/test/java/com/iluwatar/facade/AppTest.java","facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java","factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java","factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java","factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java","factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java","feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java","fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java","fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java","flux/src/test/java/com/iluwatar/flux/action/ContentTest.java","flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java","flux/src/test/java/com/iluwatar/flux/app/AppTest.java","flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java","flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java","flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java","flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java","flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java","flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java","flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java","front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java","front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java","front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java","front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java","front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java","guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java","hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java","interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java","interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java","interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java","iterator/src/test/java/com/iluwatar/iterator/AppTest.java","iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java","layers/src/test/java/com/iluwatar/layers/AppTest.java","layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java","layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java","layers/src/test/java/com/iluwatar/layers/CakeTest.java","layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java","lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java","lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java","marker/src/test/java/AppTest.java","marker/src/test/java/GuardTest.java","marker/src/test/java/ThiefTest.java","mediator/src/test/java/com/iluwatar/mediator/AppTest.java","mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java","mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java","memento/src/test/java/com/iluwatar/memento/AppTest.java","memento/src/test/java/com/iluwatar/memento/StarTest.java","message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java","model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java","module/src/test/java/com/iluwatar/module/AppTest.java","module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java","monad/src/test/java/com/iluwatar/monad/AppTest.java","monad/src/test/java/com/iluwatar/monad/MonadTest.java","monostate/src/test/java/com/iluwatar/monostate/AppTest.java","monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java","multiton/src/test/java/com/iluwatar/multiton/AppTest.java","multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java","mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java","mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java","mutex/src/test/java/com/iluwatar/mutex/AppTest.java","mutex/src/test/java/com/iluwatar/mutex/JarTest.java","mutex/src/test/java/com/iluwatar/mutex/MutexTest.java","null-object/src/test/java/com/iluwatar/nullobject/AppTest.java","null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java","null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java","object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java","object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java","object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java","observer/src/test/java/com/iluwatar/observer/AppTest.java","observer/src/test/java/com/iluwatar/observer/HobbitsTest.java","observer/src/test/java/com/iluwatar/observer/OrcsTest.java","observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java","observer/src/test/java/com/iluwatar/observer/WeatherTest.java","observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java","observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java","observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java","observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java","page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java","page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java","page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java","poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java","private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java","producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java","promise/src/test/java/com/iluwatar/promise/AppTest.java","promise/src/test/java/com/iluwatar/promise/PromiseTest.java","property/src/test/java/com/iluwatar/property/AppTest.java","property/src/test/java/com/iluwatar/property/CharacterTest.java","prototype/src/test/java/com/iluwatar/prototype/AppTest.java","prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java","prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java","proxy/src/test/java/com/iluwatar/proxy/AppTest.java","proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java","proxy/src/test/java/com/iluwatar/proxy/WizardTest.java","proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java","publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java","reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java","repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java","repository/src/test/java/com/iluwatar/repository/AppConfigTest.java","repository/src/test/java/com/iluwatar/repository/AppTest.java","repository/src/test/java/com/iluwatar/repository/RepositoryTest.java","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java","retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java","retry/src/test/java/com/iluwatar/retry/RetryTest.java","semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java","semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java","semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java","servant/src/test/java/com/iluwatar/servant/AppTest.java","servant/src/test/java/com/iluwatar/servant/KingTest.java","servant/src/test/java/com/iluwatar/servant/QueenTest.java","servant/src/test/java/com/iluwatar/servant/ServantTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java","service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java","service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java","service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java","singleton/src/test/java/com/iluwatar/singleton/AppTest.java","singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java","specification/src/test/java/com/iluwatar/specification/app/AppTest.java","specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java","specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java","specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java","specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java","state/src/test/java/com/iluwatar/state/AppTest.java","state/src/test/java/com/iluwatar/state/MammothTest.java","step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java","step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java","strategy/src/test/java/com/iluwatar/strategy/AppTest.java","strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java","strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java","template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java","template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java","template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java","thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java","throttling/src/test/java/com/iluwatar/throttling/AppTest.java","throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java","throttling/src/test/java/com/iluwatar/throttling/TenantTest.java","tls/src/test/java/com/iluwatar/tls/AppTest.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java","tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java","tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java","tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java","twin/src/test/java/com/iluwatar/twin/AppTest.java","twin/src/test/java/com/iluwatar/twin/BallItemTest.java","twin/src/test/java/com/iluwatar/twin/BallThreadTest.java","value-object/src/test/java/com/iluwatar/value/object/AppTest.java","value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java","visitor/src/test/java/com/iluwatar/visitor/AppTest.java","visitor/src/test/java/com/iluwatar/visitor/UnitTest.java","visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable","async-method-invocation/src/test/java/com/iluwatar/async/method","dao/src/test/java","reader-writer-lock","servant/src/test","front-controller/src","feature-toggle/src","flyweight/src/test/java/com/iluwatar/flyweight","monostate/src/test/java","eip-wire-tap/src/test/java/com/iluwatar","queue-load-leveling/src/test/java","service-layer/src/test/java/com/iluwatar/servicelayer/spell","publish-subscribe/src/test/java/com/iluwatar","fluentinterface/src/test/java/com/iluwatar/fluentinterface/app","flux/src/test/java/com/iluwatar","adapter","data-mapper/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar","message-channel/src/test/java/com","double-dispatch/src/test/java/com/iluwatar","front-controller","reactor/src/test","api-gateway/price-microservice/src/test","null-object/src/test/java","strategy/src/test/java/com/iluwatar","observer/src/test/java/com/iluwatar/observer","hexagonal/src/test/java/com/iluwatar/hexagonal","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern","value-object/src/test","converter/src/test","dao/src","flux/src/test","composite/src","state/src/test/java","page-object/src/test/java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking","intercepting-filter/src/test/java/com/iluwatar/intercepting","fluentinterface/src","model-view-controller","factory-kit/src/test/java/com","aggregator-microservices/information-microservice","factory-kit/src/test/java/com/iluwatar/factorykit/app","lazy-loading/src/test/java/com/iluwatar","twin/src/test","abstract-document","api-gateway/api-gateway-service/src/test/java","chain/src/test/java","hexagonal/src/test/java","bridge/src/test","factory-method/src/test/java/com/iluwatar","iterator/src/test/java","model-view-controller/src/test/java","object-pool/src/test/java","poison-pill","builder/src/test/java/com/iluwatar","prototype/src/test","abstract-document/src/test/java/com","feature-toggle","singleton/src/test/java","reactor/src/test/java/com/iluwatar/reactor/app","thread-pool/src/test/java/com","layers","publish-subscribe","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices","page-object/src/test","memento","front-controller/src/test","twin/src/test/java/com","dao/src/test/java/com/iluwatar","guarded-suspension","facade/src/test/java/com/iluwatar","repository/src/test/java","tolerant-reader/src/test/java/com/iluwatar","singleton/src","promise/src/test/java/com","business-delegate","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar","builder/src/test/java/com","double-dispatch/src/test/java","resource-acquisition-is-initialization/src/test/java/com","reactor/src/test/java/com/iluwatar","business-delegate/src/test/java/com/iluwatar/business","mute-idiom/src/test/java/com/iluwatar","chain/src/test/java/com/iluwatar","strategy/src/test/java/com/iluwatar/strategy","eip-wire-tap/src/test","marker/src","fluentinterface/src/test","template-method/src","event-queue/src","null-object/src/test/java/com","prototype/src/test/java/com/iluwatar/prototype","business-delegate/src","double-checked-locking/src/test","tls","guarded-suspension/src/test/java/com","layers/src/test/java/com","service-layer/src/test/java/com/iluwatar/servicelayer/magic","template-method/src/test/java/com/iluwatar/templatemethod","property","abstract-factory/src/test/java","resource-acquisition-is-initialization","reactor/src","flux/src/test/java/com/iluwatar/flux/action","factory-kit/src","factory-method/src/test/java/com/iluwatar/factory/method","model-view-presenter/src/test/java","caching/src/test/java/com","balking/src","abstract-factory/src/test/java/com/iluwatar","singleton/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/database","lazy-loading/src/test/java/com/iluwatar/lazy","module/src/test/java/com/iluwatar/module","data-transfer-object/src/test/java/com/iluwatar","singleton/src/test/java/com/iluwatar/singleton","memento/src/test/java","mutex/src/test/java/com","reader-writer-lock/src/test/java","thread-pool/src/test/java","front-controller/src/test/java/com/iluwatar/front/controller","data-bus/src/test/java/com/iluwatar","event-aggregator/src/test/java/com/iluwatar","prototype","facade/src/test/java/com/iluwatar/facade","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway","data-bus/src/test/java/com","abstract-factory/src/test/java/com","event-queue","api-gateway/price-microservice/src/test/java","queue-load-leveling/src/test","property/src/test/java/com/iluwatar/property","data-mapper/src/test","front-controller/src/test/java/com","dependency-injection/src/test","specification/src/test","mediator/src/test/java/com","queue-load-leveling","event-driven-architecture/src/test/java/com/iluwatar/eda","page-object/src","eip-wire-tap/src/test/java","facade/src/test/java/com","builder/src","thread-pool","model-view-presenter/src/test/java/com/iluwatar/model","event-queue/src/test/java","visitor/src/test","mediator/src/test/java/com/iluwatar/mediator","layers/src","monad/src/test/java/com","state/src/test/java/com/iluwatar/state","api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice","lazy-loading/src/test/java","event-aggregator/src/test/java","double-dispatch/src/test","object-mother/src/test","double-dispatch","chain/src/test/java/com","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes","flux","interpreter/src/test/java","tls/src","tolerant-reader/src/test/java","half-sync-half-async/src/test/java/com","tolerant-reader/src/test/java/com/iluwatar/tolerantreader","double-checked-locking","fluentinterface","throttling/src/test/java/com","execute-around/src/test/java/com/iluwatar","half-sync-half-async/src/test/java/com/iluwatar","event-sourcing/src","service-layer/src/test/java/com/iluwatar/servicelayer/wizard","aggregator-microservices/information-microservice/src","retry/src/test/java/com","singleton/src/test","strategy","data-mapper/src/test/java/com","event-driven-architecture/src/test","intercepting-filter/src","message-channel/src/test/java/com/iluwatar/message/channel","double-checked-locking/src/test/java/com/iluwatar","fluentinterface/src/test/java/com/iluwatar/fluentinterface","abstract-document/src/test/java/com/iluwatar/abstractdocument","aggregator-microservices/aggregator-service","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice","repository/src","dao/src/test/java/com","producer-consumer/src/test/java/com/iluwatar/producer","retry/src","guarded-suspension/src/test/java/com/iluwatar/guarded","fluentinterface/src/test/java/com","state","half-sync-half-async/src","hexagonal/src","flyweight/src/test/java/com/iluwatar","abstract-factory/src","eip-aggregator","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter","event-queue/src/test/java/com/iluwatar","abstract-document/src","thread-pool/src/test/java/com/iluwatar/threadpool","proxy/src/test/java/com","async-method-invocation","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice","api-gateway/image-microservice/src/test/java","model-view-presenter/src/test","event-aggregator/src/test","builder","observer/src/test/java/com/iluwatar","api-gateway/image-microservice","flyweight/src/test","specification/src/test/java/com/iluwatar/specification/app","converter/src/test/java","twin/src/test/java/com/iluwatar/twin","event-asynchronous/src/test/java","mute-idiom","abstract-factory/src/test/java/com/iluwatar/abstractfactory","hexagonal/src/test/java/com/iluwatar/hexagonal/domain","value-object/src/test/java/com","decorator/src/test","thread-pool/src/test/java/com/iluwatar","builder/src/test/java/com/iluwatar/builder","data-transfer-object/src","iterator/src/test/java/com/iluwatar","feature-toggle/src/test/java/com","converter","page-object","api-gateway/image-microservice/src","cqrs/src/test/java/com/iluwatar","service-locator/src/test/java/com/iluwatar","object-pool/src/test/java/com/iluwatar/object","factory-method/src","api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice","factory-kit/src/test/java","model-view-presenter/src/test/java/com/iluwatar/model/view","message-channel/src/test/java","template-method/src/test/java/com","extension-objects","queue-load-leveling/src/test/java/com","semaphore/src/test","monad/src/test/java/com/iluwatar","async-method-invocation/src/test/java/com/iluwatar/async","abstract-factory","cqrs/src/test/java","delegation/src/test/java/com","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion","throttling/src/test/java/com/iluwatar/throttling","eip-splitter/src/test","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource","property/src","mediator/src","object-pool/src/test/java/com/iluwatar","service-locator/src/test/java","mediator/src/test/java","service-layer/src/test/java/com/iluwatar/servicelayer","flyweight/src","flyweight/src/test/java","producer-consumer/src/test","specification/src/test/java/com","feature-toggle/src/test","balking","eip-splitter/src","proxy/src/test/java/com/iluwatar","tls/src/test/java/com","bridge/src/test/java/com/iluwatar","facade/src/test","facade","semaphore/src","poison-pill/src/test/java/com","repository/src/test/java/com","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous","flux/src/test/java/com/iluwatar/flux/store","mute-idiom/src/test/java","decorator/src/test/java/com/iluwatar","async-method-invocation/src","command/src/test/java/com/iluwatar/command","module/src/test/java/com/iluwatar","caching/src/test/java","mutex/src/test","factory-kit","servant/src/test/java/com/iluwatar/servant","service-layer/src/test/java/com/iluwatar","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator","command/src/test/java/com","data-transfer-object/src/test","eip-aggregator/src/test/java/com/iluwatar/eip","api-gateway/price-microservice/src/test/java/com/iluwatar/price","semaphore/src/test/java/com","model-view-presenter/src","flux/src/test/java/com/iluwatar/flux/app","execute-around/src/test","publish-subscribe/src/test/java","servant/src/test/java/com","service-layer/src/test/java","step-builder/src","mutex/src","event-asynchronous/src/test/java/com/iluwatar","eip-aggregator/src/test","promise/src/test/java/com/iluwatar/promise","poison-pill/src/test/java/com/iluwatar/poison","tolerant-reader/src/test","flyweight","promise/src","balking/src/test/java/com/iluwatar","monad/src/test/java","message-channel","monad/src/test","multiton/src/test/java/com/iluwatar","feature-toggle/src/test/java/com/iluwatar/featuretoggle","event-queue/src/test","multiton/src/test/java/com/iluwatar/multiton","reader-writer-lock/src","throttling/src/test/java/com/iluwatar","chain","reader-writer-lock/src/test","prototype/src/test/java/com","decorator/src/test/java","dao/src/test","memento/src/test/java/com/iluwatar","promise/src/test/java/com/iluwatar","execute-around","eip-wire-tap/src","delegation/src/test","specification/src/test/java/com/iluwatar","tolerant-reader/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/banking","producer-consumer/src/test/java/com","multiton/src/test/java","object-pool/src/test","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api","event-queue/src/test/java/com/iluwatar/event","multiton","observer/src","queue-load-leveling/src/test/java/com/iluwatar","data-transfer-object/src/test/java","flux/src","null-object/src","resource-acquisition-is-initialization/src","caching","property/src/test/java/com/iluwatar","dao","callback/src/test/java/com/iluwatar/callback","business-delegate/src/test/java/com/iluwatar/business/delegate","template-method/src/test/java/com/iluwatar","model-view-controller/src","service-locator/src/test/java/com","iterator/src","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync","dependency-injection/src","multiton/src","object-mother/src/test/java/com/iluwatar/objectmother","private-class-data/src","double-dispatch/src","data-transfer-object/src/test/java/com/iluwatar/datatransfer","module/src/test/java","tls/src/test/java","throttling/src/test","marker","mutex/src/test/java","api-gateway","guarded-suspension/src","data-bus/src/test/java/com/iluwatar/databus","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes","reactor","message-channel/src/test/java/com/iluwatar","double-dispatch/src/test/java/com","thread-pool/src","api-gateway/image-microservice/src/test/java/com","factory-method/src/test/java","visitor/src/test/java/com/iluwatar/visitor","factory-method/src/test/java/com/iluwatar/factory","extension-objects/src","cqrs/src/test/java/com/iluwatar/cqrs","poison-pill/src/test/java/com/iluwatar/poison/pill","business-delegate/src/test/java/com","cqrs/src/test/java/com","composite/src/test/java/com/iluwatar/composite","factory-kit/src/test/java/com/iluwatar/factorykit","resource-acquisition-is-initialization/src/test","flux/src/test/java/com","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information","private-class-data/src/test/java/com","guarded-suspension/src/test/java/com/iluwatar/guarded/suspension","prototype/src/test/java/com/iluwatar","value-object/src/test/java/com/iluwatar/value/object","api-gateway/api-gateway-service/src/test/java/com","aggregator-microservices/information-microservice/src/test/java","command/src/test/java","page-object/src/test/java/com/iluwatar","double-checked-locking/src/test/java/com","mute-idiom/src/test","throttling/src","proxy/src/test","caching/src/test","poison-pill/src/test","model-view-controller/src/test/java/com/iluwatar/model/view","lazy-loading/src","retry/src/test/java/com/iluwatar/retry","layers/src/test/java/com/iluwatar/layers","proxy/src/test/java/com/iluwatar/proxy","adapter/src/test","facade/src","aggregator-microservices/aggregator-service/src/test/java","adapter/src/test/java","proxy","semaphore/src/test/java/com/iluwatar","intercepting-filter/src/test","service-locator/src/test","reactor/src/test/java/com","double-checked-locking/src/test/java/com/iluwatar/doublechecked","eip-aggregator/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog","abstract-document/src/test","intercepting-filter/src/test/java/com/iluwatar","factory-method/src/test/java/com","service-locator/src/test/java/com/iluwatar/servicelocator","factory-method","servant","extension-objects/src/test/java/units","aggregator-microservices/information-microservice/src/test","servant/src/test/java","eip-aggregator/src/test/java","private-class-data/src/test/java/com/iluwatar","strategy/src/test/java","event-sourcing/src/test","private-class-data","twin/src","message-channel/src/test/java/com/iluwatar/message","memento/src/test","eip-aggregator/src/test/java/com/iluwatar","factory-method/src/test","lazy-loading","object-mother/src/test/java/com/iluwatar/objectmother/test","interpreter/src/test/java/com/iluwatar/interpreter","state/src/test","balking/src/test/java/com","dependency-injection","poison-pill/src","promise","builder/src/test/java","aggregator-microservices/information-microservice/src/test/java/com/iluwatar","api-gateway/price-microservice","model-view-controller/src/test/java/com/iluwatar","chain/src/test/java/com/iluwatar/chain","mute-idiom/src/test/java/com/iluwatar/mute","half-sync-half-async","event-aggregator/src","api-gateway/image-microservice/src/test/java/com/iluwatar/image","visitor/src/test/java/com/iluwatar","factory-kit/src/test/java/com/iluwatar/factorykit/factorykit","mediator","hexagonal","async-method-invocation/src/test/java/com/iluwatar","step-builder/src/test/java/com/iluwatar","mute-idiom/src/test/java/com","step-builder/src/test/java/com/iluwatar/stepbuilder","flux/src/test/java/com/iluwatar/flux/view","observer/src/test/java/com/iluwatar/observer/generic","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation","callback/src/test","mutex/src/test/java/com/iluwatar","object-pool/src/test/java/com/iluwatar/object/pool","data-mapper/src","callback/src/test/java/com/iluwatar","object-mother","message-channel/src/test","interpreter/src","retry","composite/src/test/java/com","marker/src/test","twin/src/test/java","value-object/src/test/java/com/iluwatar","specification","strategy/src/test/java/com","execute-around/src/test/java/com/iluwatar/execute","async-method-invocation/src/test","bridge/src/test/java","mediator/src/test","data-bus/src/test/java/com/iluwatar/databus/members","monad/src/test/java/com/iluwatar/monad","command/src/test/java/com/iluwatar","object-pool","feature-toggle/src/test/java","state/src","composite/src/test/java","event-driven-architecture/src/test/java/com/iluwatar/eda/framework","private-class-data/src/test","iterator/src/test/java/com","service-locator/src","fluentinterface/src/test/java","thread-pool/src/test","intercepting-filter/src/test/java","retry/src/test","reactor/src/test/java","fluentinterface/src/test/java/com/iluwatar","caching/src/test/java/com/iluwatar","command/src/test","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator","data-transfer-object/src/test/java/com","monostate","memento/src/test/java/com/iluwatar/memento","service-layer/src/test/java/com/iluwatar/servicelayer/spellbook","queue-load-leveling/src","step-builder/src/test","reader-writer-lock/src/test/java/com/iluwatar","api-gateway/price-microservice/src/test/java/com/iluwatar","flux/src/test/java/com/iluwatar/flux/dispatcher","service-locator","tls/src/test/java/com/iluwatar","retry/src/test/java","event-driven-architecture/src/test/java","semaphore/src/test/java/com/iluwatar/semaphore","mute-idiom/src","module/src/test","data-mapper","event-driven-architecture","dependency-injection/src/test/java","converter/src/test/java/com","extension-objects/src/test/java/concreteextensions","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion","proxy/src","balking/src/test/java/com/iluwatar/balking","layers/src/test/java/com/iluwatar","value-object/src","data-bus/src/test","eip-wire-tap/src/test/java/com/iluwatar/eip","factory-kit/src/test","promise/src/test","memento/src/test/java/com","cqrs/src/test","adapter/src/test/java/com","business-delegate/src/test/java/com/iluwatar","decorator/src","caching/src/test/java/com/iluwatar/caching","guarded-suspension/src/test","memento/src","null-object","converter/src/test/java/com/iluwatar/converter","retry/src/test/java/com/iluwatar","eip-splitter/src/test/java/com/iluwatar/eip","producer-consumer","service-layer/src/test/java/com/iluwatar/servicelayer/app","event-asynchronous/src/test/java/com","business-delegate/src/test/java","callback/src/test/java/com","promise/src/test/java","publish-subscribe/src/test","delegation/src","visitor/src","multiton/src/test/java/com","repository/src/test/java/com/iluwatar","servant/src","caching/src","value-object/src/test/java","api-gateway/api-gateway-service/src/test","module/src/test/java/com","specification/src/test/java","event-queue/src/test/java/com/iluwatar/event/queue","guarded-suspension/src/test/java","dependency-injection/src/test/java/com/iluwatar/dependency","model-view-presenter/src/test/java/com/iluwatar","observer/src/test/java/com","aggregator-microservices","guarded-suspension/src/test/java/com/iluwatar","facade/src/test/java","aggregator-microservices/inventory-microservice/src/test","event-driven-architecture/src/test/java/com/iluwatar/eda/event","feature-toggle/src/test/java/com/iluwatar/featuretoggle/user","cqrs/src","data-mapper/src/test/java/com/iluwatar/datamapper","front-controller/src/test/java","producer-consumer/src/test/java/com/iluwatar/producer/consumer","producer-consumer/src","servant/src/test/java/com/iluwatar","event-driven-architecture/src","monostate/src/test/java/com","mutex/src/test/java/com/iluwatar/mutex","hexagonal/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src/test/java/com","producer-consumer/src/test/java","eip-splitter/src/test/java/com/iluwatar/eip/splitter","event-asynchronous/src/test/java/com/iluwatar/event","business-delegate/src/test","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition","reader-writer-lock/src/test/java/com","monad/src","api-gateway/image-microservice/src/test","publish-subscribe/src/test/java/com/iluwatar/publish/subscribe","lazy-loading/src/test","eip-wire-tap","execute-around/src/test/java/com/iluwatar/execute/around","layers/src/test/java","bridge/src/test/java/com/iluwatar/bridge","proxy/src/test/java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling","execute-around/src","event-driven-architecture/src/test/java/com","delegation/src/test/java","dao/src/test/java/com/iluwatar/dao","singleton/src/test/java/com/iluwatar","template-method/src/test/java","command/src","reactor/src/test/java/com/iluwatar/reactor","adapter/src","callback","data-bus/src/test/java","decorator/src/test/java/com","event-aggregator/src/test/java/com/iluwatar/event/aggregator","event-aggregator","event-aggregator/src/test/java/com","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization","callback/src/test/java","value-object/src/test/java/com/iluwatar/value","observer","iterator","dependency-injection/src/test/java/com/iluwatar/dependency/injection","composite","specification/src/test/java/com/iluwatar/specification/selector","monad","model-view-controller/src/test/java/com/iluwatar/model/view/controller","module","interpreter","aggregator-microservices/inventory-microservice/src/test/java","async-method-invocation/src/test/java","factory-kit/src/test/java/com/iluwatar","monostate/src/test/java/com/iluwatar","step-builder","multiton/src/test","service-layer/src/test","model-view-controller/src/test/java/com/iluwatar/model","abstract-document/src/test/java/com/iluwatar","intercepting-filter","semaphore","bridge","reader-writer-lock/src/test/java/com/iluwatar/reader/writer","state/src/test/java/com","property/src/test","event-sourcing","state/src/test/java/com/iluwatar","interpreter/src/test","decorator/src/test/java/com/iluwatar/decorator","layers/src/test","eip-splitter/src/test/java","tolerant-reader/src","monostate/src","half-sync-half-async/src/test","iterator/src/test/java/com/iluwatar/iterator","service-layer/src/test/java/com","private-class-data/src/test/java/com/iluwatar/privateclassdata","builder/src/test","tls/src/test","aggregator-microservices/aggregator-service/src/test","bridge/src/test/java/com","async-method-invocation/src/test/java/com","abstract-factory/src/test","object-mother/src","feature-toggle/src/test/java/com/iluwatar","balking/src/test/java","double-checked-locking/src/test/java","message-channel/src","event-asynchronous/src","aggregator-microservices/inventory-microservice/src/test/java/com","poison-pill/src/test/java","balking/src/test","repository/src/test/java/com/iluwatar/repository","property/src/test/java","flux/src/test/java/com/iluwatar/flux","queue-load-leveling/src/test/java/com/iluwatar/queue","data-bus/src","api-gateway/api-gateway-service","extension-objects/src/test/java","page-object/src/test/java/com/iluwatar/pageobject","composite/src/test","publish-subscribe/src/test/java/com","lazy-loading/src/test/java/com","prototype/src/test/java","property/src/test/java/com","throttling","null-object/src/test/java/com/iluwatar","null-object/src/test/java/com/iluwatar/nullobject","adapter/src/test/java/com/iluwatar","delegation/src/test/java/com/iluwatar/delegation/simple","twin","step-builder/src/test/java","singleton","visitor/src/test/java/com","resource-acquisition-is-initialization/src/test/java/com/iluwatar","object-pool/src/test/java/com","publish-subscribe/src/test/java/com/iluwatar/publish","publish-subscribe/src","template-method/src/test","cqrs","value-object","repository","observer/src/test/java","dependency-injection/src/test/java/com/iluwatar","bridge/src","half-sync-half-async/src/test/java","object-mother/src/test/java/com/iluwatar","service-layer/src","eip-splitter","converter/src/test/java/com/iluwatar","null-object/src/test","eip-wire-tap/src/test/java/com","api-gateway/api-gateway-service/src","strategy/src","eip-splitter/src/test/java/com","specification/src/test/java/com/iluwatar/specification/creature","template-method","decorator","monostate/src/test","observer/src/test","service-layer/src/test/java/com/iluwatar/servicelayer/common","delegation/src/test/java/com/iluwatar","mutex","double-checked-locking/src","iterator/src/test","data-bus","event-asynchronous","delegation/src/test/java/com/iluwatar/delegation","reader-writer-lock/src/test/java/com/iluwatar/reader","double-dispatch/src/test/java/com/iluwatar/doubledispatch","event-sourcing/src/test/java","resource-acquisition-is-initialization/src/test/java","interpreter/src/test/java/com/iluwatar","api-gateway/image-microservice/src/test/java/com/iluwatar","prototype/src","throttling/src/test/java","mediator/src/test/java/com/iluwatar","api-gateway/api-gateway-service/src/test/java/com/iluwatar","event-driven-architecture/src/test/java/com/iluwatar","front-controller/src/test/java/com/iluwatar","execute-around/src/test/java","tolerant-reader","repository/src/test","model-view-presenter/src/test/java/com","abstract-document/src/test/java","model-view-controller/src/test","api-gateway/price-microservice/src/test/java/com","queue-load-leveling/src/test/java/com/iluwatar/queue/load","flux/src/test/java","front-controller/src/test/java/com/iluwatar/front","composite/src/test/java/com/iluwatar","twin/src/test/java/com/iluwatar","event-queue/src/test/java/com","step-builder/src/test/java/com","model-view-presenter","callback/src","aggregator-microservices/inventory-microservice","poison-pill/src/test/java/com/iluwatar","semaphore/src/test/java","intercepting-filter/src/test/java/com","aggregator-microservices/inventory-microservice/src","eip-aggregator/src","page-object/src/test/java/com","execute-around/src/test/java/com","eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes","specification/src/test/java/com/iluwatar/specification","eip-splitter/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src","producer-consumer/src/test/java/com/iluwatar","service-layer","event-asynchronous/src/test","dependency-injection/src/test/java/com","marker/src/test/java","strategy/src/test","private-class-data/src/test/java","interpreter/src/test/java/com","visitor","api-gateway/price-microservice/src","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is","event-aggregator/src/test/java/com/iluwatar/event","chain/src/test","module/src","object-pool/src","converter/src","monostate/src/test/java/com/iluwatar/monostate","aggregator-microservices/information-microservice/src/test/java/com","adapter/src/test/java/com/iluwatar/adapter","lazy-loading/src/test/java/com/iluwatar/lazy/loading","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock","chain/src","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory","hexagonal/src/test","hexagonal/src/test/java/com","command","tls/src/test/java/com/iluwatar/tls","extension-objects/src/test","object-mother/src/test/java","data-transfer-object","object-mother/src/test/java/com","visitor/src/test/java","specification/src","delegation","model-view-controller/src/test/java/com","flyweight/src/test/java/com","data-mapper/src/test/java"],"repositoryDirectoriesCurrent":["fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable","async-method-invocation/src/test/java/com/iluwatar/async/method","dao/src/test/java","reader-writer-lock","servant/src/test","front-controller/src","feature-toggle/src","flyweight/src/test/java/com/iluwatar/flyweight","monostate/src/test/java","eip-wire-tap/src/test/java/com/iluwatar","queue-load-leveling/src/test/java","service-layer/src/test/java/com/iluwatar/servicelayer/spell","publish-subscribe/src/test/java/com/iluwatar","fluentinterface/src/test/java/com/iluwatar/fluentinterface/app","flux/src/test/java/com/iluwatar","adapter","data-mapper/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar","message-channel/src/test/java/com","double-dispatch/src/test/java/com/iluwatar","front-controller","reactor/src/test","api-gateway/price-microservice/src/test","null-object/src/test/java","strategy/src/test/java/com/iluwatar","observer/src/test/java/com/iluwatar/observer","hexagonal/src/test/java/com/iluwatar/hexagonal","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern","value-object/src/test","converter/src/test","dao/src","flux/src/test","composite/src","state/src/test/java","page-object/src/test/java","double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking","intercepting-filter/src/test/java/com/iluwatar/intercepting","fluentinterface/src","model-view-controller","factory-kit/src/test/java/com","aggregator-microservices/information-microservice","factory-kit/src/test/java/com/iluwatar/factorykit/app","lazy-loading/src/test/java/com/iluwatar","twin/src/test","abstract-document","api-gateway/api-gateway-service/src/test/java","chain/src/test/java","hexagonal/src/test/java","bridge/src/test","factory-method/src/test/java/com/iluwatar","iterator/src/test/java","model-view-controller/src/test/java","object-pool/src/test/java","poison-pill","builder/src/test/java/com/iluwatar","prototype/src/test","abstract-document/src/test/java/com","feature-toggle","singleton/src/test/java","reactor/src/test/java/com/iluwatar/reactor/app","thread-pool/src/test/java/com","layers","publish-subscribe","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices","page-object/src/test","memento","front-controller/src/test","twin/src/test/java/com","dao/src/test/java/com/iluwatar","guarded-suspension","facade/src/test/java/com/iluwatar","repository/src/test/java","tolerant-reader/src/test/java/com/iluwatar","singleton/src","promise/src/test/java/com","business-delegate","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar","builder/src/test/java/com","double-dispatch/src/test/java","resource-acquisition-is-initialization/src/test/java/com","reactor/src/test/java/com/iluwatar","business-delegate/src/test/java/com/iluwatar/business","mute-idiom/src/test/java/com/iluwatar","chain/src/test/java/com/iluwatar","strategy/src/test/java/com/iluwatar/strategy","eip-wire-tap/src/test","marker/src","fluentinterface/src/test","template-method/src","event-queue/src","null-object/src/test/java/com","prototype/src/test/java/com/iluwatar/prototype","business-delegate/src","double-checked-locking/src/test","tls","guarded-suspension/src/test/java/com","layers/src/test/java/com","service-layer/src/test/java/com/iluwatar/servicelayer/magic","template-method/src/test/java/com/iluwatar/templatemethod","property","abstract-factory/src/test/java","resource-acquisition-is-initialization","reactor/src","flux/src/test/java/com/iluwatar/flux/action","factory-kit/src","factory-method/src/test/java/com/iluwatar/factory/method","model-view-presenter/src/test/java","caching/src/test/java/com","balking/src","abstract-factory/src/test/java/com/iluwatar","singleton/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/database","lazy-loading/src/test/java/com/iluwatar/lazy","module/src/test/java/com/iluwatar/module","data-transfer-object/src/test/java/com/iluwatar","singleton/src/test/java/com/iluwatar/singleton","memento/src/test/java","mutex/src/test/java/com","reader-writer-lock/src/test/java","thread-pool/src/test/java","front-controller/src/test/java/com/iluwatar/front/controller","data-bus/src/test/java/com/iluwatar","event-aggregator/src/test/java/com/iluwatar","prototype","facade/src/test/java/com/iluwatar/facade","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway","data-bus/src/test/java/com","abstract-factory/src/test/java/com","event-queue","api-gateway/price-microservice/src/test/java","queue-load-leveling/src/test","property/src/test/java/com/iluwatar/property","data-mapper/src/test","front-controller/src/test/java/com","dependency-injection/src/test","specification/src/test","mediator/src/test/java/com","queue-load-leveling","event-driven-architecture/src/test/java/com/iluwatar/eda","page-object/src","eip-wire-tap/src/test/java","facade/src/test/java/com","builder/src","thread-pool","model-view-presenter/src/test/java/com/iluwatar/model","event-queue/src/test/java","visitor/src/test","mediator/src/test/java/com/iluwatar/mediator","layers/src","monad/src/test/java/com","state/src/test/java/com/iluwatar/state","api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice","lazy-loading/src/test/java","event-aggregator/src/test/java","double-dispatch/src/test","object-mother/src/test","double-dispatch","chain/src/test/java/com","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes","flux","interpreter/src/test/java","tls/src","tolerant-reader/src/test/java","half-sync-half-async/src/test/java/com","tolerant-reader/src/test/java/com/iluwatar/tolerantreader","double-checked-locking","fluentinterface","throttling/src/test/java/com","execute-around/src/test/java/com/iluwatar","half-sync-half-async/src/test/java/com/iluwatar","event-sourcing/src","service-layer/src/test/java/com/iluwatar/servicelayer/wizard","aggregator-microservices/information-microservice/src","retry/src/test/java/com","singleton/src/test","strategy","data-mapper/src/test/java/com","event-driven-architecture/src/test","intercepting-filter/src","message-channel/src/test/java/com/iluwatar/message/channel","double-checked-locking/src/test/java/com/iluwatar","fluentinterface/src/test/java/com/iluwatar/fluentinterface","abstract-document/src/test/java/com/iluwatar/abstractdocument","aggregator-microservices/aggregator-service","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice","repository/src","dao/src/test/java/com","producer-consumer/src/test/java/com/iluwatar/producer","retry/src","guarded-suspension/src/test/java/com/iluwatar/guarded","fluentinterface/src/test/java/com","state","half-sync-half-async/src","hexagonal/src","flyweight/src/test/java/com/iluwatar","abstract-factory/src","eip-aggregator","model-view-presenter/src/test/java/com/iluwatar/model/view/presenter","event-queue/src/test/java/com/iluwatar","abstract-document/src","thread-pool/src/test/java/com/iluwatar/threadpool","proxy/src/test/java/com","async-method-invocation","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice","api-gateway/image-microservice/src/test/java","model-view-presenter/src/test","event-aggregator/src/test","builder","observer/src/test/java/com/iluwatar","api-gateway/image-microservice","flyweight/src/test","specification/src/test/java/com/iluwatar/specification/app","converter/src/test/java","twin/src/test/java/com/iluwatar/twin","event-asynchronous/src/test/java","mute-idiom","abstract-factory/src/test/java/com/iluwatar/abstractfactory","hexagonal/src/test/java/com/iluwatar/hexagonal/domain","value-object/src/test/java/com","decorator/src/test","thread-pool/src/test/java/com/iluwatar","builder/src/test/java/com/iluwatar/builder","data-transfer-object/src","iterator/src/test/java/com/iluwatar","feature-toggle/src/test/java/com","converter","page-object","api-gateway/image-microservice/src","cqrs/src/test/java/com/iluwatar","service-locator/src/test/java/com/iluwatar","object-pool/src/test/java/com/iluwatar/object","factory-method/src","api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice","factory-kit/src/test/java","model-view-presenter/src/test/java/com/iluwatar/model/view","message-channel/src/test/java","template-method/src/test/java/com","extension-objects","queue-load-leveling/src/test/java/com","semaphore/src/test","monad/src/test/java/com/iluwatar","async-method-invocation/src/test/java/com/iluwatar/async","abstract-factory","cqrs/src/test/java","delegation/src/test/java/com","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion","throttling/src/test/java/com/iluwatar/throttling","eip-splitter/src/test","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource","property/src","mediator/src","object-pool/src/test/java/com/iluwatar","service-locator/src/test/java","mediator/src/test/java","service-layer/src/test/java/com/iluwatar/servicelayer","flyweight/src","flyweight/src/test/java","producer-consumer/src/test","specification/src/test/java/com","feature-toggle/src/test","balking","eip-splitter/src","proxy/src/test/java/com/iluwatar","tls/src/test/java/com","bridge/src/test/java/com/iluwatar","facade/src/test","facade","semaphore/src","poison-pill/src/test/java/com","repository/src/test/java/com","event-asynchronous/src/test/java/com/iluwatar/event/asynchronous","flux/src/test/java/com/iluwatar/flux/store","mute-idiom/src/test/java","decorator/src/test/java/com/iluwatar","async-method-invocation/src","command/src/test/java/com/iluwatar/command","module/src/test/java/com/iluwatar","caching/src/test/java","mutex/src/test","factory-kit","servant/src/test/java/com/iluwatar/servant","service-layer/src/test/java/com/iluwatar","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator","command/src/test/java/com","data-transfer-object/src/test","eip-aggregator/src/test/java/com/iluwatar/eip","api-gateway/price-microservice/src/test/java/com/iluwatar/price","semaphore/src/test/java/com","model-view-presenter/src","flux/src/test/java/com/iluwatar/flux/app","execute-around/src/test","publish-subscribe/src/test/java","servant/src/test/java/com","service-layer/src/test/java","step-builder/src","mutex/src","event-asynchronous/src/test/java/com/iluwatar","eip-aggregator/src/test","promise/src/test/java/com/iluwatar/promise","poison-pill/src/test/java/com/iluwatar/poison","tolerant-reader/src/test","flyweight","promise/src","balking/src/test/java/com/iluwatar","monad/src/test/java","message-channel","monad/src/test","multiton/src/test/java/com/iluwatar","feature-toggle/src/test/java/com/iluwatar/featuretoggle","event-queue/src/test","multiton/src/test/java/com/iluwatar/multiton","reader-writer-lock/src","throttling/src/test/java/com/iluwatar","chain","reader-writer-lock/src/test","prototype/src/test/java/com","decorator/src/test/java","dao/src/test","memento/src/test/java/com/iluwatar","promise/src/test/java/com/iluwatar","execute-around","eip-wire-tap/src","delegation/src/test","specification/src/test/java/com/iluwatar","tolerant-reader/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/banking","producer-consumer/src/test/java/com","multiton/src/test/java","object-pool/src/test","api-gateway/api-gateway-service/src/test/java/com/iluwatar/api","event-queue/src/test/java/com/iluwatar/event","multiton","observer/src","queue-load-leveling/src/test/java/com/iluwatar","data-transfer-object/src/test/java","flux/src","null-object/src","resource-acquisition-is-initialization/src","caching","property/src/test/java/com/iluwatar","dao","callback/src/test/java/com/iluwatar/callback","business-delegate/src/test/java/com/iluwatar/business/delegate","template-method/src/test/java/com/iluwatar","model-view-controller/src","service-locator/src/test/java/com","iterator/src","half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync","dependency-injection/src","multiton/src","object-mother/src/test/java/com/iluwatar/objectmother","private-class-data/src","double-dispatch/src","data-transfer-object/src/test/java/com/iluwatar/datatransfer","module/src/test/java","tls/src/test/java","throttling/src/test","marker","mutex/src/test/java","api-gateway","guarded-suspension/src","data-bus/src/test/java/com/iluwatar/databus","eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes","reactor","message-channel/src/test/java/com/iluwatar","double-dispatch/src/test/java/com","thread-pool/src","api-gateway/image-microservice/src/test/java/com","factory-method/src/test/java","visitor/src/test/java/com/iluwatar/visitor","factory-method/src/test/java/com/iluwatar/factory","extension-objects/src","cqrs/src/test/java/com/iluwatar/cqrs","poison-pill/src/test/java/com/iluwatar/poison/pill","business-delegate/src/test/java/com","cqrs/src/test/java/com","composite/src/test/java/com/iluwatar/composite","factory-kit/src/test/java/com/iluwatar/factorykit","resource-acquisition-is-initialization/src/test","flux/src/test/java/com","aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information","private-class-data/src/test/java/com","guarded-suspension/src/test/java/com/iluwatar/guarded/suspension","prototype/src/test/java/com/iluwatar","value-object/src/test/java/com/iluwatar/value/object","api-gateway/api-gateway-service/src/test/java/com","aggregator-microservices/information-microservice/src/test/java","command/src/test/java","page-object/src/test/java/com/iluwatar","double-checked-locking/src/test/java/com","mute-idiom/src/test","throttling/src","proxy/src/test","caching/src/test","poison-pill/src/test","model-view-controller/src/test/java/com/iluwatar/model/view","lazy-loading/src","retry/src/test/java/com/iluwatar/retry","layers/src/test/java/com/iluwatar/layers","proxy/src/test/java/com/iluwatar/proxy","adapter/src/test","facade/src","aggregator-microservices/aggregator-service/src/test/java","adapter/src/test/java","proxy","semaphore/src/test/java/com/iluwatar","intercepting-filter/src/test","service-locator/src/test","reactor/src/test/java/com","double-checked-locking/src/test/java/com/iluwatar/doublechecked","eip-aggregator/src/test/java/com","hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog","abstract-document/src/test","intercepting-filter/src/test/java/com/iluwatar","factory-method/src/test/java/com","service-locator/src/test/java/com/iluwatar/servicelocator","factory-method","servant","extension-objects/src/test/java/units","aggregator-microservices/information-microservice/src/test","servant/src/test/java","eip-aggregator/src/test/java","private-class-data/src/test/java/com/iluwatar","strategy/src/test/java","event-sourcing/src/test","private-class-data","twin/src","message-channel/src/test/java/com/iluwatar/message","memento/src/test","eip-aggregator/src/test/java/com/iluwatar","factory-method/src/test","lazy-loading","object-mother/src/test/java/com/iluwatar/objectmother/test","interpreter/src/test/java/com/iluwatar/interpreter","state/src/test","balking/src/test/java/com","dependency-injection","poison-pill/src","promise","builder/src/test/java","aggregator-microservices/information-microservice/src/test/java/com/iluwatar","api-gateway/price-microservice","model-view-controller/src/test/java/com/iluwatar","chain/src/test/java/com/iluwatar/chain","mute-idiom/src/test/java/com/iluwatar/mute","half-sync-half-async","event-aggregator/src","api-gateway/image-microservice/src/test/java/com/iluwatar/image","visitor/src/test/java/com/iluwatar","factory-kit/src/test/java/com/iluwatar/factorykit/factorykit","mediator","hexagonal","async-method-invocation/src/test/java/com/iluwatar","step-builder/src/test/java/com/iluwatar","mute-idiom/src/test/java/com","step-builder/src/test/java/com/iluwatar/stepbuilder","flux/src/test/java/com/iluwatar/flux/view","observer/src/test/java/com/iluwatar/observer/generic","async-method-invocation/src/test/java/com/iluwatar/async/method/invocation","callback/src/test","mutex/src/test/java/com/iluwatar","object-pool/src/test/java/com/iluwatar/object/pool","data-mapper/src","callback/src/test/java/com/iluwatar","object-mother","message-channel/src/test","interpreter/src","retry","composite/src/test/java/com","marker/src/test","twin/src/test/java","value-object/src/test/java/com/iluwatar","specification","strategy/src/test/java/com","execute-around/src/test/java/com/iluwatar/execute","async-method-invocation/src/test","bridge/src/test/java","mediator/src/test","data-bus/src/test/java/com/iluwatar/databus/members","monad/src/test/java/com/iluwatar/monad","command/src/test/java/com/iluwatar","object-pool","feature-toggle/src/test/java","state/src","composite/src/test/java","event-driven-architecture/src/test/java/com/iluwatar/eda/framework","private-class-data/src/test","iterator/src/test/java/com","service-locator/src","fluentinterface/src/test/java","thread-pool/src/test","intercepting-filter/src/test/java","retry/src/test","reactor/src/test/java","fluentinterface/src/test/java/com/iluwatar","caching/src/test/java/com/iluwatar","command/src/test","aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator","data-transfer-object/src/test/java/com","monostate","memento/src/test/java/com/iluwatar/memento","service-layer/src/test/java/com/iluwatar/servicelayer/spellbook","queue-load-leveling/src","step-builder/src/test","reader-writer-lock/src/test/java/com/iluwatar","api-gateway/price-microservice/src/test/java/com/iluwatar","flux/src/test/java/com/iluwatar/flux/dispatcher","service-locator","tls/src/test/java/com/iluwatar","retry/src/test/java","event-driven-architecture/src/test/java","semaphore/src/test/java/com/iluwatar/semaphore","mute-idiom/src","module/src/test","data-mapper","event-driven-architecture","dependency-injection/src/test/java","converter/src/test/java/com","extension-objects/src/test/java/concreteextensions","feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion","proxy/src","balking/src/test/java/com/iluwatar/balking","layers/src/test/java/com/iluwatar","value-object/src","data-bus/src/test","eip-wire-tap/src/test/java/com/iluwatar/eip","factory-kit/src/test","promise/src/test","memento/src/test/java/com","cqrs/src/test","adapter/src/test/java/com","business-delegate/src/test/java/com/iluwatar","decorator/src","caching/src/test/java/com/iluwatar/caching","guarded-suspension/src/test","memento/src","null-object","converter/src/test/java/com/iluwatar/converter","retry/src/test/java/com/iluwatar","eip-splitter/src/test/java/com/iluwatar/eip","producer-consumer","service-layer/src/test/java/com/iluwatar/servicelayer/app","event-asynchronous/src/test/java/com","business-delegate/src/test/java","callback/src/test/java/com","promise/src/test/java","publish-subscribe/src/test","delegation/src","visitor/src","multiton/src/test/java/com","repository/src/test/java/com/iluwatar","servant/src","caching/src","value-object/src/test/java","api-gateway/api-gateway-service/src/test","module/src/test/java/com","specification/src/test/java","event-queue/src/test/java/com/iluwatar/event/queue","guarded-suspension/src/test/java","dependency-injection/src/test/java/com/iluwatar/dependency","model-view-presenter/src/test/java/com/iluwatar","observer/src/test/java/com","aggregator-microservices","guarded-suspension/src/test/java/com/iluwatar","facade/src/test/java","aggregator-microservices/inventory-microservice/src/test","event-driven-architecture/src/test/java/com/iluwatar/eda/event","feature-toggle/src/test/java/com/iluwatar/featuretoggle/user","cqrs/src","data-mapper/src/test/java/com/iluwatar/datamapper","front-controller/src/test/java","producer-consumer/src/test/java/com/iluwatar/producer/consumer","producer-consumer/src","servant/src/test/java/com/iluwatar","event-driven-architecture/src","monostate/src/test/java/com","mutex/src/test/java/com/iluwatar/mutex","hexagonal/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src/test/java/com","producer-consumer/src/test/java","eip-splitter/src/test/java/com/iluwatar/eip/splitter","event-asynchronous/src/test/java/com/iluwatar/event","business-delegate/src/test","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition","reader-writer-lock/src/test/java/com","monad/src","api-gateway/image-microservice/src/test","publish-subscribe/src/test/java/com/iluwatar/publish/subscribe","lazy-loading/src/test","eip-wire-tap","execute-around/src/test/java/com/iluwatar/execute/around","layers/src/test/java","bridge/src/test/java/com/iluwatar/bridge","proxy/src/test/java","queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling","execute-around/src","event-driven-architecture/src/test/java/com","delegation/src/test/java","dao/src/test/java/com/iluwatar/dao","singleton/src/test/java/com/iluwatar","template-method/src/test/java","command/src","reactor/src/test/java/com/iluwatar/reactor","adapter/src","callback","data-bus/src/test/java","decorator/src/test/java/com","event-aggregator/src/test/java/com/iluwatar/event/aggregator","event-aggregator","event-aggregator/src/test/java/com","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization","callback/src/test/java","value-object/src/test/java/com/iluwatar/value","observer","iterator","dependency-injection/src/test/java/com/iluwatar/dependency/injection","composite","specification/src/test/java/com/iluwatar/specification/selector","monad","model-view-controller/src/test/java/com/iluwatar/model/view/controller","module","interpreter","aggregator-microservices/inventory-microservice/src/test/java","async-method-invocation/src/test/java","factory-kit/src/test/java/com/iluwatar","monostate/src/test/java/com/iluwatar","step-builder","multiton/src/test","service-layer/src/test","model-view-controller/src/test/java/com/iluwatar/model","abstract-document/src/test/java/com/iluwatar","intercepting-filter","semaphore","bridge","reader-writer-lock/src/test/java/com/iluwatar/reader/writer","state/src/test/java/com","property/src/test","event-sourcing","state/src/test/java/com/iluwatar","interpreter/src/test","decorator/src/test/java/com/iluwatar/decorator","layers/src/test","eip-splitter/src/test/java","tolerant-reader/src","monostate/src","half-sync-half-async/src/test","iterator/src/test/java/com/iluwatar/iterator","service-layer/src/test/java/com","private-class-data/src/test/java/com/iluwatar/privateclassdata","builder/src/test","tls/src/test","aggregator-microservices/aggregator-service/src/test","bridge/src/test/java/com","async-method-invocation/src/test/java/com","abstract-factory/src/test","object-mother/src","feature-toggle/src/test/java/com/iluwatar","balking/src/test/java","double-checked-locking/src/test/java","message-channel/src","event-asynchronous/src","aggregator-microservices/inventory-microservice/src/test/java/com","poison-pill/src/test/java","balking/src/test","repository/src/test/java/com/iluwatar/repository","property/src/test/java","flux/src/test/java/com/iluwatar/flux","queue-load-leveling/src/test/java/com/iluwatar/queue","data-bus/src","api-gateway/api-gateway-service","extension-objects/src/test/java","page-object/src/test/java/com/iluwatar/pageobject","composite/src/test","publish-subscribe/src/test/java/com","lazy-loading/src/test/java/com","prototype/src/test/java","property/src/test/java/com","throttling","null-object/src/test/java/com/iluwatar","null-object/src/test/java/com/iluwatar/nullobject","adapter/src/test/java/com/iluwatar","delegation/src/test/java/com/iluwatar/delegation/simple","twin","step-builder/src/test/java","singleton","visitor/src/test/java/com","resource-acquisition-is-initialization/src/test/java/com/iluwatar","object-pool/src/test/java/com","publish-subscribe/src/test/java/com/iluwatar/publish","publish-subscribe/src","template-method/src/test","cqrs","value-object","repository","observer/src/test/java","dependency-injection/src/test/java/com/iluwatar","bridge/src","half-sync-half-async/src/test/java","object-mother/src/test/java/com/iluwatar","service-layer/src","eip-splitter","converter/src/test/java/com/iluwatar","null-object/src/test","eip-wire-tap/src/test/java/com","api-gateway/api-gateway-service/src","strategy/src","eip-splitter/src/test/java/com","specification/src/test/java/com/iluwatar/specification/creature","template-method","decorator","monostate/src/test","observer/src/test","service-layer/src/test/java/com/iluwatar/servicelayer/common","delegation/src/test/java/com/iluwatar","mutex","double-checked-locking/src","iterator/src/test","data-bus","event-asynchronous","delegation/src/test/java/com/iluwatar/delegation","reader-writer-lock/src/test/java/com/iluwatar/reader","double-dispatch/src/test/java/com/iluwatar/doubledispatch","event-sourcing/src/test/java","resource-acquisition-is-initialization/src/test/java","interpreter/src/test/java/com/iluwatar","api-gateway/image-microservice/src/test/java/com/iluwatar","prototype/src","throttling/src/test/java","mediator/src/test/java/com/iluwatar","api-gateway/api-gateway-service/src/test/java/com/iluwatar","event-driven-architecture/src/test/java/com/iluwatar","front-controller/src/test/java/com/iluwatar","execute-around/src/test/java","tolerant-reader","repository/src/test","model-view-presenter/src/test/java/com","abstract-document/src/test/java","model-view-controller/src/test","api-gateway/price-microservice/src/test/java/com","queue-load-leveling/src/test/java/com/iluwatar/queue/load","flux/src/test/java","front-controller/src/test/java/com/iluwatar/front","composite/src/test/java/com/iluwatar","twin/src/test/java/com/iluwatar","event-queue/src/test/java/com","step-builder/src/test/java/com","model-view-presenter","callback/src","aggregator-microservices/inventory-microservice","poison-pill/src/test/java/com/iluwatar","semaphore/src/test/java","intercepting-filter/src/test/java/com","aggregator-microservices/inventory-microservice/src","eip-aggregator/src","page-object/src/test/java/com","execute-around/src/test/java/com","eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes","specification/src/test/java/com/iluwatar/specification","eip-splitter/src/test/java/com/iluwatar","aggregator-microservices/aggregator-service/src","producer-consumer/src/test/java/com/iluwatar","service-layer","event-asynchronous/src/test","dependency-injection/src/test/java/com","marker/src/test/java","strategy/src/test","private-class-data/src/test/java","interpreter/src/test/java/com","visitor","api-gateway/price-microservice/src","intercepting-filter/src/test/java/com/iluwatar/intercepting/filter","resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is","event-aggregator/src/test/java/com/iluwatar/event","chain/src/test","module/src","object-pool/src","converter/src","monostate/src/test/java/com/iluwatar/monostate","aggregator-microservices/information-microservice/src/test/java/com","adapter/src/test/java/com/iluwatar/adapter","lazy-loading/src/test/java/com/iluwatar/lazy/loading","reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock","chain/src","eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap","aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory","hexagonal/src/test","hexagonal/src/test/java/com","command","tls/src/test/java/com/iluwatar/tls","extension-objects/src/test","object-mother/src/test/java","data-transfer-object","object-mother/src/test/java/com","visitor/src/test/java","specification/src","delegation","model-view-controller/src/test/java/com","flyweight/src/test/java/com","data-mapper/src/test/java"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java new file mode 100644 index 0000000000..63a9974b99 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * AbstractDocument test class + */ +public class AbstractDocumentTest { + + private static final String KEY = "key"; + private static final String VALUE = "value"; + + private class DocumentImplementation extends AbstractDocument { + + DocumentImplementation(Map properties) { + super(properties); + } + } + + private DocumentImplementation document = new DocumentImplementation(new HashMap<>()); + + @Test + public void shouldPutAndGetValue() { + document.put(KEY, VALUE); + assertEquals(VALUE, document.get(KEY)); + } + + @Test + public void shouldRetrieveChildren() { + Map child1 = new HashMap<>(); + Map child2 = new HashMap<>(); + List> children = Arrays.asList(child1, child2); + + document.put(KEY, children); + + Stream childrenStream = document.children(KEY, DocumentImplementation::new); + assertNotNull(children); + assertEquals(2, childrenStream.count()); + } + + @Test + public void shouldRetrieveEmptyStreamForNonExistingChildren() { + Stream children = document.children(KEY, DocumentImplementation::new); + assertNotNull(children); + assertEquals(0, children.count()); + } + + @Test + public void shouldIncludePropsInToString() { + Map props = new HashMap<>(); + props.put(KEY, VALUE); + DocumentImplementation document = new DocumentImplementation(props); + assertNotNull(document.toString().contains(KEY)); + assertNotNull(document.toString().contains(VALUE)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java new file mode 100644 index 0000000000..0546be523f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import org.junit.jupiter.api.Test; + +/** + * Simple App test + */ +public class AppTest { + + @Test + public void shouldExecuteAppWithoutException() { + App.main(null); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java new file mode 100644 index 0000000000..891e5a4576 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import com.iluwatar.abstractdocument.domain.Car; +import com.iluwatar.abstractdocument.domain.HasModel; +import com.iluwatar.abstractdocument.domain.HasParts; +import com.iluwatar.abstractdocument.domain.HasPrice; +import com.iluwatar.abstractdocument.domain.HasType; +import com.iluwatar.abstractdocument.domain.Part; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Part and Car + */ +public class DomainTest { + + private static final String TEST_PART_TYPE = "test-part-type"; + private static final String TEST_PART_MODEL = "test-part-model"; + private static final long TEST_PART_PRICE = 0L; + + private static final String TEST_CAR_MODEL = "test-car-model"; + private static final long TEST_CAR_PRICE = 1L; + + @Test + public void shouldConstructPart() { + Map partProperties = new HashMap<>(); + partProperties.put(HasType.PROPERTY, TEST_PART_TYPE); + partProperties.put(HasModel.PROPERTY, TEST_PART_MODEL); + partProperties.put(HasPrice.PROPERTY, TEST_PART_PRICE); + Part part = new Part(partProperties); + + assertEquals(TEST_PART_TYPE, part.getType().get()); + assertEquals(TEST_PART_MODEL, part.getModel().get()); + assertEquals(TEST_PART_PRICE, part.getPrice().get()); + } + + @Test + public void shouldConstructCar() { + Map carProperties = new HashMap<>(); + carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL); + carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE); + carProperties.put(HasParts.PROPERTY, Arrays.asList(new HashMap<>(), new HashMap<>())); + Car car = new Car(carProperties); + + assertEquals(TEST_CAR_MODEL, car.getModel().get()); + assertEquals(TEST_CAR_PRICE, car.getPrice().get()); + assertEquals(2, car.getParts().count()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java new file mode 100644 index 0000000000..5940da6c1a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -0,0 +1,106 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractfactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.iluwatar.abstractfactory.App.FactoryMaker; +import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Test for abstract factory + */ +public class AbstractFactoryTest { + + private App app = new App(); + private KingdomFactory elfFactory; + private KingdomFactory orcFactory; + + @BeforeEach + public void setUp() { + elfFactory = FactoryMaker.makeFactory(KingdomType.ELF); + orcFactory = FactoryMaker.makeFactory(KingdomType.ORC); + } + + @Test + public void king() { + final King elfKing = app.getKing(elfFactory); + assertTrue(elfKing instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); + final King orcKing = app.getKing(orcFactory); + assertTrue(orcKing instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); + } + + @Test + public void castle() { + final Castle elfCastle = app.getCastle(elfFactory); + assertTrue(elfCastle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); + final Castle orcCastle = app.getCastle(orcFactory); + assertTrue(orcCastle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); + } + + @Test + public void army() { + final Army elfArmy = app.getArmy(elfFactory); + assertTrue(elfArmy instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); + final Army orcArmy = app.getArmy(orcFactory); + assertTrue(orcArmy instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); + } + + @Test + public void createElfKingdom() { + app.createKingdom(elfFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, army.getDescription()); + } + + @Test + public void createOrcKingdom() { + app.createKingdom(orcFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, army.getDescription()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java new file mode 100644 index 0000000000..80c2815dcc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractfactory; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Abstract Factory example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java new file mode 100644 index 0000000000..033440b812 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.adapter; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Test class + * + */ +public class AdapterPatternTest { + + private Map beans; + + private static final String FISHING_BEAN = "fisher"; + + private static final String ROWING_BEAN = "captain"; + + /** + * This method runs before the test execution and sets the bean objects in the beans Map. + */ + @BeforeEach + public void setup() { + beans = new HashMap<>(); + + FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter()); + beans.put(FISHING_BEAN, fishingBoatAdapter); + + Captain captain = new Captain(); + captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN)); + beans.put(ROWING_BEAN, captain); + } + + /** + * This test asserts that when we use the row() method on a captain bean(client), it is + * internally calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter} + * ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one + * expected by the client ({@link Captain} ). + */ + @Test + public void testAdapter() { + RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN); + + // when captain moves + captain.row(); + + // the captain internally calls the battleship object to move + RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN); + verify(adapter).row(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AppTest.java new file mode 100644 index 0000000000..ca2c103c35 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.adapter; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Adapter example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java new file mode 100644 index 0000000000..bc07ccc211 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.aggregator.microservices; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +/** + * Test Aggregation of domain objects + */ +public class AggregatorTest { + + @InjectMocks + private Aggregator aggregator; + + @Mock + private ProductInformationClient informationClient; + + @Mock + private ProductInventoryClient inventoryClient; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + } + + /** + * Tests getting the data for a desktop client + */ + @Test + public void testGetProduct() { + String title = "The Product Title."; + int inventories = 5; + + when(informationClient.getProductTitle()).thenReturn(title); + when(inventoryClient.getProductInventories()).thenReturn(inventories); + + Product testProduct = aggregator.getProduct(); + + assertEquals(title, testProduct.getTitle()); + assertEquals(inventories, testProduct.getProductInventories()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java new file mode 100644 index 0000000000..d030cfcb4d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java @@ -0,0 +1,43 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.information.microservice; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Information Rest Controller + */ +public class InformationControllerTest { + + @Test + public void shouldGetProductTitle() { + InformationController infoController = new InformationController(); + + String title = infoController.getProductTitle(); + + assertEquals("The Product Title.", title); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java new file mode 100644 index 0000000000..78af8582e0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.inventory.microservice; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test Inventory Rest Controller + */ +public class InventoryControllerTest { + @Test + public void testGetProductInventories() throws Exception { + InventoryController inventoryController = new InventoryController(); + + int numberOfInventories = inventoryController.getProductInventories(); + + assertEquals(5, numberOfInventories); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java new file mode 100644 index 0000000000..a86d991c8e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java @@ -0,0 +1,81 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.api.gateway; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +/** + * Test API Gateway Pattern + */ +public class ApiGatewayTest { + + @InjectMocks + private ApiGateway apiGateway; + + @Mock + private ImageClient imageClient; + + @Mock + private PriceClient priceClient; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + } + + /** + * Tests getting the data for a desktop client + */ + @Test + public void testGetProductDesktop() { + String imagePath = "/product-image.png"; + String price = "20"; + when(imageClient.getImagePath()).thenReturn(imagePath); + when(priceClient.getPrice()).thenReturn(price); + + DesktopProduct desktopProduct = apiGateway.getProductDesktop(); + + assertEquals(price, desktopProduct.getPrice()); + assertEquals(imagePath, desktopProduct.getImagePath()); + } + + /** + * Tests getting the data for a mobile client + */ + @Test + public void testGetProductMobile() { + String price = "20"; + when(priceClient.getPrice()).thenReturn(price); + + MobileProduct mobileProduct = apiGateway.getProductMobile(); + + assertEquals(price, mobileProduct.getPrice()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java new file mode 100644 index 0000000000..df9b479aed --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.image.microservice; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Image Rest Controller + */ +public class ImageControllerTest { + @Test + public void testGetImagePath() { + ImageController imageController = new ImageController(); + + String imagePath = imageController.getImagePath(); + + assertEquals("/product-image.png", imagePath); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java new file mode 100644 index 0000000000..679fb601b7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.price.microservice; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Price Rest Controller + */ +public class PriceControllerTest { + @Test + public void testgetPrice() { + PriceController priceController = new PriceController(); + + String price = priceController.getPrice(); + + assertEquals("20", price); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java new file mode 100644 index 0000000000..a2744306e1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.async.method.invocation; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java new file mode 100644 index 0000000000..b5c4fff674 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -0,0 +1,343 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.async.method.invocation; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; + +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Date: 12/6/15 - 10:49 AM + * + * @author Jeroen Meulemeester + */ +public class ThreadAsyncExecutorTest { + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} + */ + @Test + public void testSuccessfulTaskWithoutCallback() throws Exception { + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} + */ + @Test + public void testSuccessfulTaskWithCallback() throws Exception { + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); + + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... same for the callback, we expect our object + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute + */ + @Test + public void testLongRunningTaskWithoutCallback() throws Exception { + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task + * takes a while to execute + */ + @Test + public void testLongRunningTaskWithCallback() throws Exception { + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + verifyZeroInteractions(callback); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task, callback); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + }); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} + */ + @Test + public void testEndProcess() throws Exception { + assertTimeout(ofMillis(5000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + assertSame(result, executor.endProcess(asyncResult)); + verify(task, times(1)).call(); + assertTrue(asyncResult.isCompleted()); + + // Calling end process a second time while already finished should give the same result + assertSame(result, executor.endProcess(asyncResult)); + verifyNoMoreInteractions(task); + }); + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' + */ + @Test + public void testNullTask() throws Exception { + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null); + + assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); + + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the + * callable is 'null', but the asynchronous callback is provided + */ + @Test + public void testNullTaskWithCallback() throws Exception { + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(null, callback); + + assertNotNull(asyncResult, "The AsyncResult should not be 'null', even though the task was 'null'."); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertTrue(optionalException.isPresent()); + + final Exception exception = optionalException.get(); + assertNotNull(exception); + assertEquals(NullPointerException.class, exception.getClass()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); + + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both + * the callable and the asynchronous callback are 'null' + */ + @Test + public void testNullTaskWithNullCallback() throws Exception { + assertTimeout(ofMillis(3000), () -> { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null, null); + + assertNotNull( + asyncResult, + "The AsyncResult should not be 'null', even though the task and callback were 'null'." + ); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + }); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/AppTest.java new file mode 100644 index 0000000000..87941dc27d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.balking; + +import org.junit.jupiter.api.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void main() throws Exception { + String[] args = {}; + App.main(args); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java new file mode 100644 index 0000000000..47957835d0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -0,0 +1,65 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.balking; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for {@link WashingMachine} + */ +public class WashingMachineTest { + + private volatile WashingMachineState machineStateGlobal; + + @Test + public void wash() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.execute(washingMachine::wash); + executorService.execute(() -> { + washingMachine.wash(); + machineStateGlobal = washingMachine.getWashingMachineState(); + }); + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + assertEquals(WashingMachineState.WASHING, machineStateGlobal); + } + + @Test + public void endOfWashing() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + washingMachine.wash(); + assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/AppTest.java new file mode 100644 index 0000000000..233f1d481e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java new file mode 100644 index 0000000000..4cb3bd69e9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +/** + * Tests for hammer + */ +public class HammerTest extends WeaponTest { + + /** + * Invoke all possible actions on the weapon and check if the actions are executed on the actual + * underlying weapon implementation. + */ + @Test + public void testHammer() throws Exception { + final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class))); + testBasicWeaponActions(hammer); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java new file mode 100644 index 0000000000..e1cccb39af --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +/** + * Tests for sword + */ +public class SwordTest extends WeaponTest { + + /** + * Invoke all possible actions on the weapon and check if the actions are executed on the actual + * underlying weapon implementation. + */ + @Test + public void testSword() throws Exception { + final Sword sword = spy(new Sword(mock(FlyingEnchantment.class))); + testBasicWeaponActions(sword); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java new file mode 100644 index 0000000000..e8518eb50b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.jupiter.api.Disabled; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Base class for weapon tests + */ +public abstract class WeaponTest { + + /** + * Invoke the basic actions of the given weapon, and test if the underlying enchantment implementation + * is invoked + * + */ + protected final void testBasicWeaponActions(final Weapon weapon) { + assertNotNull(weapon); + Enchantment enchantment = weapon.getEnchantment(); + assertNotNull(enchantment); + assertNotNull(weapon.getEnchantment()); + + weapon.swing(); + verify(enchantment).apply(); + verifyNoMoreInteractions(enchantment); + + weapon.wield(); + verify(enchantment).onActivate(); + verifyNoMoreInteractions(enchantment); + + weapon.unwield(); + verify(enchantment).onDeactivate(); + verifyNoMoreInteractions(enchantment); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/AppTest.java new file mode 100644 index 0000000000..abaaa034f7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.builder; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/HeroTest.java new file mode 100644 index 0000000000..aa2e1490f7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/builder/src/test/java/com/iluwatar/builder/HeroTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.builder; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Date: 12/6/15 - 11:01 PM + * + * @author Jeroen Meulemeester + */ +public class HeroTest { + + /** + * Test if we get the expected exception when trying to create a hero without a profession + */ + @Test + public void testMissingProfession() throws Exception { + assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(null, "Sir without a job")); + } + + /** + * Test if we get the expected exception when trying to create a hero without a name + */ + @Test + public void testMissingName() throws Exception { + assertThrows(IllegalArgumentException.class, () -> new Hero.Builder(Profession.THIEF, null)); + } + + /** + * Test if the hero build by the builder has the correct attributes, as requested + */ + @Test + public void testBuildHero() throws Exception { + final String heroName = "Sir Lancelot"; + + final Hero hero = new Hero.Builder(Profession.WARRIOR, heroName) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) + .withHairType(HairType.LONG_CURLY) + .withHairColor(HairColor.BLOND) + .build(); + + assertNotNull(hero); + assertNotNull(hero.toString()); + assertEquals(Profession.WARRIOR, hero.getProfession()); + assertEquals(heroName, hero.getName()); + assertEquals(Armor.CHAIN_MAIL, hero.getArmor()); + assertEquals(Weapon.SWORD, hero.getWeapon()); + assertEquals(HairType.LONG_CURLY, hero.getHairType()); + assertEquals(HairColor.BLOND, hero.getHairColor()); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java new file mode 100644 index 0000000000..415f855d1d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.business.delegate; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Business Delegate example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java new file mode 100644 index 0000000000..ccdaaae4ea --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.business.delegate; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * The Business Delegate pattern adds an abstraction layer between the presentation and business + * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate + * encapsulates knowledge about how to locate, connect to, and interact with the business objects + * that make up the application. + * + *

Some of the services the Business Delegate uses are instantiated directly, and some can be + * retrieved through service lookups. The Business Delegate itself may contain business logic too + * potentially tying together multiple service calls, exception handling, retrying etc. + */ +public class BusinessDelegateTest { + + private EjbService ejbService; + + private JmsService jmsService; + + private BusinessLookup businessLookup; + + private BusinessDelegate businessDelegate; + + /** + * This method sets up the instance variables of this test class. It is executed before the + * execution of every test. + */ + @BeforeEach + public void setup() { + ejbService = spy(new EjbService()); + jmsService = spy(new JmsService()); + + businessLookup = spy(new BusinessLookup()); + businessLookup.setEjbService(ejbService); + businessLookup.setJmsService(jmsService); + + businessDelegate = spy(new BusinessDelegate()); + businessDelegate.setLookupService(businessLookup); + } + + /** + * In this example the client ({@link Client}) utilizes a business delegate ( + * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate + * service and makes the service call. + */ + @Test + public void testBusinessDelegate() { + + // setup a client object + Client client = new Client(businessDelegate); + + // set the service type + businessDelegate.setServiceType(ServiceType.EJB); + + // action + client.doTask(); + + // verifying that the businessDelegate was used by client during doTask() method. + verify(businessDelegate).doTask(); + verify(ejbService).doProcessing(); + + // set the service type + businessDelegate.setServiceType(ServiceType.JMS); + + // action + client.doTask(); + + // verifying that the businessDelegate was used by client during doTask() method. + verify(businessDelegate, times(2)).doTask(); + verify(jmsService).doProcessing(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/AppTest.java new file mode 100644 index 0000000000..32935bf24a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.caching; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Caching example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/CachingTest.java new file mode 100644 index 0000000000..0a7e8aed38 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/caching/src/test/java/com/iluwatar/caching/CachingTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.caching; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class CachingTest { + App app; + + /** + * Setup of application test includes: initializing DB connection and cache size/capacity. + */ + @BeforeEach + public void setUp() { + AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests + // to avoid Maven compilation errors. Set flag to true to run the + // tests with MongoDB (provided that MongoDB is installed and socket + // connection is open). + AppManager.initCacheCapacity(3); + app = new App(); + } + + @Test + public void testReadAndWriteThroughStrategy() { + app.useReadAndWriteThroughStrategy(); + } + + @Test + public void testReadThroughAndWriteAroundStrategy() { + app.useReadThroughAndWriteAroundStrategy(); + } + + @Test + public void testReadThroughAndWriteBehindStrategy() { + app.useReadThroughAndWriteBehindStrategy(); + } + + @Test + public void testCacheAsideStrategy() { + app.useCacheAsideStategy(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/AppTest.java new file mode 100644 index 0000000000..bb9b698d41 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.callback; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Callback example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/CallbackTest.java new file mode 100644 index 0000000000..7a14b0a4a6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.callback; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Add a field as a counter. Every time the callback method is called increment this field. Unit + * test checks that the field is being incremented. + * + * Could be done with mock objects as well where the call method call is verified. + */ +public class CallbackTest { + + private Integer callingCount = 0; + + @Test + public void test() { + Callback callback = new Callback() { + @Override + public void call() { + callingCount++; + } + }; + + Task task = new SimpleTask(); + + assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); + + task.executeWith(callback); + + assertEquals(new Integer(1), callingCount, "Callback called once"); + + task.executeWith(callback); + + assertEquals(new Integer(2), callingCount, "Callback called twice"); + + } + + @Test + public void testWithLambdasExample() { + Callback callback = () -> callingCount++; + + Task task = new SimpleTask(); + + assertEquals(new Integer(0), callingCount, "Initial calling count of 0"); + + task.executeWith(callback); + + assertEquals(new Integer(1), callingCount, "Callback called once"); + + task.executeWith(callback); + + assertEquals(new Integer(2), callingCount, "Callback called twice"); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/AppTest.java new file mode 100644 index 0000000000..577221bac7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.chain; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java new file mode 100644 index 0000000000..c7cfb687c0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java @@ -0,0 +1,59 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.chain; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/6/15 - 9:29 PM + * + * @author Jeroen Meulemeester + */ +public class OrcKingTest { + + /** + * All possible requests + */ + private static final Request[] REQUESTS = new Request[]{ + new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), + new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), + new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ..."), + }; + + @Test + public void testMakeRequest() throws Exception { + final OrcKing king = new OrcKing(); + + for (final Request request : REQUESTS) { + king.makeRequest(request); + assertTrue( + request.isHandled(), + "Expected all requests from King to be handled, but [" + request + "] was not!" + ); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/AppTest.java new file mode 100644 index 0000000000..eb0cf0f8a3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.command; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Command example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/CommandTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/CommandTest.java new file mode 100644 index 0000000000..b3a3f48d04 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/command/src/test/java/com/iluwatar/command/CommandTest.java @@ -0,0 +1,93 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.command; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all + * information needed to perform an action or trigger an event at a later time. This information + * includes the method name, the object that owns the method and values for the method parameters. + * + *

Four terms always associated with the command pattern are command, receiver, invoker and + * client. A command object (spell) knows about the receiver (target) and invokes a method of + * the receiver.Values for parameters of the receiver method are stored in the command. The receiver + * then does the work. An invoker object (wizard) knows how to execute a command, and optionally + * does bookkeeping about the command execution. The invoker does not know anything about a + * concrete command, it knows only about command interface. Both an invoker object and several + * command objects are held by a client object (app). The client decides which commands to execute + * at which points. To execute a command, it passes the command object to the invoker object. + */ +public class CommandTest { + + private static final String GOBLIN = "Goblin"; + + /** + * This test verifies that when the wizard casts spells on the goblin. The wizard keeps track of + * the previous spells cast, so it is easy to undo them. In addition, it also verifies that the + * wizard keeps track of the spells undone, so they can be redone. + */ + @Test + public void testCommand() { + + Wizard wizard = new Wizard(); + Goblin goblin = new Goblin(); + + wizard.castSpell(new ShrinkSpell(), goblin); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.castSpell(new InvisibilitySpell(), goblin); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); + + wizard.undoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.undoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.NORMAL, Visibility.VISIBLE); + + wizard.redoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.redoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); + } + + /** + * This method asserts that the passed goblin object has the name as expectedName, size as + * expectedSize and visibility as expectedVisibility. + * + * @param goblin a goblin object whose state is to be verified against other parameters + * @param expectedName expectedName of the goblin + * @param expectedSize expected size of the goblin + * @param expectedVisibility expected visibility of the goblin + */ + private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, + Visibility expectedVisibility) { + assertEquals(expectedName, goblin.toString(), "Goblin's name must be same as expectedName"); + assertEquals(expectedSize, goblin.getSize(), "Goblin's size must be same as expectedSize"); + assertEquals(expectedVisibility, goblin.getVisibility(), + "Goblin's visibility must be same as expectedVisibility"); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/AppTest.java new file mode 100644 index 0000000000..76e0220c92 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.composite; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/MessengerTest.java new file mode 100644 index 0000000000..3911382be1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/composite/src/test/java/com/iluwatar/composite/MessengerTest.java @@ -0,0 +1,112 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.composite; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/11/15 - 8:12 PM + * + * @author Jeroen Meulemeester + */ +public class MessengerTest { + + /** + * The buffer used to capture every write to {@link System#out} + */ + private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); + + /** + * Keep the original std-out so it can be restored after the test + */ + private final PrintStream realStdOut = System.out; + + /** + * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test + */ + @BeforeEach + public void setUp() { + this.stdOutBuffer = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOutBuffer)); + } + + /** + * Removed the mocked std-out {@link PrintStream} again from the {@link System} class + */ + @AfterEach + public void tearDown() { + System.setOut(realStdOut); + } + + /** + * Test the message from the orcs + */ + @Test + public void testMessageFromOrcs() { + final Messenger messenger = new Messenger(); + testMessage( + messenger.messageFromOrcs(), + "Where there is a whip there is a way." + ); + } + + /** + * Test the message from the elves + */ + @Test + public void testMessageFromElves() { + final Messenger messenger = new Messenger(); + testMessage( + messenger.messageFromElves(), + "Much wind pours from your mouth." + ); + } + + /** + * Test if the given composed message matches the expected message + * + * @param composedMessage The composed message, received from the messenger + * @param message The expected message + */ + private void testMessage(final LetterComposite composedMessage, final String message) { + // Test is the composed message has the correct number of words + final String[] words = message.split(" "); + assertNotNull(composedMessage); + assertEquals(words.length, composedMessage.count()); + + // Print the message to the mocked stdOut ... + composedMessage.print(); + + // ... and verify if the message matches with the expected one + assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/AppTest.java new file mode 100644 index 0000000000..1617beeb40 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.converter; + +import org.junit.jupiter.api.Test; + +/** + * App running test + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/ConverterTest.java new file mode 100644 index 0000000000..f5c41256d8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.converter; + +import com.google.common.collect.Lists; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for {@link Converter} + */ +public class ConverterTest { + + private UserConverter userConverter = new UserConverter(); + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test + public void testConversionsStartingFromDomain() { + User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); + User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); + assertEquals(u1, u2); + } + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test + public void testConversionsStartingFromDto() { + UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); + UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); + assertEquals(u1, u2); + } + + /** + * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and + * cleanly instantiated allowing various different conversion strategies to be implemented. + */ + @Test + public void testCustomConverter() { + Converter converter = new Converter<>( + userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + String.valueOf(new Random().nextInt())), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); + User u1 = new User("John", "Doe", false, "12324"); + UserDto userDto = converter.convertFromEntity(u1); + assertEquals(userDto.getEmail(), "johndoe@whatever.com"); + } + + /** + * Test whether converting a collection of Users to DTO Users and then converting them back to domain + * users returns an equal collection. + */ + @Test + public void testCollectionConversion() { + ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); + List fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); + assertEquals(fromDtos, users); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java new file mode 100644 index 0000000000..536418cbe8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java @@ -0,0 +1,116 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs; + +import java.math.BigInteger; +import java.util.List; + +import com.iluwatar.cqrs.commandes.CommandServiceImpl; +import com.iluwatar.cqrs.commandes.ICommandService; +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import com.iluwatar.cqrs.queries.IQueryService; +import com.iluwatar.cqrs.queries.QueryServiceImpl; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Integration test of IQueryService and ICommandService with h2 data + * + */ +public class IntegrationTest { + + private static IQueryService queryService; + private static ICommandService commandService; + + @BeforeAll + public static void initializeAndPopulateDatabase() { + commandService = new CommandServiceImpl(); + queryService = new QueryServiceImpl(); + + // create first author1 + commandService.authorCreated("username1", "name1", "email1"); + + // create author1 and update all its data + commandService.authorCreated("username2", "name2", "email2"); + commandService.authorEmailUpdated("username2", "new_email2"); + commandService.authorNameUpdated("username2", "new_name2"); + commandService.authorUsernameUpdated("username2", "new_username2"); + + // add book1 to author1 + commandService.bookAddedToAuthor("title1", 10, "username1"); + + // add book2 to author1 and update all its data + commandService.bookAddedToAuthor("title2", 20, "username1"); + commandService.bookPriceUpdated("title2", 30); + commandService.bookTitleUpdated("title2", "new_title2"); + + } + + @Test + public void testGetAuthorByUsername() { + Author author = queryService.getAuthorByUsername("username1"); + assertEquals("username1", author.getUsername()); + assertEquals("name1", author.getName()); + assertEquals("email1", author.getEmail()); + } + + @Test + public void testGetUpdatedAuthorByUsername() { + Author author = queryService.getAuthorByUsername("new_username2"); + Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); + assertEquals(expectedAuthor, author); + + } + + @Test + public void testGetBook() { + Book book = queryService.getBook("title1"); + assertEquals("title1", book.getTitle()); + assertEquals(10, book.getPrice(), 0.01); + } + + @Test + public void testGetAuthorBooks() { + List books = queryService.getAuthorBooks("username1"); + assertTrue(books.size() == 2); + assertTrue(books.contains(new Book("title1", 10))); + assertTrue(books.contains(new Book("new_title2", 30))); + } + + @Test + public void testGetAuthorBooksCount() { + BigInteger bookCount = queryService.getAuthorBooksCount("username1"); + assertEquals(new BigInteger("2"), bookCount); + } + + @Test + public void testGetAuthorsCount() { + BigInteger authorCount = queryService.getAuthorsCount(); + assertEquals(new BigInteger("2"), authorCount); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/AppTest.java new file mode 100644 index 0000000000..75ef59f184 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import org.junit.jupiter.api.Test; + +/** + * Tests that DAO example runs without errors. + */ +public class AppTest { + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/CustomerTest.java new file mode 100644 index 0000000000..1a55e3bebc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * Tests {@link Customer}. + */ +public class CustomerTest { + + private Customer customer; + private static final int ID = 1; + private static final String FIRSTNAME = "Winston"; + private static final String LASTNAME = "Churchill"; + + @BeforeEach + public void setUp() { + customer = new Customer(ID, FIRSTNAME, LASTNAME); + } + + @Test + public void getAndSetId() { + final int newId = 2; + customer.setId(newId); + assertEquals(newId, customer.getId()); + } + + @Test + public void getAndSetFirstname() { + final String newFirstname = "Bill"; + customer.setFirstName(newFirstname); + assertEquals(newFirstname, customer.getFirstName()); + } + + @Test + public void getAndSetLastname() { + final String newLastname = "Clinton"; + customer.setLastName(newLastname); + assertEquals(newLastname, customer.getLastName()); + } + + @Test + public void notEqualWithDifferentId() { + final int newId = 2; + final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); + assertNotEquals(customer, otherCustomer); + assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + public void equalsWithSameObjectValues() { + final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); + assertEquals(customer, otherCustomer); + assertEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + public void equalsWithSameObjects() { + assertEquals(customer, customer); + assertEquals(customer.hashCode(), customer.hashCode()); + } + + @Test + public void testToString() { + final StringBuffer buffer = new StringBuffer(); + buffer.append("Customer{id=") + .append("" + customer.getId()) + .append(", firstName='") + .append(customer.getFirstName()) + .append("\', lastName='") + .append(customer.getLastName() + "\'}"); + assertEquals(buffer.toString(), customer.toString()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java new file mode 100644 index 0000000000..e66bb15990 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -0,0 +1,276 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dao; + +import org.h2.jdbcx.JdbcDataSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +/** + * Tests {@link DbCustomerDao}. + */ +public class DbCustomerDaoTest { + + private static final String DB_URL = "jdbc:h2:~/dao"; + private DbCustomerDao dao; + private Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); + + /** + * Creates customers schema. + * @throws SQLException if there is any error while creating schema. + */ + @BeforeEach + public void createSchema() throws SQLException { + try (Connection connection = DriverManager.getConnection(DB_URL); + Statement statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); + } + } + + /** + * Represents the scenario where DB connectivity is present. + */ + @Nested + public class ConnectionSuccess { + + /** + * Setup for connection success scenario. + * @throws Exception if any error occurs. + */ + @BeforeEach + public void setUp() throws Exception { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dao = new DbCustomerDao(dataSource); + boolean result = dao.add(existingCustomer); + assertTrue(result); + } + + /** + * Represents the scenario when DAO operations are being performed on a non existing customer. + */ + @Nested + public class NonExistingCustomer { + + @Test + public void addingShouldResultInSuccess() throws Exception { + try (Stream allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final int nonExistingId = getNonExistingCustomerId(); + final String newFirstname = "Douglas"; + final String newLastname = "MacArthur"; + final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); + boolean result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + public void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents a scenario where DAO operations are being performed on an already existing + * customer. + * + */ + @Nested + public class ExistingCustomer { + + @Test + public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); + + boolean result = dao.add(existingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + boolean result = dao.delete(existingCustomer); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(existingCustomer.getId()).isPresent()); + } + + @Test + public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); + boolean result = dao.update(customer); + + assertTrue(result); + + final Customer cust = dao.getById(existingCustomer.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + } + } + + /** + * Represents a scenario where DB connectivity is not present due to network issue, or + * DB service unavailable. + * + */ + @Nested + public class ConnectivityIssue { + + private static final String EXCEPTION_CAUSE = "Connection not available"; + //@Rule public ExpectedException exception = ExpectedException.none(); + + /** + * setup a connection failure scenario. + * @throws SQLException if any error occurs. + */ + @BeforeEach + public void setUp() throws SQLException { + dao = new DbCustomerDao(mockedDatasource()); + //exception.expect(Exception.class); + //exception.expectMessage(EXCEPTION_CAUSE); + } + + private DataSource mockedDatasource() throws SQLException { + DataSource mockedDataSource = mock(DataSource.class); + Connection mockedConnection = mock(Connection.class); + SQLException exception = new SQLException(EXCEPTION_CAUSE); + doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); + doReturn(mockedConnection).when(mockedDataSource).getConnection(); + return mockedDataSource; + } + + @Test + public void addingACustomerFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.add(new Customer(2, "Bernard", "Montgomery")); + }); + } + + @Test + public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() { + assertThrows(Exception.class, () -> { + dao.delete(existingCustomer); + }); + } + + @Test + public void updatingACustomerFailsWithFeedbackToTheClient() { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + assertThrows(Exception.class, () -> { + dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); + }); + } + + @Test + public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.getById(existingCustomer.getId()); + }); + } + + @Test + public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() { + assertThrows(Exception.class, () -> { + dao.getAll(); + }); + } + + } + + /** + * Delete customer schema for fresh setup per test. + * @throws SQLException if any error occurs. + */ + @AfterEach + public void deleteSchema() throws SQLException { + try (Connection connection = DriverManager.getConnection(DB_URL); + Statement statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); + } + } + + private void assertCustomerCountIs(int count) throws Exception { + try (Stream allCustomers = dao.getAll()) { + assertTrue(allCustomers.count() == count); + } + } + + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java new file mode 100644 index 0000000000..7cb14b0b1d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -0,0 +1,162 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Optional; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Tests {@link InMemoryCustomerDao}. + */ +public class InMemoryCustomerDaoTest { + + private InMemoryCustomerDao dao; + private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); + + @BeforeEach + public void setUp() { + dao = new InMemoryCustomerDao(); + assertTrue(dao.add(CUSTOMER)); + } + + /** + * Represents the scenario when the DAO operations are being performed on a non existent + * customer. + */ + @Nested + public class NonExistingCustomer { + + @Test + public void addingShouldResultInSuccess() throws Exception { + try (Stream allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final int nonExistingId = getNonExistingCustomerId(); + final String newFirstname = "Douglas"; + final String newLastname = "MacArthur"; + final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); + boolean result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + public void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents the scenario when the DAO operations are being performed on an already existing + * customer. + */ + @Nested + public class ExistingCustomer { + + @Test + public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + boolean result = dao.add(CUSTOMER); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get()); + } + + @Test + public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + boolean result = dao.delete(CUSTOMER); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(CUSTOMER.getId()).isPresent()); + } + + @Test + public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); + boolean result = dao.update(customer); + + assertTrue(result); + + final Customer cust = dao.getById(CUSTOMER.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + + @Test + public void retriveShouldReturnTheCustomer() { + Optional optionalCustomer = dao.getById(CUSTOMER.getId()); + + assertTrue(optionalCustomer.isPresent()); + assertEquals(CUSTOMER, optionalCustomer.get()); + } + } + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } + + private void assertCustomerCountIs(int count) throws Exception { + try (Stream allCustomers = dao.getAll()) { + assertTrue(allCustomers.count() == count); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java new file mode 100644 index 0000000000..83d5386ace --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -0,0 +1,74 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.never; + +/** + * Tests for {@link DataBus}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class DataBusTest { + + @Mock + private Member member; + + @Mock + private DataType event; + + @BeforeEach + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void publishedEventIsReceivedBySubscribedMember() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + //when + dataBus.publish(event); + //then + then(member).should().accept(event); + } + + @Test + public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + dataBus.unsubscribe(member); + //when + dataBus.publish(event); + //then + then(member).should(never()).accept(event); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java new file mode 100644 index 0000000000..be705d6e76 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus.members; + +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link MessageCollectorMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class MessageCollectorMemberTest { + + @Test + public void collectMessageFromMessageData() { + //given + final String message = "message"; + final MessageData messageData = new MessageData(message); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(messageData); + //then + assertTrue(collector.getMessages().contains(message)); + } + + @Test + public void collectIgnoresMessageFromOtherDataTypes() { + //given + final StartingData startingData = new StartingData(LocalDateTime.now()); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(startingData); + //then + assertEquals(0, collector.getMessages().size()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java new file mode 100644 index 0000000000..41c0fccca7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -0,0 +1,81 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus.members; + +import com.iluwatar.databus.DataBus; +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import com.iluwatar.databus.data.StoppingData; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; +import java.time.Month; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Tests for {@link StatusMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StatusMemberTest { + + @Test + public void statusRecordsTheStartTime() { + //given + final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); + final StartingData startingData = new StartingData(startTime); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(startingData); + //then + assertEquals(startTime, statusMember.getStarted()); + } + + @Test + public void statusRecordsTheStopTime() { + //given + final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); + final StoppingData stoppingData = new StoppingData(stop); + stoppingData.setDataBus(DataBus.getInstance()); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(stoppingData); + //then + assertEquals(stop, statusMember.getStopped()); + } + + @Test + public void statusIgnoresMessageData() { + //given + final MessageData messageData = new MessageData("message"); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(messageData); + //then + assertNull(statusMember.getStarted()); + assertNull(statusMember.getStopped()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java new file mode 100644 index 0000000000..5c665a4e47 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java @@ -0,0 +1,33 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import org.junit.jupiter.api.Test; + +/** + * Tests that Data-Mapper example runs without errors. + */ +public final class AppTest { + + @Test + public void test() { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java new file mode 100644 index 0000000000..5f63cf045c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the + * database. Its responsibility is to transfer data between the two and also to isolate them from + * each other. With Data Mapper the in-memory objects needn't know even that there's a database + * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The + * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , + * Data Mapper itself is even unknown to the domain layer. + *

+ */ +public class DataMapperTest { + + /** + * This test verify that first data mapper is able to perform all CRUD operations on Student + */ + @Test + public void testFirstDataMapper() { + + /* Create new data mapper of first type */ + final StudentDataMapper mapper = new StudentDataMapperImpl(); + + /* Create new student */ + Student student = new Student(1, "Adam", 'A'); + + /* Add student in respectibe db */ + mapper.insert(student); + + /* Check if student is added in db */ + assertEquals(student.getStudentId(), mapper.find(student.getStudentId()).get().getStudentId()); + + /* Update existing student object */ + student = new Student(student.getStudentId(), "AdamUpdated", 'A'); + + /* Update student in respectibe db */ + mapper.update(student); + + /* Check if student is updated in db */ + assertEquals(mapper.find(student.getStudentId()).get().getName(), "AdamUpdated"); + + /* Delete student in db */ + mapper.delete(student); + + /* Result should be false */ + assertEquals(false, mapper.find(student.getStudentId()).isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java new file mode 100644 index 0000000000..523a6509a3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -0,0 +1,55 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests {@link Student}. + */ +public final class StudentTest { + + @Test + /** + * This API tests the equality behaviour of Student object + * Object Equality should work as per logic defined in equals method + * + * @throws Exception if any execution error during test + */ + public void testEquality() throws Exception { + + /* Create some students */ + final Student firstStudent = new Student(1, "Adam", 'A'); + final Student secondStudent = new Student(2, "Donald", 'B'); + final Student secondSameStudent = new Student(2, "Donald", 'B'); + final Student firstSameStudent = firstStudent; + + /* Check equals functionality: should return 'true' */ + assertTrue(firstStudent.equals(firstSameStudent)); + + /* Check equals functionality: should return 'false' */ + assertFalse(firstStudent.equals(secondStudent)); + + /* Check equals functionality: should return 'true' */ + assertTrue(secondStudent.equals(secondSameStudent)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java new file mode 100644 index 0000000000..db669b785f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java @@ -0,0 +1,81 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.datatransfer; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * tests {@link CustomerResource}. + */ +public class CustomerResourceTest { + @Test + public void shouldGetAllCustomers() { + CustomerDto customer = new CustomerDto("1", "Melody", "Yates"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + List allCustomers = customerResource.getAllCustomers(); + + assertEquals(allCustomers.size(), 1); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Melody"); + assertEquals(allCustomers.get(0).getLastName(), "Yates"); + } + + @Test + public void shouldSaveCustomer() { + CustomerDto customer = new CustomerDto("1", "Rita", "Reynolds"); + CustomerResource customerResource = new CustomerResource(new ArrayList<>()); + + customerResource.save(customer); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Rita"); + assertEquals(allCustomers.get(0).getLastName(), "Reynolds"); + } + + @Test + public void shouldDeleteCustomer() { + CustomerDto customer = new CustomerDto("1", "Terry", "Nguyen"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + customerResource.delete(customer.getId()); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.size(), 0); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/AppTest.java new file mode 100644 index 0000000000..35cc76dbdd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java new file mode 100644 index 0000000000..5221eb2da0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Tests for {@link ClubbedTroll} + */ +public class ClubbedTrollTest { + + @Test + public void testClubbedTroll() throws Exception { + // Create a normal troll first, but make sure we can spy on it later on. + final Troll simpleTroll = spy(new SimpleTroll()); + + // Now we want to decorate the troll to make it stronger ... + final Troll clubbed = new ClubbedTroll(simpleTroll); + assertEquals(20, clubbed.getAttackPower()); + verify(simpleTroll, times(1)).getAttackPower(); + + // Check if the clubbed troll actions are delegated to the decorated troll + clubbed.attack(); + verify(simpleTroll, times(1)).attack(); + + clubbed.fleeBattle(); + verify(simpleTroll, times(1)).fleeBattle(); + verifyNoMoreInteractions(simpleTroll); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java new file mode 100644 index 0000000000..14d944b2ee --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java @@ -0,0 +1,91 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for {@link SimpleTroll} + */ +public class SimpleTrollTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(SimpleTroll.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testTrollActions() throws Exception { + final SimpleTroll troll = new SimpleTroll(); + assertEquals(10, troll.getAttackPower()); + + troll.attack(); + assertEquals("The troll tries to grab you!", appender.getLastMessage()); + + troll.fleeBattle(); + assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage()); + + assertEquals(2, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java new file mode 100644 index 0000000000..ffdc96b807 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.delegation.simple; + +import org.junit.jupiter.api.Test; + +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java new file mode 100644 index 0000000000..422da5685f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.delegation.simple; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import com.iluwatar.delegation.simple.printers.CanonPrinter; +import com.iluwatar.delegation.simple.printers.EpsonPrinter; +import com.iluwatar.delegation.simple.printers.HpPrinter; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Delegation Pattern + */ +public class DelegateTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + private static final String MESSAGE = "Test Message Printed"; + + @Test + public void testCanonPrinter() throws Exception { + PrinterController printerController = new PrinterController(new CanonPrinter()); + printerController.print(MESSAGE); + + assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage()); + } + + @Test + public void testHpPrinter() throws Exception { + PrinterController printerController = new PrinterController(new HpPrinter()); + printerController.print(MESSAGE); + + assertEquals("HP Printer : Test Message Printed", appender.getLastMessage()); + } + + @Test + public void testEpsonPrinter() throws Exception { + PrinterController printerController = new PrinterController(new EpsonPrinter()); + printerController.print(MESSAGE); + + assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); + } + + /** + * Logging Appender + */ + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java new file mode 100644 index 0000000000..da15b7c52c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +/** + * Date: 28/04/17 - 7:40 AM + * + * @author Stanislav Kapinus + */ + +public class AdvancedSorceressTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to her + * through the setter's parameter + */ + @Test + public void testSmokeEveryThing() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final AdvancedSorceress advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(tobacco); + advancedSorceress.smoke(); + // Verify if the sorceress is smoking the correct tobacco ... + assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java new file mode 100644 index 0000000000..46e38cc335 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +/** + * Date: 12/10/15 - 8:40 PM + * + * @author Jeroen Meulemeester + */ +public class AdvancedWizardTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the constructor parameter + */ + @Test + public void testSmokeEveryThing() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); + advancedWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java new file mode 100644 index 0000000000..fc87759425 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java new file mode 100644 index 0000000000..042a418556 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/10/15 - 8:57 PM + * + * @author Jeroen Meulemeester + */ +public class GuiceWizardTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the constructor parameter + */ + @Test + public void testSmokeEveryThingThroughConstructor() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final GuiceWizard guiceWizard = new GuiceWizard(tobacco); + guiceWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + } + + /** + * Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the Guice google inject framework + */ + @Test + public void testSmokeEveryThingThroughInjectionFramework() throws Exception { + + @SuppressWarnings("unchecked") + final Class[] tobaccos = new Class[]{ + OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class + }; + + for (final Class tobaccoClass : tobaccos) { + // Configure the tobacco in the injection framework ... + final Injector injector = Guice.createInjector(new AbstractModule() { + @Override + protected void configure() { + bind(Tobacco.class).to(tobaccoClass); + } + }); + + // ... and create a new wizard with it + final GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage()); + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java new file mode 100644 index 0000000000..4600a2598e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/10/15 - 8:26 PM + * + * @author Jeroen Meulemeester + */ +public class SimpleWizardTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link SimpleWizard} does the only thing it can do: Smoke it's {@link + * OldTobyTobacco} + */ + @Test + public void testSmoke() { + final SimpleWizard simpleWizard = new SimpleWizard(); + simpleWizard.smoke(); + assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java new file mode 100644 index 0000000000..649afa58f4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doublechecked.locking; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java new file mode 100644 index 0000000000..2929afc5ef --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java @@ -0,0 +1,131 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doublechecked.locking; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/10/15 - 9:34 PM + * + * @author Jeroen Meulemeester + */ +public class InventoryTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Inventory.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * The number of threads used to stress test the locking of the {@link Inventory#addItem(Item)} + * method + */ + private static final int THREAD_COUNT = 8; + + /** + * The maximum number of {@link Item}s allowed in the {@link Inventory} + */ + private static final int INVENTORY_SIZE = 1000; + + /** + * Concurrently add multiple items to the inventory, and check if the items were added in order by + * checking the stdOut for continuous growth of the inventory. When 'items.size()=xx' shows up out + * of order, it means that the locking is not ok, increasing the risk of going over the inventory + * item limit. + */ + @Test + public void testAddItem() throws Exception { + assertTimeout(ofMillis(10000), () -> { + // Create a new inventory with a limit of 1000 items and put some load on the add method + final Inventory inventory = new Inventory(INVENTORY_SIZE); + final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); + for (int i = 0; i < THREAD_COUNT; i++) { + executorService.execute(() -> { + while (inventory.addItem(new Item())) {}; + }); + } + + // Wait until all threads have finished + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + + // Check the number of items in the inventory. It should not have exceeded the allowed maximum + final List items = inventory.getItems(); + assertNotNull(items); + assertEquals(INVENTORY_SIZE, items.size()); + + assertEquals(INVENTORY_SIZE, appender.getLogSize()); + + // ... and check if the inventory size is increasing continuously + for (int i = 0; i < items.size(); i++) { + assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); + } + }); + } + + + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java new file mode 100644 index 0000000000..ce39b2cce9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java new file mode 100644 index 0000000000..683fcd5b05 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -0,0 +1,111 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/10/15 - 8:37 PM + * Test for Collision + * @param Type of GameObject + * @author Jeroen Meulemeester + */ +public abstract class CollisionTest { + + /** + * Get the tested object + * + * @return The tested object, should never return 'null' + */ + abstract O getTestedObject(); + + /** + * Collide the tested item with the other given item and verify if the damage and fire state is as + * expected + * + * @param other The other object we have to collide with + * @param otherDamaged Indicates if the other object should be damaged after the collision + * @param otherOnFire Indicates if the other object should be burning after the collision + * @param thisDamaged Indicates if the test object should be damaged after the collision + * @param thisOnFire Indicates if the other object should be burning after the collision + * @param description The expected description of the collision + */ + void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, + final boolean thisDamaged, final boolean thisOnFire, final String description) { + + Objects.requireNonNull(other); + Objects.requireNonNull(getTestedObject()); + + final O tested = getTestedObject(); + + tested.collision(other); + + testOnFire(other, tested, otherOnFire); + testDamaged(other, tested, otherDamaged); + + testOnFire(tested, other, thisOnFire); + testDamaged(tested, other, thisDamaged); + + } + + /** + * Test if the fire state of the target matches the expected state after colliding with the given + * object + * + * @param target The target object + * @param other The other object + * @param expectTargetOnFire The expected state of fire on the target object + */ + private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { + final String targetName = target.getClass().getSimpleName(); + final String otherName = other.getClass().getSimpleName(); + + final String errorMessage = expectTargetOnFire + ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" + : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; + + assertEquals(expectTargetOnFire, target.isOnFire(), errorMessage); + } + + /** + * Test if the damage state of the target matches the expected state after colliding with the + * given object + * + * @param target The target object + * @param other The other object + * @param expectedDamage The expected state of damage on the target object + */ + private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { + final String targetName = target.getClass().getSimpleName(); + final String otherName = other.getClass().getSimpleName(); + + final String errorMessage = expectedDamage + ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" + : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; + + assertEquals(expectedDamage, target.isDamaged(), errorMessage); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java new file mode 100644 index 0000000000..7c5edb5c97 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class FlamingAsteroidTest extends CollisionTest { + + @Override + final FlamingAsteroid getTestedObject() { + return new FlamingAsteroid(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final FlamingAsteroid asteroid = new FlamingAsteroid(1, 2, 3, 4); + assertEquals(1, asteroid.getLeft()); + assertEquals(2, asteroid.getTop()); + assertEquals(3, asteroid.getRight()); + assertEquals(4, asteroid.getBottom()); + assertTrue(asteroid.isOnFire()); + assertFalse(asteroid.isDamaged()); + assertEquals("FlamingAsteroid at [1,2,3,4] damaged=false onFire=true", asteroid.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 2, 3, 4), + false, true, + false, true, + "FlamingAsteroid hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, true, + "FlamingAsteroid hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, true, + false, true, + "FlamingAsteroid hits SpaceStationIss. SpaceStationIss is damaged! SpaceStationIss is set on fire!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, true, + false, true, + "FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java new file mode 100644 index 0000000000..40ba0f60d1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class MeteoroidTest extends CollisionTest { + + @Override + final Meteoroid getTestedObject() { + return new Meteoroid(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final Meteoroid meteoroid = new Meteoroid(1, 2, 3, 4); + assertEquals(1, meteoroid.getLeft()); + assertEquals(2, meteoroid.getTop()); + assertEquals(3, meteoroid.getRight()); + assertEquals(4, meteoroid.getBottom()); + assertFalse(meteoroid.isOnFire()); + assertFalse(meteoroid.isDamaged()); + assertEquals("Meteoroid at [1,2,3,4] damaged=false onFire=false", meteoroid.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "Meteoroid hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "Meteoroid hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "Meteoroid hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "Meteoroid hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java new file mode 100644 index 0000000000..8f547c11f8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for Rectangle + */ +public class RectangleTest { + + /** + * Test if the values passed through the constructor matches the values fetched from the getters + */ + @Test + public void testConstructor() { + final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + assertEquals(1, rectangle.getLeft()); + assertEquals(2, rectangle.getTop()); + assertEquals(3, rectangle.getRight()); + assertEquals(4, rectangle.getBottom()); + } + + /** + * Test if the values passed through the constructor matches the values in the {@link + * #toString()} + */ + @Test + public void testToString() throws Exception { + final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + assertEquals("[1,2,3,4]", rectangle.toString()); + } + + /** + * Test if the {@link Rectangle} class can detect if it intersects with another rectangle. + */ + @Test + public void testIntersection() { + assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1))); + assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-1, -5, 7, 8))); + assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3))); + assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1))); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java new file mode 100644 index 0000000000..f99f6bdf5e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class SpaceStationIssTest extends CollisionTest { + + @Override + final SpaceStationIss getTestedObject() { + return new SpaceStationIss(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final SpaceStationIss iss = new SpaceStationIss(1, 2, 3, 4); + assertEquals(1, iss.getLeft()); + assertEquals(2, iss.getTop()); + assertEquals(3, iss.getRight()); + assertEquals(4, iss.getBottom()); + assertFalse(iss.isOnFire()); + assertFalse(iss.isDamaged()); + assertEquals("SpaceStationIss at [1,2,3,4] damaged=false onFire=false", iss.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "SpaceStationIss hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "SpaceStationIss hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationIss hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationIss hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java new file mode 100644 index 0000000000..f0cbd36685 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class SpaceStationMirTest extends CollisionTest { + + @Override + final SpaceStationMir getTestedObject() { + return new SpaceStationMir(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final SpaceStationMir mir = new SpaceStationMir(1, 2, 3, 4); + assertEquals(1, mir.getLeft()); + assertEquals(2, mir.getTop()); + assertEquals(3, mir.getRight()); + assertEquals(4, mir.getBottom()); + assertFalse(mir.isOnFire()); + assertFalse(mir.isDamaged()); + assertEquals("SpaceStationMir at [1,2,3,4] damaged=false onFire=false", mir.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "SpaceStationMir hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "SpaceStationMir hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationMir hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationMir hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java new file mode 100644 index 0000000000..40a3367867 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java new file mode 100644 index 0000000000..2c7d207d6f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test class for AggregatorRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class AggregatorRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody("TEST1"); + entry.sendBody("TEST2"); + entry.sendBody("TEST3"); + entry.sendBody("TEST4"); + entry.sendBody("TEST5"); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(2); + endpoint.assertIsSatisfied(); + + String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody(); + assertEquals(3, body.split(";").length); + + String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody(); + assertEquals(2, body2.split(";").length); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java new file mode 100644 index 0000000000..7a7a151546 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator.routes; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests MessageAggregationStrategy + */ +public class MessageAggregationStrategyTest { + + @Test + public void testAggregate() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + Exchange oldExchange = new DefaultExchange((CamelContext) null); + oldExchange.getIn().setBody("TEST1"); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(oldExchange, newExchange); + String outputBody = (String) output.getIn().getBody(); + assertEquals("TEST1;TEST2", outputBody); + } + + @Test + public void testAggregateOldNull() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(null, newExchange); + String outputBody = (String) output.getIn().getBody(); + + assertEquals(newExchange, output); + assertEquals("TEST2", outputBody); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java new file mode 100644 index 0000000000..fe3eca01e2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.splitter; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java new file mode 100644 index 0000000000..9257a44101 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java @@ -0,0 +1,72 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.splitter.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +/** + * Test class for SplitterRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = SplitterRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class SplitterRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"}); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(3); + endpoint.assertIsSatisfied(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java new file mode 100644 index 0000000000..673803df70 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.wiretap; + +import org.junit.jupiter.api.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java new file mode 100644 index 0000000000..449f862082 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.wiretap.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test class for WireTapRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@ExtendWith(SpringExtension.class) +@SpringApplicationConfiguration(classes = WireTapRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class WireTapRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + @EndpointInject(uri = "{{wireTapEndpoint}}") + private MockEndpoint wireTapEndpoint; + + /** + * Test if both endpoints receive exactly one message containing the same, unchanged body. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testWireTap() throws Exception { + entry.sendBody("TEST"); + + endpoint.expectedMessageCount(1); + wireTapEndpoint.expectedMessageCount(1); + + endpoint.assertIsSatisfied(); + wireTapEndpoint.assertIsSatisfied(); + + Message endpointIn = endpoint.getExchanges().get(0).getIn(); + Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn(); + + assertEquals("TEST", endpointIn.getBody()); + assertEquals("TEST", wireTapEndpointIn.getBody()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java new file mode 100644 index 0000000000..09548e3843 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java new file mode 100644 index 0000000000..c2f457e28f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -0,0 +1,156 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * Date: 12/12/15 - 10:58 PM + * Tests for Event Emitter + * @param Type of Event Emitter + * @author Jeroen Meulemeester + */ +public abstract class EventEmitterTest { + + /** + * Factory used to create a new instance of the test object with a default observer + */ + private final Function factoryWithDefaultObserver; + + /** + * Factory used to create a new instance of the test object without passing a default observer + */ + private final Supplier factoryWithoutDefaultObserver; + + /** + * The day of the week an event is expected + */ + private final Weekday specialDay; + + /** + * The expected event, emitted on the special day + */ + private final Event event; + + /** + * Create a new event emitter test, using the given test object factories, special day and event + */ + EventEmitterTest(final Weekday specialDay, final Event event, + final Function factoryWithDefaultObserver, + final Supplier factoryWithoutDefaultObserver) { + + this.specialDay = specialDay; + this.event = event; + this.factoryWithDefaultObserver = Objects.requireNonNull(factoryWithDefaultObserver); + this.factoryWithoutDefaultObserver = Objects.requireNonNull(factoryWithoutDefaultObserver); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. This test + * is executed twice, once without a default emitter and once with + */ + @Test + public void testAllDays() { + testAllDaysWithoutDefaultObserver(specialDay, event); + testAllDaysWithDefaultObserver(specialDay, event); + } + + /** + * Pass each week of the day, day by day to the event emitter and verify of the given observers + * received the correct event on the special day. + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + * @param emitter The event emitter + * @param observers The registered observer mocks + */ + private void testAllDays(final Weekday specialDay, final Event event, final E emitter, + final EventObserver... observers) { + + for (final Weekday weekday : Weekday.values()) { + // Pass each week of the day, day by day to the event emitter + emitter.timePasses(weekday); + + if (weekday == specialDay) { + // On a special day, every observer should have received the event + for (final EventObserver observer : observers) { + verify(observer, times(1)).onEvent(eq(event)); + } + } else { + // On any other normal day, the observers should have received nothing at all + verifyZeroInteractions(observers); + } + } + + // The observers should not have received any additional events after the week + verifyNoMoreInteractions(observers); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. Use an + * event emitter without a default observer + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + */ + private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final Event event) { + final EventObserver observer1 = mock(EventObserver.class); + final EventObserver observer2 = mock(EventObserver.class); + + final E emitter = this.factoryWithoutDefaultObserver.get(); + emitter.registerObserver(observer1); + emitter.registerObserver(observer2); + + testAllDays(specialDay, event, emitter, observer1, observer2); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + */ + private void testAllDaysWithDefaultObserver(final Weekday specialDay, final Event event) { + final EventObserver defaultObserver = mock(EventObserver.class); + final EventObserver observer1 = mock(EventObserver.class); + final EventObserver observer2 = mock(EventObserver.class); + + final E emitter = this.factoryWithDefaultObserver.apply(defaultObserver); + emitter.registerObserver(observer1); + emitter.registerObserver(observer2); + + testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java new file mode 100644 index 0000000000..28062c613e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java @@ -0,0 +1,49 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/12/15 - 2:52 PM + * + * @author Jeroen Meulemeester + */ +public class EventTest { + + /** + * Verify if every event has a non-null, non-empty description + */ + @Test + public void testToString() { + for (final Event event : Event.values()) { + final String toString = event.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java new file mode 100644 index 0000000000..3f3296c575 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java @@ -0,0 +1,98 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/12/15 - 3:04 PM + * + * @author Jeroen Meulemeester + */ +public class KingJoffreyTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(KingJoffrey.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test if {@link KingJoffrey} tells us what event he received + */ + @Test + public void testOnEvent() { + final KingJoffrey kingJoffrey = new KingJoffrey(); + + for (int i = 0; i < Event.values().length; ++i) { + assertEquals(i, appender.getLogSize()); + Event event = Event.values()[i]; + kingJoffrey.onEvent(event); + + final String expectedMessage = "Received event from the King's Hand: " + event.toString(); + assertEquals(expectedMessage, appender.getLastMessage()); + assertEquals(i + 1, appender.getLogSize()); + } + + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java new file mode 100644 index 0000000000..3a5ae8f68f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:57 AM + * + * @author Jeroen Meulemeester + */ +public class KingsHandTest extends EventEmitterTest { + + /** + * Create a new test instance, using the correct object factory + */ + public KingsHandTest() { + super(null, null, KingsHand::new, KingsHand::new); + } + + /** + * The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if every + * event received is passed up to it's superior, in most cases {@link KingJoffrey} but now just a + * mocked observer. + */ + @Test + public void testPassThrough() throws Exception { + final EventObserver observer = mock(EventObserver.class); + final KingsHand kingsHand = new KingsHand(observer); + + // The kings hand should not pass any events before he received one + verifyZeroInteractions(observer); + + // Verify if each event is passed on to the observer, nothing less, nothing more. + for (final Event event : Event.values()) { + kingsHand.onEvent(event); + verify(observer, times(1)).onEvent(eq(event)); + verifyNoMoreInteractions(observer); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java new file mode 100644 index 0000000000..df2d8ac795 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/12/15 - 2:12 PM + * + * @author Jeroen Meulemeester + */ +public class WeekdayTest { + + @Test + public void testToString() throws Exception { + for (final Weekday weekday : Weekday.values()) { + final String toString = weekday.toString(); + assertNotNull(toString); + assertEquals(weekday.name(), toString.toUpperCase()); + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java new file mode 100644 index 0000000000..372bc2f582 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java @@ -0,0 +1,32 @@ +/** + * The MIT License Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.event.asynchronous; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that EventAsynchronous example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java new file mode 100644 index 0000000000..aa2c644cb5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -0,0 +1,142 @@ +/** + * The MIT License Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.event.asynchronous; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * + * Application test + * + */ +public class EventAsynchronousTest { + App app; + + private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); + + @BeforeEach + public void setUp() { + app = new App(); + } + + @Test + public void testAsynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int aEventId = eventManager.createAsync(60); + eventManager.start(aEventId); + assertTrue(eventManager.getEventPool().size() == 1); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() == -1); + eventManager.cancel(aEventId); + assertTrue(eventManager.getEventPool().size() == 0); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testSynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int sEventId = eventManager.create(60); + eventManager.start(sEventId); + assertTrue(eventManager.getEventPool().size() == 1); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() != -1); + eventManager.cancel(sEventId); + assertTrue(eventManager.getEventPool().size() == 0); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException + | InvalidOperationException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testUnsuccessfulSynchronousEvent() throws InvalidOperationException { + assertThrows(InvalidOperationException.class, () -> { + EventManager eventManager = new EventManager(); + try { + int sEventId = eventManager.create(60); + eventManager.start(sEventId); + sEventId = eventManager.create(60); + eventManager.start(sEventId); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + }); + } + + @Test + public void testFullSynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int eventTime = 1; + + int sEventId = eventManager.create(eventTime); + assertTrue(eventManager.getEventPool().size() == 1); + eventManager.start(sEventId); + + long currentTime = System.currentTimeMillis(); + long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to + // complete + // properly. + while (System.currentTimeMillis() < endTime) { + } + + assertTrue(eventManager.getEventPool().size() == 0); + + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException + | InvalidOperationException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testFullAsynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int eventTime = 1; + + int aEventId1 = eventManager.createAsync(eventTime); + int aEventId2 = eventManager.createAsync(eventTime); + int aEventId3 = eventManager.createAsync(eventTime); + assertTrue(eventManager.getEventPool().size() == 3); + + eventManager.start(aEventId1); + eventManager.start(aEventId2); + eventManager.start(aEventId3); + + long currentTime = System.currentTimeMillis(); + long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to complete + // properly. + while (System.currentTimeMillis() < endTime) { + } + + assertTrue(eventManager.getEventPool().size() == 0); + + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java new file mode 100644 index 0000000000..f74232ac1e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Event Driven Architecture example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java new file mode 100644 index 0000000000..823605e9d3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda.event; + +import com.iluwatar.eda.model.User; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. + */ +public class UserCreatedEventTest { + + /** + * This unit test should correctly return the {@link AbstractEvent} class type when calling the + * {@link AbstractEvent#getType() getType} method. + */ + @Test + public void testGetEventType() { + User user = new User("iluwatar"); + UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); + assertEquals(UserCreatedEvent.class, userCreatedEvent.getType()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java new file mode 100644 index 0000000000..6f647245dc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda.framework; + +import com.iluwatar.eda.event.UserCreatedEvent; +import com.iluwatar.eda.event.UserUpdatedEvent; +import com.iluwatar.eda.handler.UserCreatedEventHandler; +import com.iluwatar.eda.handler.UserUpdatedEventHandler; +import com.iluwatar.eda.model.User; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour + */ +public class EventDispatcherTest { + + /** + * This unit test should register events and event handlers correctly with the event dispatcher + * and events should be dispatched accordingly. + */ + @Test + public void testEventDriverPattern() { + + EventDispatcher dispatcher = spy(new EventDispatcher()); + UserCreatedEventHandler userCreatedEventHandler = spy(new UserCreatedEventHandler()); + UserUpdatedEventHandler userUpdatedEventHandler = spy(new UserUpdatedEventHandler()); + dispatcher.registerHandler(UserCreatedEvent.class, userCreatedEventHandler); + dispatcher.registerHandler(UserUpdatedEvent.class, userUpdatedEventHandler); + + User user = new User("iluwatar"); + + UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); + UserUpdatedEvent userUpdatedEvent = new UserUpdatedEvent(user); + + //fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. + dispatcher.dispatch(userCreatedEvent); + verify(userCreatedEventHandler).onEvent(userCreatedEvent); + verify(dispatcher).dispatch(userCreatedEvent); + + //fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. + dispatcher.dispatch(userUpdatedEvent); + verify(userUpdatedEventHandler).onEvent(userUpdatedEvent); + verify(dispatcher).dispatch(userUpdatedEvent); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java new file mode 100644 index 0000000000..47f332526d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.event.queue; + +import org.junit.jupiter.api.Test; + +import javax.sound.sampled.UnsupportedAudioFileException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +/** + * Testing the Audio service of the Queue + * @author mkuprivecz + * + */ +public class AudioTest { + + /** + * Test here that the playSound method works correctly + * @throws UnsupportedAudioFileException when the audio file is not supported + * @throws IOException when the file is not readable + * @throws InterruptedException when the test is interrupted externally + */ + @Test + public void testPlaySound() throws UnsupportedAudioFileException, IOException, InterruptedException { + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); + // test that service is started + assertTrue(Audio.isServiceRunning()); + // adding a small pause to be sure that the sound is ended + Thread.sleep(5000); + // test that service is finished + assertFalse(!Audio.isServiceRunning()); + } + + /** + * Test here that the Queue + * @throws UnsupportedAudioFileException when the audio file is not supported + * @throws IOException when the file is not readable + * @throws InterruptedException when the test is interrupted externally + */ + @Test + public void testQueue() throws UnsupportedAudioFileException, IOException, InterruptedException { + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + assertTrue(Audio.getPendingAudio().length > 0); + // test that service is started + assertTrue(Audio.isServiceRunning()); + // adding a small pause to be sure that the sound is ended + Thread.sleep(10000); + // test that service is finished + assertFalse(!Audio.isServiceRunning()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-sourcing/src/test/java/IntegrationTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-sourcing/src/test/java/IntegrationTest.java new file mode 100644 index 0000000000..aab1ea7ea1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/event-sourcing/src/test/java/IntegrationTest.java @@ -0,0 +1,99 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import com.iluwatar.event.sourcing.processor.DomainEventProcessor; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.util.Date; + +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Intergartion Test for Event Sourcing state recovery + * + * Created by Serdar Hamzaogullari on 19.08.2017. + */ +public class IntegrationTest { + + /** + * The Domain event processor. + */ + private DomainEventProcessor eventProcessor; + + /** + * Initialize. + */ + @BeforeEach + public void initialize() { + eventProcessor = new DomainEventProcessor(); + } + + /** + * Test state recovery. + */ + @Test + public void testStateRecovery() { + eventProcessor.reset(); + + eventProcessor.process(new AccountCreateEvent( + 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + + eventProcessor.process(new AccountCreateEvent( + 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + + eventProcessor.process(new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + + eventProcessor.process(new MoneyDepositEvent( + 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + + eventProcessor.process(new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, + ACCOUNT_OF_JON)); + + Account accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + AccountAggregate.resetState(); + + eventProcessor = new DomainEventProcessor(); + eventProcessor.recover(); + + Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), + accountOfDaenerysAfterShotDown.getMoney()); + assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java new file mode 100644 index 0000000000..298f7e0d79 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.execute.around; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; + +/** + * + * Tests execute-around example. + * + */ +public class AppTest { + + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } + + @BeforeEach + @AfterEach + public void cleanup() { + File file = new File("testfile.txt"); + file.delete(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java new file mode 100644 index 0000000000..22bdf68f7e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -0,0 +1,101 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.execute.around; + +import org.junit.Rule; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/12/15 - 3:21 PM + * + * @author Jeroen Meulemeester + */ +@EnableRuleMigrationSupport +public class SimpleFileWriterTest { + + /** + * Create a temporary folder, used to generate files in during this test + */ + @Rule + public final TemporaryFolder testFolder = new TemporaryFolder(); + + /** + * Verify if the given writer is not 'null' + */ + @Test + public void testWriterNotNull() throws Exception { + final File temporaryFile = this.testFolder.newFile(); + new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull); + } + + /** + * Test if the {@link SimpleFileWriter} creates a file if it doesn't exist + */ + @Test + public void testNonExistentFile() throws Exception { + final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); + assertFalse(nonExistingFile.exists()); + + new SimpleFileWriter(nonExistingFile.getPath(), Assertions::assertNotNull); + assertTrue(nonExistingFile.exists()); + } + + /** + * Test if the data written to the file writer actually gets in the file + */ + @Test + public void testActualWrite() throws Exception { + final String testMessage = "Test message"; + + final File temporaryFile = this.testFolder.newFile(); + assertTrue(temporaryFile.exists()); + + new SimpleFileWriter(temporaryFile.getPath(), writer -> writer.write(testMessage)); + assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); + } + + /** + * Verify if an {@link IOException} during the write ripples through + */ + @Test + public void testIoException() throws Exception { + assertThrows(IOException.class, () -> { + final File temporaryFile = this.testFolder.newFile(); + new SimpleFileWriter(temporaryFile.getPath(), writer -> { + throw new IOException(""); + }); + }); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/AppTest.java new file mode 100644 index 0000000000..f3111bebbf --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import org.junit.jupiter.api.Test; + +/** + * Created by Srdjan on 03-May-17. + */ +public class AppTest { + @Test + public void main() throws Exception { + + String[] args = {}; + App.main(args); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/CommanderTest.java new file mode 100644 index 0000000000..5dac551f43 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/CommanderTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.jupiter.api.Test; +import units.CommanderUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class CommanderTest { + @Test + public void commanderReady() throws Exception { + final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest")); + + commander.commanderReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SergeantTest.java new file mode 100644 index 0000000000..f26830e2c2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SergeantTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.jupiter.api.Test; +import units.SergeantUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SergeantTest { + @Test + public void sergeantReady() throws Exception { + final Sergeant sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest")); + + sergeant.sergeantReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SoldierTest.java new file mode 100644 index 0000000000..a9a6c47685 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/concreteextensions/SoldierTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.jupiter.api.Test; +import units.SoldierUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SoldierTest { + @Test + public void soldierReady() throws Exception { + final Soldier soldier = new Soldier(new SoldierUnit("SoldierUnitTest")); + + soldier.soldierReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/CommanderUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/CommanderUnitTest.java new file mode 100644 index 0000000000..536c3ae3f5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/CommanderUnitTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.CommanderExtension; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class CommanderUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new CommanderUnit("CommanderUnitName"); + + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNotNull((CommanderExtension) unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SergeantUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SergeantUnitTest.java new file mode 100644 index 0000000000..ac518b4882 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SergeantUnitTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.SergeantExtension; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SergeantUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new SergeantUnit("SergeantUnitName"); + + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNotNull((SergeantExtension) unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SoldierUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SoldierUnitTest.java new file mode 100644 index 0000000000..1aeb9a3cdd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/SoldierUnitTest.java @@ -0,0 +1,47 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.SoldierExtension; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SoldierUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new SoldierUnit("SoldierUnitName"); + + assertNotNull((SoldierExtension) unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/UnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/UnitTest.java new file mode 100644 index 0000000000..389c9f753d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/extension-objects/src/test/java/units/UnitTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class UnitTest { + + @Test + public void testConstGetSet() throws Exception { + final String name = "testName"; + final Unit unit = new Unit(name); + assertEquals(name, unit.getName()); + + final String newName = "newName"; + unit.setName(newName); + assertEquals(newName, unit.getName()); + + + assertNull(unit.getUnitExtension("")); + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/AppTest.java new file mode 100644 index 0000000000..366315e9e0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java new file mode 100644 index 0000000000..19987acbc4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -0,0 +1,135 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/9/15 - 9:40 PM + * + * @author Jeroen Meulemeester + */ +public class DwarvenGoldmineFacadeTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Test a complete day cycle in the gold mine by executing all three different steps: {@link + * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link + * DwarvenGoldmineFacade#endDay()}. + * + * See if the workers are doing what's expected from them on each step. + */ + @Test + public void testFullWorkDay() { + final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade(); + goldMine.startNewDay(); + + // On the start of a day, all workers should wake up ... + assertTrue(appender.logContains("Dwarf gold digger wakes up.")); + assertTrue(appender.logContains("Dwarf cart operator wakes up.")); + assertTrue(appender.logContains("Dwarven tunnel digger wakes up.")); + + // ... and go to the mine + assertTrue(appender.logContains("Dwarf gold digger goes to the mine.")); + assertTrue(appender.logContains("Dwarf cart operator goes to the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to the mine.")); + + // No other actions were invoked, so the workers shouldn't have done (printed) anything else + assertEquals(6, appender.getLogSize()); + + // Now do some actual work, start digging gold! + goldMine.digOutGold(); + + // Since we gave the dig command, every worker should be doing it's job ... + assertTrue(appender.logContains("Dwarf gold digger digs for gold.")); + assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel.")); + + // Again, they shouldn't be doing anything else. + assertEquals(9, appender.getLogSize()); + + // Enough gold, lets end the day. + goldMine.endDay(); + + // Check if the workers go home ... + assertTrue(appender.logContains("Dwarf gold digger goes home.")); + assertTrue(appender.logContains("Dwarf cart operator goes home.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes home.")); + + // ... and go to sleep. We need well rested workers the next day :) + assertTrue(appender.logContains("Dwarf gold digger goes to sleep.")); + assertTrue(appender.logContains("Dwarf cart operator goes to sleep.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to sleep.")); + + // Every worker should be sleeping now, no other actions allowed + assertEquals(15, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java new file mode 100644 index 0000000000..0be22b9b02 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factorykit.app; + +import com.iluwatar.factorykit.App; +import org.junit.jupiter.api.Test; + +/** + * Application Test Entrypoint + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} + diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java new file mode 100644 index 0000000000..f15223feb4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java @@ -0,0 +1,89 @@ + /** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factorykit.factorykit; + +import com.iluwatar.factorykit.Axe; +import com.iluwatar.factorykit.Spear; +import com.iluwatar.factorykit.Sword; +import com.iluwatar.factorykit.Weapon; +import com.iluwatar.factorykit.WeaponFactory; +import com.iluwatar.factorykit.WeaponType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + + /** + * Test Factory Kit Pattern + */ +public class FactoryKitTest { + + private WeaponFactory factory; + + @BeforeEach + public void init() { + factory = WeaponFactory.factory(builder -> { + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SWORD, Sword::new); + }); + } + + /** + * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of {@link Spear} + */ + @Test + public void testSpearWeapon() { + Weapon weapon = factory.create(WeaponType.SPEAR); + verifyWeapon(weapon, Spear.class); + } + + /** + * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of {@link Axe} + */ + @Test + public void testAxeWeapon() { + Weapon weapon = factory.create(WeaponType.AXE); + verifyWeapon(weapon, Axe.class); + } + + + /** + * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of {@link Sword} + */ + @Test + public void testWeapon() { + Weapon weapon = factory.create(WeaponType.SWORD); + verifyWeapon(weapon, Sword.class); + } + + /** + * This method asserts that the weapon object that is passed is an instance of the clazz + * + * @param weapon weapon object which is to be verified + * @param clazz expected class of the weapon + */ + private void verifyWeapon(Weapon weapon, Class clazz) { + assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java new file mode 100644 index 0000000000..4a73077c14 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factory.method; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Factory Method example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java new file mode 100644 index 0000000000..75d8e46779 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factory.method; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The Factory Method is a creational design pattern which uses factory methods to deal with the + * problem of creating objects without specifying the exact class of object that will be created. + * This is done by creating objects via calling a factory method either specified in an interface + * and implemented by child classes, or implemented in a base class and optionally overridden by + * derived classes—rather than by calling a constructor. + * + *

Factory produces the object of its liking. + * The weapon {@link Weapon} manufactured by the + * blacksmith depends on the kind of factory implementation it is referring to. + *

+ */ +public class FactoryMethodTest { + + /** + * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance + * of {@link OrcWeapon}. + */ + @Test + public void testOrcBlacksmithWithSpear() { + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); + } + + /** + * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance + * of {@link OrcWeapon}. + */ + @Test + public void testOrcBlacksmithWithAxe() { + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); + } + + /** + * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an + * instance of {@link ElfWeapon}. + */ + @Test + public void testElfBlacksmithWithShortSword() { + Blacksmith blacksmith = new ElfBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); + verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); + } + + /** + * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance + * of {@link ElfWeapon}. + */ + @Test + public void testElfBlacksmithWithSpear() { + Blacksmith blacksmith = new ElfBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); + } + + /** + * This method asserts that the weapon object that is passed is an instance of the clazz and the + * weapon is of type expectedWeaponType. + * + * @param weapon weapon object which is to be verified + * @param expectedWeaponType expected WeaponType of the weapon + * @param clazz expected class of the weapon + */ + private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { + assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); + assertEquals(expectedWeaponType, weapon.getWeaponType(), "Weapon must be of weaponType: " + expectedWeaponType); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java new file mode 100644 index 0000000000..9f0d377fa3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.featuretoggle.pattern.propertiesversion; + +import com.iluwatar.featuretoggle.pattern.Service; +import com.iluwatar.featuretoggle.user.User; +import org.junit.jupiter.api.Test; + +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Properties Toggle + */ +public class PropertiesFeatureToggleVersionTest { + + @Test + public void testNullPropertiesPassed() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + new PropertiesFeatureToggleVersion(null); + }); + } + + @Test + public void testNonBooleanProperty() throws Exception { + assertThrows(IllegalArgumentException.class, () -> { + final Properties properties = new Properties(); + properties.setProperty("enhancedWelcome", "Something"); + new PropertiesFeatureToggleVersion(properties); + }); + } + + @Test + public void testFeatureTurnedOn() throws Exception { + final Properties properties = new Properties(); + properties.put("enhancedWelcome", true); + Service service = new PropertiesFeatureToggleVersion(properties); + assertTrue(service.isEnhanced()); + final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); + } + + @Test + public void testFeatureTurnedOff() throws Exception { + final Properties properties = new Properties(); + properties.put("enhancedWelcome", false); + Service service = new PropertiesFeatureToggleVersion(properties); + assertFalse(service.isEnhanced()); + final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + assertEquals("Welcome to the application.", welcomeMessage); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java new file mode 100644 index 0000000000..0ed0afea96 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.featuretoggle.pattern.tieredversion; + +import com.iluwatar.featuretoggle.pattern.Service; +import com.iluwatar.featuretoggle.user.User; +import com.iluwatar.featuretoggle.user.UserGroup; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Tiered Feature Toggle + */ +public class TieredFeatureToggleVersionTest { + + final User paidUser = new User("Jamie Coder"); + final User freeUser = new User("Alan Defect"); + final Service service = new TieredFeatureToggleVersion(); + + @BeforeEach + public void setUp() throws Exception { + UserGroup.addUserToPaidGroup(paidUser); + UserGroup.addUserToFreeGroup(freeUser); + } + + @Test + public void testGetWelcomeMessageForPaidUser() throws Exception { + final String welcomeMessage = service.getWelcomeMessage(paidUser); + final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; + assertEquals(expected, welcomeMessage); + } + + @Test + public void testGetWelcomeMessageForFreeUser() throws Exception { + final String welcomeMessage = service.getWelcomeMessage(freeUser); + final String expected = "I suppose you can use this software."; + assertEquals(expected, welcomeMessage); + } + + @Test + public void testIsEnhancedAlwaysTrueAsTiered() throws Exception { + assertTrue(service.isEnhanced()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java new file mode 100644 index 0000000000..2771655dde --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.featuretoggle.user; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test User Group specific feature + */ +public class UserGroupTest { + + @Test + public void testAddUserToFreeGroup() throws Exception { + User user = new User("Free User"); + UserGroup.addUserToFreeGroup(user); + assertFalse(UserGroup.isPaid(user)); + } + + @Test + public void testAddUserToPaidGroup() throws Exception { + User user = new User("Paid User"); + UserGroup.addUserToPaidGroup(user); + assertTrue(UserGroup.isPaid(user)); + } + + @Test + public void testAddUserToPaidWhenOnFree() throws Exception { + User user = new User("Paid User"); + UserGroup.addUserToFreeGroup(user); + assertThrows(IllegalArgumentException.class, () -> { + UserGroup.addUserToPaidGroup(user); + }); + } + + @Test + public void testAddUserToFreeWhenOnPaid() throws Exception { + User user = new User("Free User"); + UserGroup.addUserToPaidGroup(user); + assertThrows(IllegalArgumentException.class, () -> { + UserGroup.addUserToFreeGroup(user); + }); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java new file mode 100644 index 0000000000..6e21bd8e41 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fluentinterface.app; + +import org.junit.jupiter.api.Test; + +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java new file mode 100644 index 0000000000..0eb9e003a0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -0,0 +1,202 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fluentinterface.fluentiterable; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Spliterator; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 7:00 PM + * + * @author Jeroen Meulemeester + */ +public abstract class FluentIterableTest { + + /** + * Create a new {@link FluentIterable} from the given integers + * + * @param integers The integers + * @return The new iterable, use for testing + */ + protected abstract FluentIterable createFluentIterable(final Iterable integers); + + @Test + public void testFirst() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final Optional first = createFluentIterable(integers).first(); + assertNotNull(first); + assertTrue(first.isPresent()); + assertEquals(integers.get(0), first.get()); + } + + @Test + public void testFirstEmptyCollection() throws Exception { + final List integers = Collections.emptyList(); + final Optional first = createFluentIterable(integers).first(); + assertNotNull(first); + assertFalse(first.isPresent()); + } + + @Test + public void testFirstCount() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List first4 = createFluentIterable(integers) + .first(4) + .asList(); + + assertNotNull(first4); + assertEquals(4, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + assertEquals(integers.get(3), first4.get(3)); + } + + @Test + public void testFirstCountLessItems() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List first4 = createFluentIterable(integers) + .first(4) + .asList(); + + assertNotNull(first4); + assertEquals(3, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + } + + @Test + public void testLast() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final Optional last = createFluentIterable(integers).last(); + assertNotNull(last); + assertTrue(last.isPresent()); + assertEquals(integers.get(integers.size() - 1), last.get()); + } + + @Test + public void testLastEmptyCollection() throws Exception { + final List integers = Collections.emptyList(); + final Optional last = createFluentIterable(integers).last(); + assertNotNull(last); + assertFalse(last.isPresent()); + } + + @Test + public void testLastCount() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List last4 = createFluentIterable(integers) + .last(4) + .asList(); + + assertNotNull(last4); + assertEquals(4, last4.size()); + assertEquals(Integer.valueOf(3), last4.get(0)); + assertEquals(Integer.valueOf(10), last4.get(1)); + assertEquals(Integer.valueOf(9), last4.get(2)); + assertEquals(Integer.valueOf(8), last4.get(3)); + } + + @Test + public void testLastCountLessItems() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List last4 = createFluentIterable(integers) + .last(4) + .asList(); + + assertNotNull(last4); + assertEquals(3, last4.size()); + + assertEquals(Integer.valueOf(1), last4.get(0)); + assertEquals(Integer.valueOf(2), last4.get(1)); + assertEquals(Integer.valueOf(3), last4.get(2)); + } + + @Test + public void testFilter() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List evenItems = createFluentIterable(integers) + .filter(i -> i % 2 == 0) + .asList(); + + assertNotNull(evenItems); + assertEquals(3, evenItems.size()); + assertEquals(Integer.valueOf(2), evenItems.get(0)); + assertEquals(Integer.valueOf(10), evenItems.get(1)); + assertEquals(Integer.valueOf(8), evenItems.get(2)); + } + + @Test + public void testMap() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List longs = createFluentIterable(integers) + .map(Integer::longValue) + .asList(); + + assertNotNull(longs); + assertEquals(integers.size(), longs.size()); + assertEquals(Long.valueOf(1), longs.get(0)); + assertEquals(Long.valueOf(2), longs.get(1)); + assertEquals(Long.valueOf(3), longs.get(2)); + } + + @Test + public void testForEach() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + + final Consumer consumer = mock(Consumer.class); + createFluentIterable(integers).forEach(consumer); + + verify(consumer, times(1)).accept(Integer.valueOf(1)); + verify(consumer, times(1)).accept(Integer.valueOf(2)); + verify(consumer, times(1)).accept(Integer.valueOf(3)); + verifyNoMoreInteractions(consumer); + + } + + @Test + public void testSpliterator() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final Spliterator split = createFluentIterable(integers).spliterator(); + assertNotNull(split); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java new file mode 100644 index 0000000000..53db61ddd0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.action; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/12/15 - 10:11 PM + * + * @author Jeroen Meulemeester + */ +public class ContentTest { + + @Test + public void testToString() throws Exception { + for (final Content content : Content.values()) { + final String toString = content.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java new file mode 100644 index 0000000000..60f19d8f3b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.action; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/12/15 - 10:15 PM + * + * @author Jeroen Meulemeester + */ +public class MenuItemTest { + + @Test + public void testToString() throws Exception { + for (final MenuItem menuItem : MenuItem.values()) { + final String toString = menuItem.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/app/AppTest.java new file mode 100644 index 0000000000..0a83759167 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.app; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java new file mode 100644 index 0000000000..54760557bf --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -0,0 +1,113 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.dispatcher; + +import com.iluwatar.flux.action.Action; +import com.iluwatar.flux.action.ActionType; +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.store.Store; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 8:22 PM + * + * @author Jeroen Meulemeester + */ +public class DispatcherTest { + + /** + * Dispatcher is a singleton with no way to reset it's internal state back to the beginning. + * Replace the instance with a fresh one before each test to make sure test cases have no + * influence on each other. + */ + @BeforeEach + public void setUp() throws Exception { + final Constructor constructor; + constructor = Dispatcher.class.getDeclaredConstructor(); + constructor.setAccessible(true); + + final Field field = Dispatcher.class.getDeclaredField("instance"); + field.setAccessible(true); + field.set(Dispatcher.getInstance(), constructor.newInstance()); + } + + @Test + public void testGetInstance() throws Exception { + assertNotNull(Dispatcher.getInstance()); + assertSame(Dispatcher.getInstance(), Dispatcher.getInstance()); + } + + @Test + public void testMenuItemSelected() throws Exception { + final Dispatcher dispatcher = Dispatcher.getInstance(); + + final Store store = mock(Store.class); + dispatcher.registerStore(store); + dispatcher.menuItemSelected(MenuItem.HOME); + dispatcher.menuItemSelected(MenuItem.COMPANY); + + // We expect 4 events, 2 menu selections and 2 content change actions + final ArgumentCaptor actionCaptor = ArgumentCaptor.forClass(Action.class); + verify(store, times(4)).onAction(actionCaptor.capture()); + verifyNoMoreInteractions(store); + + final List actions = actionCaptor.getAllValues(); + final List menuActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) + .map(a -> (MenuAction) a) + .collect(Collectors.toList()); + + final List contentActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) + .map(a -> (ContentAction) a) + .collect(Collectors.toList()); + + assertEquals(2, menuActions.size()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); + + assertEquals(2, contentActions.size()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java new file mode 100644 index 0000000000..02a16ef33e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.store; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:18 PM + * + * @author Jeroen Meulemeester + */ +public class ContentStoreTest { + + @Test + public void testOnAction() throws Exception { + final ContentStore contentStore = new ContentStore(); + + final View view = mock(View.class); + contentStore.registerView(view); + + verifyZeroInteractions(view); + + // Content should not react on menu action ... + contentStore.onAction(new MenuAction(MenuItem.PRODUCTS)); + verifyZeroInteractions(view); + + // ... but it should react on a content action + contentStore.onAction(new ContentAction(Content.COMPANY)); + verify(view, times(1)).storeChanged(eq(contentStore)); + verifyNoMoreInteractions(view); + assertEquals(Content.COMPANY, contentStore.getContent()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java new file mode 100644 index 0000000000..aa432e1ff7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.store; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:18 PM + * + * @author Jeroen Meulemeester + */ +public class MenuStoreTest { + + @Test + public void testOnAction() throws Exception { + final MenuStore menuStore = new MenuStore(); + + final View view = mock(View.class); + menuStore.registerView(view); + + verifyZeroInteractions(view); + + // Menu should not react on content action ... + menuStore.onAction(new ContentAction(Content.COMPANY)); + verifyZeroInteractions(view); + + // ... but it should react on a menu action + menuStore.onAction(new MenuAction(MenuItem.PRODUCTS)); + verify(view, times(1)).storeChanged(eq(menuStore)); + verifyNoMoreInteractions(view); + assertEquals(MenuItem.PRODUCTS, menuStore.getSelected()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java new file mode 100644 index 0000000000..c4498bacf3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.view; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.store.ContentStore; +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:31 PM + * + * @author Jeroen Meulemeester + */ +public class ContentViewTest { + + @Test + public void testStoreChanged() throws Exception { + final ContentStore store = mock(ContentStore.class); + when(store.getContent()).thenReturn(Content.PRODUCTS); + + final ContentView view = new ContentView(); + view.storeChanged(store); + + verify(store, times(1)).getContent(); + verifyNoMoreInteractions(store); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java new file mode 100644 index 0000000000..0967d51a88 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -0,0 +1,71 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.view; + +import com.iluwatar.flux.action.Action; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.dispatcher.Dispatcher; +import com.iluwatar.flux.store.MenuStore; +import com.iluwatar.flux.store.Store; +import org.junit.jupiter.api.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/12/15 - 10:31 PM + * + * @author Jeroen Meulemeester + */ +public class MenuViewTest { + + @Test + public void testStoreChanged() throws Exception { + final MenuStore store = mock(MenuStore.class); + when(store.getSelected()).thenReturn(MenuItem.HOME); + + final MenuView view = new MenuView(); + view.storeChanged(store); + + verify(store, times(1)).getSelected(); + verifyNoMoreInteractions(store); + } + + @Test + public void testItemClicked() throws Exception { + final Store store = mock(Store.class); + Dispatcher.getInstance().registerStore(store); + + final MenuView view = new MenuView(); + view.itemClicked(MenuItem.PRODUCTS); + + // We should receive a menu click action and a content changed action + verify(store, times(2)).onAction(any(Action.class)); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java new file mode 100644 index 0000000000..86d231e22a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/12/15 - 10:54 PM + * + * @author Jeroen Meulemeester + */ +public class AlchemistShopTest { + + @Test + public void testShop() throws Exception { + final AlchemistShop shop = new AlchemistShop(); + + final List bottomShelf = shop.getBottomShelf(); + assertNotNull(bottomShelf); + assertEquals(5, bottomShelf.size()); + + final List topShelf = shop.getTopShelf(); + assertNotNull(topShelf); + assertEquals(8, topShelf.size()); + + final List allPotions = new ArrayList<>(); + allPotions.addAll(topShelf); + allPotions.addAll(bottomShelf); + + // There are 13 potion instances, but only 5 unique instance types + assertEquals(13, allPotions.size()); + assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java new file mode 100644 index 0000000000..f7a33f0505 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java new file mode 100644 index 0000000000..f7fe59cf1f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java new file mode 100644 index 0000000000..ee13d47d70 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -0,0 +1,42 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Date: 12/13/15 - 1:35 PM + * + * @author Jeroen Meulemeester + */ +public class ApplicationExceptionTest { + + @Test + public void testCause() throws Exception { + final Exception cause = new Exception(); + assertSame(cause, new ApplicationException(cause).getCause()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java new file mode 100644 index 0000000000..9e8f986e20 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +public class CommandTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + static List dataProvider() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{"Archer", "Displaying archers"}); + parameters.add(new Object[]{"Catapult", "Displaying catapults"}); + parameters.add(new Object[]{"NonExistentCommand", "Error 500"}); + return parameters; + } + + /** + * @param request The request that's been tested + * @param displayMessage The expected display message + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(String request, String displayMessage) { + final FrontController frontController = new FrontController(); + assertEquals(0, appender.getLogSize()); + frontController.handleRequest(request); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java new file mode 100644 index 0000000000..4b4eb6fdd8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +public class FrontControllerTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + static List dataProvider() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); + parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); + parameters.add(new Object[]{new UnknownCommand(), "Error 500"}); + return parameters; + } + + /** + * @param command The command that's been tested + * @param displayMessage The expected display message + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(Command command, String displayMessage) { + assertEquals(0, appender.getLogSize()); + command.process(); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java new file mode 100644 index 0000000000..a0c3032359 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +public class ViewTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + static List dataProvider() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); + parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); + parameters.add(new Object[]{new ErrorView(), "Error 500"}); + return parameters; + } + + /** + * @param view The view that's been tested + * @param displayMessage The expected display message + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testDisplay(View view, String displayMessage) { + assertEquals(0, appender.getLogSize()); + view.display(); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java new file mode 100644 index 0000000000..2834bd4ef8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.guarded.suspension; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Test for Guarded Queue + */ +public class GuardedQueueTest { + private volatile Integer value; + + @Test + public void testGet() { + GuardedQueue g = new GuardedQueue(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.submit(() -> value = g.get()); + executorService.submit(() -> g.put(Integer.valueOf(10))); + executorService.shutdown(); + try { + executorService.awaitTermination(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + assertEquals(Integer.valueOf(10), value); + } + + @Test + public void testPut() { + GuardedQueue g = new GuardedQueue(); + g.put(12); + assertEquals(Integer.valueOf(12), g.get()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java new file mode 100644 index 0000000000..dea242f85a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.halfsynchalfasync; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutionException; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws InterruptedException, ExecutionException { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java new file mode 100644 index 0000000000..a5496415e3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -0,0 +1,101 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.halfsynchalfasync; + +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.io.IOException; +import java.util.concurrent.LinkedBlockingQueue; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/12/15 - 11:15 PM + * + * @author Jeroen Meulemeester + */ +public class AsynchronousServiceTest { + + @Test + public void testPerfectExecution() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final Object result = new Object(); + when(task.call()).thenReturn(result); + service.execute(task); + + verify(task, timeout(2000)).onPostCall(eq(result)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).call(); + inOrder.verify(task, times(1)).onPostCall(eq(result)); + + verifyNoMoreInteractions(task); + } + + @Test + public void testCallException() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final IOException exception = new IOException(); + when(task.call()).thenThrow(exception); + service.execute(task); + + verify(task, timeout(2000)).onError(eq(exception)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).call(); + inOrder.verify(task, times(1)).onError(exception); + + verifyNoMoreInteractions(task); + } + + @Test + public void testPreCallException() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final IllegalStateException exception = new IllegalStateException(); + doThrow(exception).when(task).onPreCall(); + service.execute(task); + + verify(task, timeout(2000)).onError(eq(exception)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).onError(exception); + + verifyNoMoreInteractions(task); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java new file mode 100644 index 0000000000..d034ee8654 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal; + +import org.junit.jupiter.api.Test; + +/** + * Unit test for simple App. + */ +public class AppTest { + + @Test + public void testApp() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java new file mode 100644 index 0000000000..f32a7068fd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.banking; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * + * Tests for banking + * + */ +public class InMemoryBankTest { + + private final WireTransfers bank = new InMemoryBank(); + + @Test + public void testInit() { + assertEquals(bank.getFunds("foo"), 0); + bank.setFunds("foo", 100); + assertEquals(bank.getFunds("foo"), 100); + bank.setFunds("bar", 150); + assertEquals(bank.getFunds("bar"), 150); + assertTrue(bank.transferFunds(50, "bar", "foo")); + assertEquals(bank.getFunds("foo"), 150); + assertEquals(bank.getFunds("bar"), 100); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java new file mode 100644 index 0000000000..d3589b0c7b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.banking; + +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for Mongo banking adapter + */ +@Disabled +public class MongoBankTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_ACCOUNTS_COLLECTION = "testAccounts"; + + private MongoBank mongoBank; + + @BeforeEach + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + mongoBank = new MongoBank(TEST_DB, TEST_ACCOUNTS_COLLECTION); + } + + @Test + public void testSetup() { + assertEquals(0, mongoBank.getAccountsCollection().count()); + } + + @Test + public void testFundTransfers() { + assertEquals(0, mongoBank.getFunds("000-000")); + mongoBank.setFunds("000-000", 10); + assertEquals(10, mongoBank.getFunds("000-000")); + assertEquals(0, mongoBank.getFunds("111-111")); + mongoBank.transferFunds(9, "000-000", "111-111"); + assertEquals(1, mongoBank.getFunds("000-000")); + assertEquals(9, mongoBank.getFunds("111-111")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java new file mode 100644 index 0000000000..f14caa94f2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.database; + +import java.util.Optional; + +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.test.LotteryTestUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * + * Tests for {@link LotteryTicketRepository} + * + */ +public class InMemoryTicketRepositoryTest { + + private final LotteryTicketRepository repository = new InMemoryTicketRepository(); + + @BeforeEach + public void clear() { + repository.deleteAll(); + } + + @Test + public void testCrudOperations() { + LotteryTicketRepository repository = new InMemoryTicketRepository(); + assertEquals(repository.findAll().size(), 0); + LotteryTicket ticket = LotteryTestUtils.createLotteryTicket(); + Optional id = repository.save(ticket); + assertTrue(id.isPresent()); + assertEquals(repository.findAll().size(), 1); + Optional optionalTicket = repository.findById(id.get()); + assertTrue(optionalTicket.isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java new file mode 100644 index 0000000000..08dcc51c3c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.database; + +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for Mongo based ticket repository + */ +@Disabled +public class MongoTicketRepositoryTest { + + private static final String TEST_DB = "lotteryTestDB"; + private static final String TEST_TICKETS_COLLECTION = "lotteryTestTickets"; + private static final String TEST_COUNTERS_COLLECTION = "testCounters"; + + private MongoTicketRepository repository; + + @BeforeEach + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + repository = new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, + TEST_COUNTERS_COLLECTION); + } + + @Test + public void testSetup() { + assertTrue(repository.getCountersCollection().count() == 1); + assertTrue(repository.getTicketsCollection().count() == 0); + } + + @Test + public void testNextId() { + assertEquals(1, repository.getNextId()); + assertEquals(2, repository.getNextId()); + assertEquals(3, repository.getNextId()); + } + + @Test + public void testCrudOperations() { + // create new lottery ticket and save it + PlayerDetails details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); + LotteryNumbers random = LotteryNumbers.createRandom(); + LotteryTicket original = new LotteryTicket(new LotteryTicketId(), details, random); + Optional saved = repository.save(original); + assertEquals(1, repository.getTicketsCollection().count()); + assertTrue(saved.isPresent()); + // fetch the saved lottery ticket from database and check its contents + Optional found = repository.findById(saved.get()); + assertTrue(found.isPresent()); + LotteryTicket ticket = found.get(); + assertEquals("foo@bar.com", ticket.getPlayerDetails().getEmail()); + assertEquals("123-123", ticket.getPlayerDetails().getBankAccount()); + assertEquals("07001234", ticket.getPlayerDetails().getPhoneNumber()); + assertEquals(original.getNumbers(), ticket.getNumbers()); + // clear the collection + repository.deleteAll(); + assertEquals(0, repository.getTicketsCollection().count()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java new file mode 100644 index 0000000000..b823bc3c7a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * + * Unit tests for {@link LotteryNumbers} + * + */ +public class LotteryNumbersTest { + + @Test + public void testGivenNumbers() { + LotteryNumbers numbers = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + assertEquals(numbers.getNumbers().size(), 4); + assertTrue(numbers.getNumbers().contains(1)); + assertTrue(numbers.getNumbers().contains(2)); + assertTrue(numbers.getNumbers().contains(3)); + assertTrue(numbers.getNumbers().contains(4)); + } + + @Test + public void testNumbersCantBeModified() { + LotteryNumbers numbers = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + assertThrows(UnsupportedOperationException.class, () -> { + numbers.getNumbers().add(5); + }); + } + + @Test + public void testRandomNumbers() { + LotteryNumbers numbers = LotteryNumbers.createRandom(); + assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS); + } + + @Test + public void testEquals() { + LotteryNumbers numbers1 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers2 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + assertTrue(numbers1.equals(numbers2)); + LotteryNumbers numbers3 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(11, 12, 13, 14))); + assertFalse(numbers1.equals(numbers3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java new file mode 100644 index 0000000000..2290b7d494 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -0,0 +1,113 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import com.iluwatar.hexagonal.module.LotteryTestingModule; +import com.iluwatar.hexagonal.test.LotteryTestUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * + * Test the lottery system + * + */ +public class LotteryTest { + + private Injector injector; + @Inject + private LotteryAdministration administration; + @Inject + private LotteryService service; + @Inject + private WireTransfers wireTransfers; + + public LotteryTest() { + this.injector = Guice.createInjector(new LotteryTestingModule()); + } + + @BeforeEach + public void setup() { + injector.injectMembers(this); + // add funds to the test player's bank account + wireTransfers.setFunds("123-12312", 100); + } + + @Test + public void testLottery() { + // admin resets the lottery + administration.resetLottery(); + assertEquals(administration.getAllSubmittedTickets().size(), 0); + + // players submit the lottery tickets + Optional ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", + "123-12312", "+32425255", new HashSet<>(Arrays.asList(1, 2, 3, 4)))); + assertTrue(ticket1.isPresent()); + Optional ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", + "123-12312", "+32423455", new HashSet<>(Arrays.asList(11, 12, 13, 14)))); + assertTrue(ticket2.isPresent()); + Optional ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", + "123-12312", "+32421255", new HashSet<>(Arrays.asList(6, 8, 13, 19)))); + assertTrue(ticket3.isPresent()); + assertEquals(administration.getAllSubmittedTickets().size(), 3); + + // perform lottery + LotteryNumbers winningNumbers = administration.performLottery(); + + // cheat a bit for testing sake, use winning numbers to submit another ticket + Optional ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", + "123-12312", "+12421255", winningNumbers.getNumbers())); + assertTrue(ticket4.isPresent()); + assertEquals(administration.getAllSubmittedTickets().size(), 4); + + // check winners + Map tickets = administration.getAllSubmittedTickets(); + for (LotteryTicketId id: tickets.keySet()) { + LotteryTicketCheckResult checkResult = service.checkTicketForPrize(id, winningNumbers); + assertTrue(checkResult.getResult() != CheckResult.TICKET_NOT_SUBMITTED); + if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { + assertTrue(checkResult.getPrizeAmount() > 0); + } else if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { + assertEquals(checkResult.getPrizeAmount(), 0); + } + } + + // check another ticket that has not been submitted + LotteryTicketCheckResult checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); + assertTrue(checkResult.getResult() == CheckResult.TICKET_NOT_SUBMITTED); + assertEquals(checkResult.getPrizeAmount(), 0); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java new file mode 100644 index 0000000000..4ded94bc4d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * + * Unit tests for {@link LotteryTicketCheckResult} + * + */ +public class LotteryTicketCheckResultTest { + + @Test + public void testEquals() { + LotteryTicketCheckResult result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + LotteryTicketCheckResult result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + assertEquals(result1, result2); + LotteryTicketCheckResult result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); + assertFalse(result1.equals(result3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java new file mode 100644 index 0000000000..6bcaea4f03 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for lottery ticket id + */ +public class LotteryTicketIdTest { + + @Test + public void testEquals() { + LotteryTicketId ticketId1 = new LotteryTicketId(); + LotteryTicketId ticketId2 = new LotteryTicketId(); + LotteryTicketId ticketId3 = new LotteryTicketId(); + assertFalse(ticketId1.equals(ticketId2)); + assertFalse(ticketId2.equals(ticketId3)); + LotteryTicketId ticketId4 = new LotteryTicketId(ticketId1.getId()); + assertTrue(ticketId1.equals(ticketId4)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java new file mode 100644 index 0000000000..2c0332458d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Test Lottery Tickets for equality + */ +public class LotteryTicketTest { + + @Test + public void testEquals() { + PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + LotteryNumbers numbers1 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); + LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); + PlayerDetails details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + LotteryNumbers numbers2 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); + LotteryTicket ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); + assertEquals(ticket1, ticket2); + PlayerDetails details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); + LotteryNumbers numbers3 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 8))); + LotteryTicket ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); + assertFalse(ticket1.equals(ticket3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java new file mode 100644 index 0000000000..4d49fcae51 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * + * Unit tests for {@link PlayerDetails} + * + */ +public class PlayerDetailsTest { + + @Test + public void testEquals() { + PlayerDetails details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + PlayerDetails details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + assertEquals(details1, details2); + PlayerDetails details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); + assertFalse(details1.equals(details3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java new file mode 100644 index 0000000000..06942a0329 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.eventlog; + +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for Mongo event log + */ +@Disabled +public class MongoEventLogTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_EVENTS_COLLECTION = "testEvents"; + + private MongoEventLog mongoEventLog; + + @BeforeEach + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION); + } + + @Test + public void testSetup() { + assertEquals(0, mongoEventLog.getEventsCollection().count()); + } + + @Test + public void testFundTransfers() { + PlayerDetails playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(1, mongoEventLog.getEventsCollection().count()); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(2, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(3, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(4, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(5, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(6, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(7, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(8, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(9, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(10, mongoEventLog.getEventsCollection().count()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java new file mode 100644 index 0000000000..fb6cfb7e45 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test. + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java new file mode 100644 index 0000000000..74259c152a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/13/15 - 3:01 PM + * + * @author Jeroen Meulemeester + */ +public class FilterManagerTest { + + @Test + public void testFilterRequest() throws Exception { + final Target target = mock(Target.class); + final FilterManager filterManager = new FilterManager(); + assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); + verifyZeroInteractions(target); + } + + @Test + public void testAddFilter() throws Exception { + final Target target = mock(Target.class); + final FilterManager filterManager = new FilterManager(); + + verifyZeroInteractions(target); + + final Filter filter = mock(Filter.class); + when(filter.execute(any(Order.class))).thenReturn("filter"); + + filterManager.addFilter(filter); + + final Order order = mock(Order.class); + assertEquals("filter", filterManager.filterRequest(order)); + + verify(filter, times(1)).execute(any(Order.class)); + verifyZeroInteractions(target, filter, order); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java new file mode 100644 index 0000000000..43170af426 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -0,0 +1,105 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Date: 12/13/15 - 2:17 PM + * + * @author Jeroen Meulemeester + */ +public class FilterTest { + + private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); + private static final Order WRONG_ORDER = new Order("name", "12345678901", "addr", "dep", ""); + private static final Order WRONG_DEPOSIT = new Order("name", "12345678901", "addr", "", "order"); + private static final Order WRONG_ADDRESS = new Order("name", "12345678901", "", "dep", "order"); + private static final Order WRONG_CONTACT = new Order("name", "", "addr", "dep", "order"); + private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); + + static List getTestData() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{new NameFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}); + testData.add(new Object[]{new NameFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new ContactFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}); + testData.add(new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new AddressFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}); + testData.add(new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new DepositFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}); + testData.add(new Object[]{new DepositFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new OrderFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"}); + + return testData; + } + + @ParameterizedTest + @MethodSource("getTestData") + public void testExecute(Filter filter, Order order, String expectedResult) throws Exception { + final String result = filter.execute(order); + assertNotNull(result); + assertEquals(expectedResult, result.trim()); + } + + @ParameterizedTest + @MethodSource("getTestData") + public void testNext(Filter filter) throws Exception { + assertNull(filter.getNext()); + assertSame(filter, filter.getLast()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java new file mode 100644 index 0000000000..3b03e45998 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -0,0 +1,73 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/13/15 - 2:57 PM + * + * @author Jeroen Meulemeester + */ +public class OrderTest { + + private static final String EXPECTED_VALUE = "test"; + + @Test + public void testSetName() throws Exception { + final Order order = new Order(); + order.setName(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getName()); + } + + @Test + public void testSetContactNumber() throws Exception { + final Order order = new Order(); + order.setContactNumber(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getContactNumber()); + } + + @Test + public void testSetAddress() throws Exception { + final Order order = new Order(); + order.setAddress(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getAddress()); + } + + @Test + public void testSetDepositNumber() throws Exception { + final Order order = new Order(); + order.setDepositNumber(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getDepositNumber()); + } + + @Test + public void testSetOrder() throws Exception { + final Order order = new Order(); + order.setOrderItem(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getOrderItem()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java new file mode 100644 index 0000000000..547c0fa13f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java new file mode 100644 index 0000000000..a3d9f21f22 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -0,0 +1,112 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.IntBinaryOperator; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/14/15 - 11:48 AM + * + * Test Case for Expressions + * @param Type of Expression + * @author Jeroen Meulemeester + */ +public abstract class ExpressionTest { + + /** + * Generate inputs ranging from -10 to 10 for both input params and calculate the expected result + * + * @param resultCalc The function used to calculate the expected result + * @return A stream with test entries + */ + static Stream prepareParameters(final IntBinaryOperator resultCalc) { + final List testData = new ArrayList<>(); + for (int i = -10; i < 10; i++) { + for (int j = -10; j < 10; j++) { + testData.add(Arguments.of( + new NumberExpression(i), + new NumberExpression(j), + resultCalc.applyAsInt(i, j) + )); + } + } + return testData.stream(); + } + + /** + * The expected {@link E#toString()} response + */ + private final String expectedToString; + + /** + * Factory, used to create a new test object instance with the correct first and second parameter + */ + private final BiFunction factory; + + /** + * Create a new test instance with the given parameters and expected results + * + * @param expectedToString The expected {@link E#toString()} response + * @param factory Factory, used to create a new test object instance + */ + ExpressionTest(final String expectedToString, + final BiFunction factory + ) { + this.expectedToString = expectedToString; + this.factory = factory; + } + + /** + * Verify if the expression calculates the correct result when calling {@link E#interpret()} + */ + @ParameterizedTest + @MethodSource("expressionProvider") + public void testInterpret(NumberExpression first, NumberExpression second, int result) { + final E expression = factory.apply(first, second); + assertNotNull(expression); + assertEquals(result, expression.interpret()); + } + + /** + * Verify if the expression has the expected {@link E#toString()} value + */ + @ParameterizedTest + @MethodSource("expressionProvider") + public void testToString(NumberExpression first, NumberExpression second) { + final E expression = factory.apply(first, second); + assertNotNull(expression); + assertEquals(expectedToString, expression.toString()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java new file mode 100644 index 0000000000..eab0ea0111 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.params.provider.Arguments; + +import java.util.stream.Stream; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +public class MinusExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + public static Stream expressionProvider() { + return prepareParameters((f, s) -> f - s); + } + + /** + * Create a new test instance using the given test parameters and expected result + */ + public MinusExpressionTest() { + super("-", MinusExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java new file mode 100644 index 0000000000..6e5384f8b2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.params.provider.Arguments; + +import java.util.stream.Stream; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +public class MultiplyExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + public static Stream expressionProvider() { + return prepareParameters((f, s) -> f * s); + } + + /** + * Create a new test instance using the given test parameters and expected result + * + */ + public MultiplyExpressionTest() { + super("*", MultiplyExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java new file mode 100644 index 0000000000..698da52bc5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +public class NumberExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + public static Stream expressionProvider() { + return prepareParameters((f, s) -> f); + } + + /** + * Create a new test instance using the given test parameters and expected result + */ + public NumberExpressionTest() { + super("number", (f, s) -> f); + } + + /** + * Verify if the {@link NumberExpression#NumberExpression(String)} constructor works as expected + */ + @ParameterizedTest + @MethodSource("expressionProvider") + public void testFromString(NumberExpression first) throws Exception { + final int expectedValue = first.interpret(); + final String testStringValue = String.valueOf(expectedValue); + final NumberExpression numberExpression = new NumberExpression(testStringValue); + assertEquals(expectedValue, numberExpression.interpret()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java new file mode 100644 index 0000000000..ae2423c7a2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.jupiter.params.provider.Arguments; + +import java.util.stream.Stream; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +public class PlusExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + public static Stream expressionProvider() { + return prepareParameters((f, s) -> f + s); + } + + /** + * Create a new test instance using the given test parameters and expected result + */ + public PlusExpressionTest() { + super("+", PlusExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/AppTest.java new file mode 100644 index 0000000000..f448a378e4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.iterator; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java new file mode 100644 index 0000000000..665666aa7c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java @@ -0,0 +1,115 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.iterator; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Date: 12/14/15 - 2:58 PM + * + * @author Jeroen Meulemeester + */ +public class TreasureChestTest { + + /** + * Create a list of all expected items in the chest. + * + * @return The set of all expected items in the chest + */ + public static List dataProvider() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); + parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of blood")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of rust")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of healing")}); + parameters.add(new Object[]{new Item(ItemType.RING, "Ring of armor")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}); + return parameters; + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testIterator(Item expectedItem) { + final TreasureChest chest = new TreasureChest(); + final ItemIterator iterator = chest.iterator(expectedItem.getType()); + assertNotNull(iterator); + + while (iterator.hasNext()) { + final Item item = iterator.next(); + assertNotNull(item); + assertEquals(expectedItem.getType(), item.getType()); + + final String name = item.toString(); + assertNotNull(name); + if (expectedItem.toString().equals(name)) { + return; + } + } + + fail("Expected to find item [" + expectedItem + "] using iterator, but we didn't."); + + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link + * TreasureChest#getItems()} method + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetItems(Item expectedItem) throws Exception { + final TreasureChest chest = new TreasureChest(); + final List items = chest.getItems(); + assertNotNull(items); + + for (final Item item : items) { + assertNotNull(item); + assertNotNull(item.getType()); + assertNotNull(item.toString()); + + final boolean sameType = expectedItem.getType() == item.getType(); + final boolean sameName = expectedItem.toString().equals(item.toString()); + if (sameType && sameName) { + return; + } + } + + fail("Expected to find item [" + expectedItem + "] in the item list, but we didn't."); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/AppTest.java new file mode 100644 index 0000000000..aa14e039d0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java new file mode 100644 index 0000000000..e13e148a37 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Date: 12/15/15 - 7:57 PM + * + * @author Jeroen Meulemeester + */ +public class CakeBakingExceptionTest { + + @Test + public void testConstructor() throws Exception { + final CakeBakingException exception = new CakeBakingException(); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testConstructorWithMessage() throws Exception { + final String expectedMessage = "message"; + final CakeBakingException exception = new CakeBakingException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java new file mode 100644 index 0000000000..f740fb5f46 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java @@ -0,0 +1,186 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/15/15 - 9:55 PM + * + * @author Jeroen Meulemeester + */ +public class CakeBakingServiceImplTest { + + @Test + public void testLayers() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialLayers = service.getAvailableLayers(); + assertNotNull(initialLayers); + assertTrue(initialLayers.isEmpty()); + + service.saveNewLayer(new CakeLayerInfo("Layer1", 1000)); + service.saveNewLayer(new CakeLayerInfo("Layer2", 2000)); + + final List availableLayers = service.getAvailableLayers(); + assertNotNull(availableLayers); + assertEquals(2, availableLayers.size()); + for (final CakeLayerInfo layer : availableLayers) { + assertNotNull(layer.id); + assertNotNull(layer.name); + assertNotNull(layer.toString()); + assertTrue(layer.calories > 0); + } + + } + + @Test + public void testToppings() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialToppings = service.getAvailableToppings(); + assertNotNull(initialToppings); + assertTrue(initialToppings.isEmpty()); + + service.saveNewTopping(new CakeToppingInfo("Topping1", 1000)); + service.saveNewTopping(new CakeToppingInfo("Topping2", 2000)); + + final List availableToppings = service.getAvailableToppings(); + assertNotNull(availableToppings); + assertEquals(2, availableToppings.size()); + for (final CakeToppingInfo topping : availableToppings) { + assertNotNull(topping.id); + assertNotNull(topping.name); + assertNotNull(topping.toString()); + assertTrue(topping.calories > 0); + } + + } + + @Test + public void testBakeCakes() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); + service.saveNewTopping(topping1); + service.saveNewTopping(topping2); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + final CakeLayerInfo layer3 = new CakeLayerInfo("Layer3", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + service.saveNewLayer(layer3); + + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); + + final List allCakes = service.getAllCakes(); + assertNotNull(allCakes); + assertEquals(2, allCakes.size()); + for (final CakeInfo cakeInfo : allCakes) { + assertNotNull(cakeInfo.id); + assertNotNull(cakeInfo.cakeToppingInfo); + assertNotNull(cakeInfo.cakeLayerInfos); + assertNotNull(cakeInfo.toString()); + assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); + assertTrue(cakeInfo.calculateTotalCalories() > 0); + } + + } + + @Test + public void testBakeCakeMissingTopping() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + + final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000); + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); + }); + } + + @Test + public void testBakeCakeMissingLayer() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + service.saveNewTopping(topping1); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + service.saveNewLayer(layer1); + + final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000); + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); + }); + } + + @Test + public void testBakeCakesUsedLayer() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); + service.saveNewTopping(topping1); + service.saveNewTopping(topping2); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + assertThrows(CakeBakingException.class, () -> { + service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); + }); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeTest.java new file mode 100644 index 0000000000..f71a0b35d4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeTest.java @@ -0,0 +1,119 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/15/15 - 8:02 PM + * + * @author Jeroen Meulemeester + */ +public class CakeTest { + + @Test + public void testSetId() { + final Cake cake = new Cake(); + assertNull(cake.getId()); + + final Long expectedId = Long.valueOf(1234L); + cake.setId(expectedId); + assertEquals(expectedId, cake.getId()); + } + + @Test + public void testSetTopping() { + final Cake cake = new Cake(); + assertNull(cake.getTopping()); + + final CakeTopping expectedTopping = new CakeTopping("DummyTopping", 1000); + cake.setTopping(expectedTopping); + assertEquals(expectedTopping, cake.getTopping()); + } + + @Test + public void testSetLayers() { + final Cake cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final Set expectedLayers = new HashSet<>(); + expectedLayers.add(new CakeLayer("layer1", 1000)); + expectedLayers.add(new CakeLayer("layer2", 2000)); + expectedLayers.add(new CakeLayer("layer3", 3000)); + + cake.setLayers(expectedLayers); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + public void testAddLayer() { + final Cake cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final Set initialLayers = new HashSet<>(); + initialLayers.add(new CakeLayer("layer1", 1000)); + initialLayers.add(new CakeLayer("layer2", 2000)); + + cake.setLayers(initialLayers); + assertEquals(initialLayers, cake.getLayers()); + + final CakeLayer newLayer = new CakeLayer("layer3", 3000); + cake.addLayer(newLayer); + + final Set expectedLayers = new HashSet<>(); + expectedLayers.addAll(initialLayers); + expectedLayers.addAll(initialLayers); + expectedLayers.add(newLayer); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + public void testToString() { + final CakeTopping topping = new CakeTopping("topping", 20); + topping.setId(2345L); + + final CakeLayer layer = new CakeLayer("layer", 100); + layer.setId(3456L); + + final Cake cake = new Cake(); + cake.setId(1234L); + cake.setTopping(topping); + cake.addLayer(layer); + + final String expected = "id=1234 topping=id=2345 name=topping calories=20 " + + "layers=[id=3456 name=layer calories=100]"; + assertEquals(expected, cake.toString()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java new file mode 100644 index 0000000000..4aed18869e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/15/15 - 10:04 PM + * + * @author Jeroen Meulemeester + */ +public class CakeViewImplTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(CakeViewImpl.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Verify if the cake view renders the expected result + */ + @Test + public void testRender() { + + final List layers = new ArrayList<>(); + layers.add(new CakeLayerInfo("layer1", 1000)); + layers.add(new CakeLayerInfo("layer2", 2000)); + layers.add(new CakeLayerInfo("layer3", 3000)); + + final List cakes = new ArrayList<>(); + final CakeInfo cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); + cakes.add(cake); + + final CakeBakingService bakingService = mock(CakeBakingService.class); + when(bakingService.getAllCakes()).thenReturn(cakes); + + final CakeViewImpl cakeView = new CakeViewImpl(bakingService); + + assertEquals(0, appender.getLogSize()); + + cakeView.render(); + assertEquals(cake.toString(), appender.getLastMessage()); + + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java new file mode 100644 index 0000000000..56b5a2c3d8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.lazy.loading; + +import org.junit.jupiter.api.Test; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; + +/** + * Date: 12/19/15 - 11:58 AM + * + * @author Jeroen Meulemeester + */ +public abstract class AbstractHolderTest { + + /** + * Get the internal state of the holder value + * + * @return The internal value + */ + abstract Heavy getInternalHeavyValue() throws Exception; + + /** + * Request a lazy loaded {@link Heavy} object from the holder. + * + * @return The lazy loaded {@link Heavy} object + */ + abstract Heavy getHeavy() throws Exception; + + /** + * This test shows that the heavy field is not instantiated until the method getHeavy is called + */ + @Test + public void testGetHeavy() throws Exception { + assertTimeout(ofMillis(3000), () -> { + assertNull(getInternalHeavyValue()); + assertNotNull(getHeavy()); + assertNotNull(getInternalHeavyValue()); + assertSame(getHeavy(), getInternalHeavyValue()); + }); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java new file mode 100644 index 0000000000..bd43b0d359 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.lazy.loading; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/AppTest.java new file mode 100644 index 0000000000..856635007c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/AppTest.java @@ -0,0 +1,36 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import org.junit.jupiter.api.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/GuardTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/GuardTest.java new file mode 100644 index 0000000000..cadd82f827 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/GuardTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Guard test + */ +public class GuardTest { + + @Test + public void testGuard() { + Guard guard = new Guard(); + assertThat(guard, instanceOf(Permission.class)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/ThiefTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/ThiefTest.java new file mode 100644 index 0000000000..56492334c9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/marker/src/test/java/ThiefTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * Thief test + */ +public class ThiefTest { + @Test + public void testThief() { + Thief thief = new Thief(); + assertFalse(thief instanceof Permission); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/AppTest.java new file mode 100644 index 0000000000..a375490cd2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java new file mode 100644 index 0000000000..820bf17ee4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/19/15 - 10:00 PM + * + * @author Jeroen Meulemeester + */ +public class PartyImplTest { + + /** + * Verify if a member is notified when it's joining a party. Generate an action and see if the + * other member gets it. Also check members don't get their own actions. + */ + @Test + public void testPartyAction() { + final PartyMember partyMember1 = mock(PartyMember.class); + final PartyMember partyMember2 = mock(PartyMember.class); + + final PartyImpl party = new PartyImpl(); + party.addMember(partyMember1); + party.addMember(partyMember2); + + verify(partyMember1).joinedParty(party); + verify(partyMember2).joinedParty(party); + + party.act(partyMember1, Action.GOLD); + verifyZeroInteractions(partyMember1); + verify(partyMember2).partyAction(Action.GOLD); + + verifyNoMoreInteractions(partyMember1, partyMember2); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java new file mode 100644 index 0000000000..61f926c314 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -0,0 +1,146 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Date: 12/19/15 - 10:13 PM + * + * @author Jeroen Meulemeester + */ +public class PartyMemberTest { + + static Collection[]> dataProvider() { + return Arrays.asList( + new Supplier[]{Hobbit::new}, + new Supplier[]{Hunter::new}, + new Supplier[]{Rogue::new}, + new Supplier[]{Wizard::new} + ); + } + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(PartyMemberBase.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Verify if a party action triggers the correct output to the std-Out + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testPartyAction(Supplier memberSupplier) { + final PartyMember member = memberSupplier.get(); + + for (final Action action : Action.values()) { + member.partyAction(action); + assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); + } + + assertEquals(Action.values().length, appender.getLogSize()); + } + + /** + * Verify if a member action triggers the expected interactions with the party class + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testAct(Supplier memberSupplier) { + final PartyMember member = memberSupplier.get(); + + member.act(Action.GOLD); + assertEquals(0, appender.getLogSize()); + + final Party party = mock(Party.class); + member.joinedParty(party); + assertEquals(member.toString() + " joins the party", appender.getLastMessage()); + + for (final Action action : Action.values()) { + member.act(action); + assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); + verify(party).act(member, action); + } + + assertEquals(Action.values().length + 1, appender.getLogSize()); + } + + /** + * Verify if {@link PartyMember#toString()} generate the expected output + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testToString(Supplier memberSupplier) throws Exception { + final PartyMember member = memberSupplier.get(); + final Class memberClass = member.getClass(); + assertEquals(memberClass.getSimpleName(), member.toString()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/AppTest.java new file mode 100644 index 0000000000..c6ea91e9bc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.memento; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/StarTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/StarTest.java new file mode 100644 index 0000000000..c3d16efe5d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/memento/src/test/java/com/iluwatar/memento/StarTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.memento; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/20/15 - 10:08 AM + * + * @author Jeroen Meulemeester + */ +public class StarTest { + + /** + * Verify the stages of a dying sun, without going back in time + */ + @Test + public void testTimePasses() { + final Star star = new Star(StarType.SUN, 1, 2); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + star.timePasses(); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.timePasses(); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 16 years mass: 8192 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 64 years mass: 0 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 256 years mass: 0 tons", star.toString()); + } + + /** + * Verify some stage of a dying sun, but go back in time to test the memento + */ + @Test + public void testSetMemento() { + final Star star = new Star(StarType.SUN, 1, 2); + final StarMemento firstMemento = star.getMemento(); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + star.timePasses(); + final StarMemento secondMemento = star.getMemento(); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.timePasses(); + final StarMemento thirdMemento = star.getMemento(); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.setMemento(thirdMemento); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.setMemento(secondMemento); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.setMemento(firstMemento); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java new file mode 100644 index 0000000000..97094b864c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.message.channel; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java new file mode 100644 index 0000000000..1c4dc3dad1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java new file mode 100644 index 0000000000..73f3487702 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java @@ -0,0 +1,122 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/20/15 - 2:19 PM + * + * @author Jeroen Meulemeester + */ +public class GiantControllerTest { + + /** + * Verify if the controller passes the health level through to the model and vice versa + */ + @Test + public void testSetHealth() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Health health : Health.values()) { + controller.setHealth(health); + verify(model).setHealth(health); + verifyZeroInteractions(view); + } + + controller.getHealth(); + verify(model).getHealth(); + + verifyNoMoreInteractions(model, view); + } + + /** + * Verify if the controller passes the fatigue level through to the model and vice versa + */ + @Test + public void testSetFatigue() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Fatigue fatigue : Fatigue.values()) { + controller.setFatigue(fatigue); + verify(model).setFatigue(fatigue); + verifyZeroInteractions(view); + } + + controller.getFatigue(); + verify(model).getFatigue(); + + verifyNoMoreInteractions(model, view); + } + + /** + * Verify if the controller passes the nourishment level through to the model and vice versa + */ + @Test + public void testSetNourishment() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Nourishment nourishment : Nourishment.values()) { + controller.setNourishment(nourishment); + verify(model).setNourishment(nourishment); + verifyZeroInteractions(view); + } + + controller.getNourishment(); + verify(model).getNourishment(); + + verifyNoMoreInteractions(model, view); + } + + @Test + public void testUpdateView() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + controller.updateView(); + verify(view).displayGiant(model); + + verifyNoMoreInteractions(model, view); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java new file mode 100644 index 0000000000..339c170f4c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/20/15 - 2:10 PM + * + * @author Jeroen Meulemeester + */ +public class GiantModelTest { + + /** + * Verify if the health value is set properly though the constructor and setter + */ + @Test + public void testSetHealth() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Health.HEALTHY, model.getHealth()); + for (final Health health : Health.values()) { + model.setHealth(health); + assertEquals(health, model.getHealth()); + assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString()); + } + } + + /** + * Verify if the fatigue level is set properly though the constructor and setter + */ + @Test + public void testSetFatigue() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Fatigue.ALERT, model.getFatigue()); + for (final Fatigue fatigue : Fatigue.values()) { + model.setFatigue(fatigue); + assertEquals(fatigue, model.getFatigue()); + assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString()); + } + } + + /** + * Verify if the nourishment level is set properly though the constructor and setter + */ + @Test + public void testSetNourishment() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Nourishment.SATURATED, model.getNourishment()); + for (final Nourishment nourishment : Nourishment.values()) { + model.setNourishment(nourishment); + assertEquals(nourishment, model.getNourishment()); + assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java new file mode 100644 index 0000000000..855c976060 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/20/15 - 2:04 PM + * + * @author Jeroen Meulemeester + */ +public class GiantViewTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(GiantView.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Verify if the {@link GiantView} does what it has to do: Print the {@link GiantModel} to the + * standard out stream, nothing more, nothing less. + */ + @Test + public void testDisplayGiant() { + final GiantView view = new GiantView(); + + final GiantModel model = mock(GiantModel.class); + view.displayGiant(model); + + assertEquals(model.toString(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java new file mode 100644 index 0000000000..c1b33cb304 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java new file mode 100644 index 0000000000..56bc3b8bdf --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java @@ -0,0 +1,43 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Date: 12/21/15 - 12:12 PM + * + * @author Jeroen Meulemeester + */ +public class FileLoaderTest { + + @Test + public void testLoadData() throws Exception { + final FileLoader fileLoader = new FileLoader(); + fileLoader.setFileName("non-existing-file"); + assertNull(fileLoader.loadData()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java new file mode 100644 index 0000000000..ff68cef6e3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -0,0 +1,145 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * This test case is responsible for testing our application by taking advantage of the + * Model-View-Controller architectural pattern. + */ +public class FileSelectorPresenterTest { + + /** + * The Presenter component. + */ + private FileSelectorPresenter presenter; + + /** + * The View component, implemented this time as a Stub!!! + */ + private FileSelectorStub stub; + + /** + * The Model component. + */ + private FileLoader loader; + + /** + * Initializes the components of the test case. + */ + @BeforeEach + public void setUp() { + this.stub = new FileSelectorStub(); + this.loader = new FileLoader(); + presenter = new FileSelectorPresenter(this.stub); + presenter.setLoader(loader); + } + + /** + * Tests if the Presenter was successfully connected with the View. + */ + @Test + public void wiring() { + presenter.start(); + + assertNotNull(stub.getPresenter()); + assertTrue(stub.isOpened()); + } + + /** + * Tests if the name of the file changes. + */ + @Test + public void updateFileNameToLoader() { + String expectedFile = "Stamatis"; + stub.setFileName(expectedFile); + + presenter.start(); + presenter.fileNameChanged(); + + assertEquals(expectedFile, loader.getFileName()); + } + + /** + * Tests if we receive a confirmation when we attempt to open a file that it's name is null or an + * empty string. + */ + @Test + public void fileConfirmationWhenNameIsNull() { + stub.setFileName(null); + + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertFalse(loader.isLoaded()); + assertEquals(1, stub.getMessagesSent()); + } + + /** + * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. + */ + @Test + public void fileConfirmationWhenFileDoesNotExist() { + stub.setFileName("RandomName.txt"); + + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertFalse(loader.isLoaded()); + assertEquals(1, stub.getMessagesSent()); + } + + /** + * Tests if we can open the file, when it exists. + */ + @Test + public void fileConfirmationWhenFileExists() { + stub.setFileName("etc/data/test.txt"); + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertTrue(loader.isLoaded()); + assertTrue(stub.dataDisplayed()); + } + + /** + * Tests if the view closes after cancellation. + */ + @Test + public void cancellation() { + presenter.start(); + presenter.cancelled(); + + assertFalse(stub.isOpened()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/AppTest.java new file mode 100644 index 0000000000..0514dff3a8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/AppTest.java @@ -0,0 +1,35 @@ +/** + * The MIT License Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.module; + +import org.junit.jupiter.api.Test; + +import java.io.FileNotFoundException; + +/** + * Tests that Module example runs without errors. + */ +public final class AppTest { + + @Test + public void test() throws FileNotFoundException { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java new file mode 100644 index 0000000000..bdae597bc2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java @@ -0,0 +1,182 @@ +/** + * The MIT License Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.module; + +import org.apache.log4j.Logger; +import org.junit.jupiter.api.Test; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages + * the creation and organization of other elements, and groups them as the structural pattern does. + * An object that applies this pattern can provide the equivalent of a namespace, providing the + * initialization and finalization process of a static class or a class with static members with + * cleaner, more concise syntax and semantics. + *

+ * The below example demonstrates a JUnit test for testing two different modules: File Logger and + * Console Logger + */ +public final class FileLoggerModuleTest { + + private static final Logger LOGGER = Logger.getLogger(FileLoggerModuleTest.class); + + private static final String OUTPUT_FILE = "output.txt"; + private static final String ERROR_FILE = "error.txt"; + + private static final String MESSAGE = "MESSAGE"; + private static final String ERROR = "ERROR"; + + + /** + * This test verify that 'MESSAGE' is perfectly printed in output file + * + * @throws IOException if program is not able to find log files (output.txt and error.txt) + */ + @Test + public void testFileMessage() throws IOException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Print 'Message' in file */ + fileLoggerModule.printString(MESSAGE); + + /* Test if 'Message' is printed in file */ + assertEquals(readFirstLine(OUTPUT_FILE), MESSAGE); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that nothing is printed in output file + * + * @throws IOException if program is not able to find log files (output.txt and error.txt) + */ + @Test + public void testNoFileMessage() throws IOException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Test if nothing is printed in file */ + assertEquals(readFirstLine(OUTPUT_FILE), null); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that 'ERROR' is perfectly printed in error file + * + * @throws FileNotFoundException if program is not able to find log files (output.txt and + * error.txt) + */ + @Test + public void testFileErrorMessage() throws FileNotFoundException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Print 'Error' in file */ + fileLoggerModule.printErrorString(ERROR); + + /* Test if 'Message' is printed in file */ + assertEquals(readFirstLine(ERROR_FILE), ERROR); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that nothing is printed in error file + * + * @throws FileNotFoundException if program is not able to find log files (output.txt and + * error.txt) + */ + @Test + public void testNoFileErrorMessage() throws FileNotFoundException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Test if nothing is printed in file */ + assertEquals(readFirstLine(ERROR_FILE), null); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * Utility method to read first line of a file + * + * @param file as file name to be read + * @return a string value as first line in file + */ + private static final String readFirstLine(final String file) { + + String firstLine = null; + BufferedReader bufferedReader = null; + try { + + /* Create a buffered reader */ + bufferedReader = new BufferedReader(new FileReader(file)); + + while (bufferedReader.ready()) { + + /* Read the line */ + firstLine = bufferedReader.readLine(); + } + + LOGGER.info("ModuleTest::readFirstLine() : firstLine : " + firstLine); + + } catch (final IOException e) { + LOGGER.error("ModuleTest::readFirstLine()", e); + } finally { + + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (final IOException e) { + LOGGER.error("ModuleTest::readFirstLine()", e); + } + } + } + + return firstLine; + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/AppTest.java new file mode 100644 index 0000000000..d6515dfc20 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + +import org.junit.jupiter.api.Test; + +/** + * Application Test + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/MonadTest.java new file mode 100644 index 0000000000..d5c4ded804 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monad/src/test/java/com/iluwatar/monad/MonadTest.java @@ -0,0 +1,65 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + +import org.junit.jupiter.api.Test; + +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Test for Monad Pattern + */ +public class MonadTest { + + @Test + public void testForInvalidName() { + User tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); + assertThrows(IllegalStateException.class, () -> { + Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get(); + }); + } + + @Test + public void testForInvalidAge() { + User john = new User("John", 17, Sex.MALE, "john@qwe.bar"); + assertThrows(IllegalStateException.class, () -> { + Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null") + .validate(User::getAge, age -> age > 21, "user is underaged") + .get(); + }); + } + + @Test + public void testForValid() { + User sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org"); + User validated = Validator.of(sarah).validate(User::getName, Objects::nonNull, "name cannot be null") + .validate(User::getAge, age -> age > 21, "user is underaged") + .validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female") + .validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign") + .get(); + assertSame(validated, sarah); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/AppTest.java new file mode 100644 index 0000000000..dfa2542aa2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monostate; + +import org.junit.jupiter.api.Test; + +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java new file mode 100644 index 0000000000..51cbcdecd8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monostate; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/21/15 - 12:26 PM + * + * @author Jeroen Meulemeester + */ +public class LoadBalancerTest { + + @Test + public void testSameStateAmongstAllInstances() { + final LoadBalancer firstBalancer = new LoadBalancer(); + final LoadBalancer secondBalancer = new LoadBalancer(); + firstBalancer.addServer(new Server("localhost", 8085, 6)); + // Both should have the same number of servers. + assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers()); + // Both Should have the same LastServedId + assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId()); + } + + @Test + public void testServe() { + final Server server = mock(Server.class); + when(server.getHost()).thenReturn("testhost"); + when(server.getPort()).thenReturn(1234); + doNothing().when(server).serve(any(Request.class)); + + final LoadBalancer loadBalancer = new LoadBalancer(); + loadBalancer.addServer(server); + + verifyZeroInteractions(server); + + final Request request = new Request("test"); + for (int i = 0; i < loadBalancer.getNoOfServers() * 2; i++) { + loadBalancer.serverRequest(request); + } + + verify(server, times(2)).serve(request); + verifyNoMoreInteractions(server); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/AppTest.java new file mode 100644 index 0000000000..14e725b26a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.multiton; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java new file mode 100644 index 0000000000..941ceeee4d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.multiton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Date: 12/22/15 - 22:28 AM + * + * @author Jeroen Meulemeester + */ +public class NazgulTest { + + /** + * Verify if {@link Nazgul#getInstance(NazgulName)} returns the correct Nazgul multiton instance + */ + @Test + public void testGetInstance() { + for (final NazgulName name : NazgulName.values()) { + final Nazgul nazgul = Nazgul.getInstance(name); + assertNotNull(nazgul); + assertSame(nazgul, Nazgul.getInstance(name)); + assertEquals(name, nazgul.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java new file mode 100644 index 0000000000..31624c9944 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.mute; + +import org.junit.jupiter.api.Test; + +/** + * Tests that Mute idiom example runs without errors. + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java new file mode 100644 index 0000000000..73bab01d22 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -0,0 +1,81 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.mute; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test for the mute-idiom pattern + */ +public class MuteTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class); + + private static final String MESSAGE = "should not occur"; + + @Test + public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + Mute.mute(() -> methodNotThrowingAnyException()); + } + + @Test + public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception { + assertThrows(AssertionError.class, () -> { + Mute.mute(() -> methodThrowingException()); + }); + } + + @Test + public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + Mute.loggedMute(() -> methodNotThrowingAnyException()); + } + + @Test + public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(stream)); + + Mute.loggedMute(() -> methodThrowingException()); + + assertTrue(new String(stream.toByteArray()).contains(MESSAGE)); + } + + + private void methodNotThrowingAnyException() { + LOGGER.info("Executed successfully"); + } + + private void methodThrowingException() throws Exception { + throw new Exception(MESSAGE); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/AppTest.java new file mode 100644 index 0000000000..8e9ecf8750 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Application Test Entrypoint + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/JarTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/JarTest.java new file mode 100644 index 0000000000..4f2e91d7e0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/JarTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test case for taking beans from a Jar + */ +public class JarTest { + + @Test + public void testTakeBeans() { + Mutex mutex = new Mutex(); + Jar jar = new Jar(10, mutex); + for (int i = 0; i < 10; i++) { + assertTrue(jar.takeBean()); + } + assertFalse(jar.takeBean()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java new file mode 100644 index 0000000000..4d61764d85 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test case for acquiring and releasing a Mutex + */ +public class MutexTest { + + @Test + public void acquireReleaseTest() { + Mutex mutex = new Mutex(); + assertNull(mutex.getOwner()); + try { + mutex.acquire(); + assertEquals(mutex.getOwner(), Thread.currentThread()); + } catch (InterruptedException e) { + fail(e.toString()); + } + mutex.release(); + assertNull(mutex.getOwner()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java new file mode 100644 index 0000000000..484807aea4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java new file mode 100644 index 0000000000..0482b7f892 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Date: 12/26/15 - 11:47 PM + * + * @author Jeroen Meulemeester + */ +public class NullNodeTest { + + /** + * Verify if {@link NullNode#getInstance()} actually returns the same object instance + */ + @Test + public void testGetInstance() { + final NullNode instance = NullNode.getInstance(); + assertNotNull(instance); + assertSame(instance, NullNode.getInstance()); + } + + @Test + public void testFields() { + final NullNode node = NullNode.getInstance(); + assertEquals(0, node.getTreeSize()); + assertNull(node.getName()); + assertNull(node.getLeft()); + assertNull(node.getRight()); + } + + @Test + public void testWalk() throws Exception { + NullNode.getInstance().walk(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java new file mode 100644 index 0000000000..f0cdbf0c92 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java @@ -0,0 +1,164 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/26/15 - 11:44 PM + * + * @author Jeroen Meulemeester + */ +public class TreeTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * During the tests, the same tree structure will be used, shown below. End points will be + * terminated with the {@link NullNode} instance. + * + *

+   * root
+   * ├── level1_a
+   * │   ├── level2_a
+   * │   │   ├── level3_a
+   * │   │   └── level3_b
+   * │   └── level2_b
+   * └── level1_b
+   * 
+ */ + private static final Node TREE_ROOT; + + static { + final NodeImpl level1B = new NodeImpl("level1_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level2B = new NodeImpl("level2_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level3A = new NodeImpl("level3_a", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level3B = new NodeImpl("level3_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level2A = new NodeImpl("level2_a", level3A, level3B); + final NodeImpl level1A = new NodeImpl("level1_a", level2A, level2B); + TREE_ROOT = new NodeImpl("root", level1A, level1B); + } + + /** + * Verify the number of items in the tree. The root has 6 children so we expect a {@link + * Node#getTreeSize()} of 7 {@link Node}s in total. + */ + @Test + public void testTreeSize() { + assertEquals(7, TREE_ROOT.getTreeSize()); + } + + /** + * Walk through the tree and verify if every item is handled + */ + @Test + public void testWalk() { + TREE_ROOT.walk(); + + assertTrue(appender.logContains("root")); + assertTrue(appender.logContains("level1_a")); + assertTrue(appender.logContains("level2_a")); + assertTrue(appender.logContains("level3_a")); + assertTrue(appender.logContains("level3_b")); + assertTrue(appender.logContains("level2_b")); + assertTrue(appender.logContains("level1_b")); + assertEquals(7, appender.getLogSize()); + } + + @Test + public void testGetLeft() throws Exception { + final Node level1 = TREE_ROOT.getLeft(); + assertNotNull(level1); + assertEquals("level1_a", level1.getName()); + assertEquals(5, level1.getTreeSize()); + + final Node level2 = level1.getLeft(); + assertNotNull(level2); + assertEquals("level2_a", level2.getName()); + assertEquals(3, level2.getTreeSize()); + + final Node level3 = level2.getLeft(); + assertNotNull(level3); + assertEquals("level3_a", level3.getName()); + assertEquals(1, level3.getTreeSize()); + assertSame(NullNode.getInstance(), level3.getRight()); + assertSame(NullNode.getInstance(), level3.getLeft()); + } + + @Test + public void testGetRight() throws Exception { + final Node level1 = TREE_ROOT.getRight(); + assertNotNull(level1); + assertEquals("level1_b", level1.getName()); + assertEquals(1, level1.getTreeSize()); + assertSame(NullNode.getInstance(), level1.getRight()); + assertSame(NullNode.getInstance(), level1.getLeft()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java new file mode 100644 index 0000000000..9bc29611c7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java @@ -0,0 +1,91 @@ +/** + * The MIT License + * Copyright (c) 2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.objectmother.test; + +import com.iluwatar.objectmother.King; +import com.iluwatar.objectmother.Queen; +import com.iluwatar.objectmother.Royalty; +import com.iluwatar.objectmother.RoyaltyObjectMother; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Generation of Royalty Types using the object-mother + */ +public class RoyaltyObjectMotherTest { + + @Test + public void unsuccessfulKingFlirt() { + King soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing(); + Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + soberUnhappyKing.flirt(flirtyQueen); + assertFalse(soberUnhappyKing.isHappy()); + } + + @Test + public void queenIsBlockingFlirtCauseDrunkKing() { + King drunkUnhappyKing = RoyaltyObjectMother.createDrunkKing(); + Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + drunkUnhappyKing.flirt(notFlirtyQueen); + assertFalse(drunkUnhappyKing.isHappy()); + } + + @Test + public void queenIsBlockingFlirt() { + King soberHappyKing = RoyaltyObjectMother.createHappyKing(); + Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + soberHappyKing.flirt(notFlirtyQueen); + assertFalse(soberHappyKing.isHappy()); + } + + @Test + public void successfullKingFlirt() { + King soberHappyKing = RoyaltyObjectMother.createHappyKing(); + Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + soberHappyKing.flirt(flirtyQueen); + assertTrue(soberHappyKing.isHappy()); + } + + @Test + public void testQueenType() { + Royalty flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + Royalty notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + assertEquals(flirtyQueen.getClass(), Queen.class); + assertEquals(notFlirtyQueen.getClass(), Queen.class); + } + + @Test + public void testKingType() { + Royalty drunkKing = RoyaltyObjectMother.createDrunkKing(); + Royalty happyDrunkKing = RoyaltyObjectMother.createHappyDrunkKing(); + Royalty happyKing = RoyaltyObjectMother.createHappyKing(); + Royalty soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing(); + assertEquals(drunkKing.getClass(), King.class); + assertEquals(happyDrunkKing.getClass(), King.class); + assertEquals(happyKing.getClass(), King.class); + assertEquals(soberUnhappyKing.getClass(), King.class); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java new file mode 100644 index 0000000000..54524c2f69 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.object.pool; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java new file mode 100644 index 0000000000..e92709fca4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java @@ -0,0 +1,125 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.object.pool; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/27/15 - 1:05 AM + * + * @author Jeroen Meulemeester + */ +public class OliphauntPoolTest { + + /** + * Use the same object 100 times subsequently. This should not take much time since the heavy + * object instantiation is done only once. Verify if we get the same object each time. + */ + @Test + public void testSubsequentCheckinCheckout() { + assertTimeout(ofMillis(5000), () -> { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); + + final Oliphaunt expectedOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + + pool.checkIn(expectedOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=0"); + + for (int i = 0; i < 100; i++) { + final Oliphaunt oliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + assertSame(expectedOliphaunt, oliphaunt); + assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); + assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); + + pool.checkIn(oliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=0"); + } + }); + } + + /** + * Use the same object 100 times subsequently. This should not take much time since the heavy + * object instantiation is done only once. Verify if we get the same object each time. + */ + @Test + public void testConcurrentCheckinCheckout() { + assertTimeout(ofMillis(5000), () -> { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); + + final Oliphaunt firstOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + + final Oliphaunt secondOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + + assertNotSame(firstOliphaunt, secondOliphaunt); + assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); + + // After checking in the second, we should get the same when checking out a new oliphaunt ... + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + final Oliphaunt oliphaunt3 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(secondOliphaunt, oliphaunt3); + + // ... and the same applies for the first one + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + final Oliphaunt oliphaunt4 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(firstOliphaunt, oliphaunt4); + + // When both oliphaunt return to the pool, we should still get the same instances + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=2 inUse=0"); + + // The order of the returned instances is not determined, so just put them in a list + // and verify if both expected instances are in there. + final List oliphaunts = Arrays.asList(pool.checkOut(), pool.checkOut()); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertTrue(oliphaunts.contains(firstOliphaunt)); + assertTrue(oliphaunts.contains(secondOliphaunt)); + }); + } + + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/AppTest.java new file mode 100644 index 0000000000..086a5de761 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java new file mode 100644 index 0000000000..21e4acd445 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +public class HobbitsTest extends WeatherObserverTest { + + static Collection dataProvider() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); + testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); + testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); + testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + */ + public HobbitsTest() { + super(Hobbits::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/OrcsTest.java new file mode 100644 index 0000000000..78667b6780 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/OrcsTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +public class OrcsTest extends WeatherObserverTest { + + static Collection dataProvider() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); + testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); + testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); + testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + */ + public OrcsTest() { + super(Orcs::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java new file mode 100644 index 0000000000..da3fad1ebc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import com.iluwatar.observer.utils.InMemoryAppender; +import java.util.function.Supplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/27/15 - 11:44 AM + * Weather Observer Tests + * @param Type of WeatherObserver + * @author Jeroen Meulemeester + */ +public abstract class WeatherObserverTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * The observer instance factory + */ + private final Supplier factory; + + /** + * Create a new test instance using the given parameters + * + * @param factory The factory, used to create an instance of the tested observer + */ + WeatherObserverTest(final Supplier factory) { + this.factory = factory; + } + + /** + * Verify if the weather has the expected influence on the observer + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testObserver(WeatherType weather, String response) { + final O observer = this.factory.get(); + assertEquals(0, appender.getLogSize()); + + observer.update(weather); + assertEquals(response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherTest.java new file mode 100644 index 0000000000..ca84be5f63 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/27/15 - 11:08 AM + * + * @author Jeroen Meulemeester + */ +public class WeatherTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Weather.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the + * observer again and verify that there are no more notifications. + */ + @Test + public void testAddRemoveObserver() { + final WeatherObserver observer = mock(WeatherObserver.class); + + final Weather weather = new Weather(); + weather.addObserver(observer); + verifyZeroInteractions(observer); + + weather.timePasses(); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); + verify(observer).update(WeatherType.RAINY); + + weather.removeObserver(observer); + weather.timePasses(); + assertEquals("The weather changed to windy.", appender.getLastMessage()); + + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); + } + + /** + * Verify if the weather passes in the order of the {@link WeatherType}s + */ + @Test + public void testTimePasses() { + final WeatherObserver observer = mock(WeatherObserver.class); + final Weather weather = new Weather(); + weather.addObserver(observer); + + final InOrder inOrder = inOrder(observer); + final WeatherType[] weatherTypes = WeatherType.values(); + for (int i = 1; i < 20; i++) { + weather.timePasses(); + inOrder.verify(observer).update(weatherTypes[i % weatherTypes.length]); + } + + verifyNoMoreInteractions(observer); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java new file mode 100644 index 0000000000..8d86529c7a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherType; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +public class GHobbitsTest extends ObserverTest { + + static Collection dataProvider() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); + testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); + testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); + testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + */ + public GHobbitsTest() { + super(GHobbits::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java new file mode 100644 index 0000000000..d7adeff89e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java @@ -0,0 +1,98 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherObserver; +import com.iluwatar.observer.WeatherType; +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +/** + * Date: 12/27/15 - 11:08 AM + * + * @author Jeroen Meulemeester + */ +public class GWeatherTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(GWeather.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the + * observer again and verify that there are no more notifications. + */ + @Test + public void testAddRemoveObserver() { + final Race observer = mock(Race.class); + + final GWeather weather = new GWeather(); + weather.addObserver(observer); + verifyZeroInteractions(observer); + + weather.timePasses(); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); + verify(observer).update(weather, WeatherType.RAINY); + + weather.removeObserver(observer); + weather.timePasses(); + assertEquals("The weather changed to windy.", appender.getLastMessage()); + + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); + } + + /** + * Verify if the weather passes in the order of the {@link WeatherType}s + */ + @Test + public void testTimePasses() { + final Race observer = mock(Race.class); + final GWeather weather = new GWeather(); + weather.addObserver(observer); + + final InOrder inOrder = inOrder(observer); + final WeatherType[] weatherTypes = WeatherType.values(); + for (int i = 1; i < 20; i++) { + weather.timePasses(); + inOrder.verify(observer).update(weather, weatherTypes[i % weatherTypes.length]); + } + + verifyNoMoreInteractions(observer); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java new file mode 100644 index 0000000000..0feba8ea2f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherType; +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/27/15 - 11:44 AM + * Test for Observers + * @param Type of Observer + * @author Jeroen Meulemeester + */ +public abstract class ObserverTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * The observer instance factory + */ + private final Supplier factory; + + /** + * Create a new test instance using the given parameters + * + * @param factory The factory, used to create an instance of the tested observer + */ + ObserverTest(final Supplier factory) { + this.factory = factory; + } + + /** + * Verify if the weather has the expected influence on the observer + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testObserver(WeatherType weather, String response) { + final O observer = this.factory.get(); + assertEquals(0, appender.getLogSize()); + + observer.update(null, weather); + assertEquals(response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java new file mode 100644 index 0000000000..95adf5a285 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherType; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +public class OrcsTest extends ObserverTest { + + static Collection dataProvider() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); + testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); + testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); + testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + */ + public OrcsTest() { + super(GOrcs::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java new file mode 100644 index 0000000000..9cc3893f47 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.AlbumPage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Album Selection and Album Listing + */ +public class AlbumListPageTest { + + private AlbumListPage albumListPage = new AlbumListPage(new WebClient()); + + @BeforeEach + public void setUp() { + albumListPage.navigateToPage(); + } + + @Test + public void testSelectAlbum() { + AlbumPage albumPage = albumListPage.selectAlbum("21"); + albumPage.navigateToPage(); + assertTrue(albumPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java new file mode 100644 index 0000000000..4b567fcad2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.AlbumPage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Album Page Operations + */ +public class AlbumPageTest { + + private AlbumPage albumPage = new AlbumPage(new WebClient()); + + @BeforeEach + public void setUp() { + albumPage.navigateToPage(); + } + + @Test + public void testSaveAlbum() { + + AlbumPage albumPageAfterChanges = albumPage + .changeAlbumTitle("25") + .changeArtist("Adele Laurie Blue Adkins") + .changeAlbumYear(2015) + .changeAlbumRating("B") + .changeNumberOfSongs(20) + .saveChanges(); + + assertTrue(albumPageAfterChanges.isAt()); + + } + + @Test + public void testCancelChanges() { + AlbumListPage albumListPage = albumPage.cancelChanges(); + albumListPage.navigateToPage(); + assertTrue(albumListPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java new file mode 100644 index 0000000000..59f69552bc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -0,0 +1,55 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.LoginPage; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Test Login Page Object + */ +public class LoginPageTest { + + private LoginPage loginPage = new LoginPage(new WebClient()); + + @BeforeEach + public void setUp() { + loginPage.navigateToPage(); + } + + @Test + public void testLogin() { + AlbumListPage albumListPage = loginPage + .enterUsername("admin") + .enterPassword("password") + .login(); + albumListPage.navigateToPage(); + assertTrue(albumListPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java new file mode 100644 index 0000000000..0bef8bfeea --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java new file mode 100644 index 0000000000..93b5f91e11 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java @@ -0,0 +1,112 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/27/15 - 9:45 PM + * + * @author Jeroen Meulemeester + */ +public class ConsumerTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Consumer.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testConsume() throws Exception { + final Message[] messages = new Message[]{ + createMessage("you", "Hello!"), + createMessage("me", "Hi!"), + Message.POISON_PILL, + createMessage("late_for_the_party", "Hello? Anyone here?"), + }; + + final MessageQueue queue = new SimpleMessageQueue(messages.length); + for (final Message message : messages) { + queue.put(message); + } + + new Consumer("NSA", queue).consume(); + + assertTrue(appender.logContains("Message [Hello!] from [you] received by [NSA]")); + assertTrue(appender.logContains("Message [Hi!] from [me] received by [NSA]")); + assertTrue(appender.logContains("Consumer NSA receive request to terminate.")); + } + + /** + * Create a new message from the given sender with the given message body + * + * @param sender The sender's name + * @param message The message body + * @return The message instance + */ + private static Message createMessage(final String sender, final String message) { + final SimpleMessage msg = new SimpleMessage(); + msg.addHeader(Message.Headers.SENDER, sender); + msg.addHeader(Message.Headers.DATE, LocalDateTime.now().toString()); + msg.setBody(message); + return msg; + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java new file mode 100644 index 0000000000..334c49809a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java @@ -0,0 +1,73 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.jupiter.api.Test; + +import static com.iluwatar.poison.pill.Message.Headers; +import static com.iluwatar.poison.pill.Message.POISON_PILL; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Date: 12/27/15 - 10:30 PM + * + * @author Jeroen Meulemeester + */ +public class PoisonMessageTest { + + @Test + public void testAddHeader() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.addHeader(Headers.SENDER, "sender"); + }); + } + + @Test + public void testGetHeader() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getHeader(Headers.SENDER); + }); + } + + @Test + public void testGetHeaders() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getHeaders(); + }); + } + + @Test + public void testSetBody() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.setBody("Test message."); + }); + } + + @Test + public void testGetBody() throws Exception { + assertThrows(UnsupportedOperationException.class, () -> { + POISON_PILL.getBody(); + }); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java new file mode 100644 index 0000000000..5d7420ecf3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java @@ -0,0 +1,86 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/27/15 - 10:32 PM + * + * @author Jeroen Meulemeester + */ +public class ProducerTest { + + @Test + public void testSend() throws Exception { + final MqPublishPoint publishPoint = mock(MqPublishPoint.class); + final Producer producer = new Producer("producer", publishPoint); + verifyZeroInteractions(publishPoint); + + producer.send("Hello!"); + + final ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); + verify(publishPoint).put(messageCaptor.capture()); + + final Message message = messageCaptor.getValue(); + assertNotNull(message); + assertEquals("producer", message.getHeader(Message.Headers.SENDER)); + assertNotNull(message.getHeader(Message.Headers.DATE)); + assertEquals("Hello!", message.getBody()); + + verifyNoMoreInteractions(publishPoint); + } + + @Test + public void testStop() throws Exception { + final MqPublishPoint publishPoint = mock(MqPublishPoint.class); + final Producer producer = new Producer("producer", publishPoint); + verifyZeroInteractions(publishPoint); + + producer.stop(); + verify(publishPoint).put(eq(Message.POISON_PILL)); + + try { + producer.send("Hello!"); + fail("Expected 'IllegalStateException' at this point, since the producer has stopped!"); + } catch (IllegalStateException e) { + assertNotNull(e); + assertNotNull(e.getMessage()); + assertEquals("Producer Hello! was stopped and fail to deliver requested message [producer].", + e.getMessage()); + } + + verifyNoMoreInteractions(publishPoint); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java new file mode 100644 index 0000000000..20f9287f42 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java @@ -0,0 +1,65 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/27/15 - 10:25 PM + * + * @author Jeroen Meulemeester + */ +public class SimpleMessageTest { + + @Test + public void testGetHeaders() { + final SimpleMessage message = new SimpleMessage(); + assertNotNull(message.getHeaders()); + assertTrue(message.getHeaders().isEmpty()); + + final String senderName = "test"; + message.addHeader(Message.Headers.SENDER, senderName); + assertNotNull(message.getHeaders()); + assertFalse(message.getHeaders().isEmpty()); + assertEquals(senderName, message.getHeaders().get(Message.Headers.SENDER)); + } + + @Test + public void testUnModifiableHeaders() { + final SimpleMessage message = new SimpleMessage(); + final Map headers = message.getHeaders(); + assertThrows(UnsupportedOperationException.class, () -> { + headers.put(Message.Headers.SENDER, "test"); + }); + } + + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java new file mode 100644 index 0000000000..efd387d751 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java new file mode 100644 index 0000000000..aac2d6ac44 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java @@ -0,0 +1,83 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/27/15 - 10:46 PM + * + * @author Jeroen Meulemeester + */ +public class ImmutableStewTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Verify if mixing the stew doesn't change the internal state + */ + @Test + public void testMix() { + final Stew stew = new Stew(1, 2, 3, 4); + final String expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; + + for (int i = 0; i < 20; i++) { + stew.mix(); + assertEquals(expectedMessage, appender.getLastMessage()); + } + + assertEquals(20, appender.getLogSize()); + } + + /** + * Verify if tasting the stew actually removes one of each ingredient + */ + @Test + public void testDrink() { + final Stew stew = new Stew(1, 2, 3, 4); + stew.mix(); + + assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender.getLastMessage()); + + stew.taste(); + assertEquals("Tasting the stew", appender.getLastMessage()); + + stew.mix(); + assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender.getLastMessage()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java new file mode 100644 index 0000000000..3345a1db29 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/27/15 - 10:46 PM + * + * @author Jeroen Meulemeester + */ +public class StewTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Verify if mixing the stew doesn't change the internal state + */ + @Test + public void testMix() { + final ImmutableStew stew = new ImmutableStew(1, 2, 3, 4); + final String expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + + "2 carrots, 3 meat and 4 peppers"; + + for (int i = 0; i < 20; i++) { + stew.mix(); + assertEquals(expectedMessage, appender.getLastMessage()); + } + + assertEquals(20, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java new file mode 100644 index 0000000000..bae8ba6358 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java new file mode 100644 index 0000000000..114b39255f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * Date: 12/27/15 - 11:01 PM + * + * @author Jeroen Meulemeester + */ +public class ConsumerTest { + + private static final int ITEM_COUNT = 5; + + @Test + public void testConsume() throws Exception { + final ItemQueue queue = spy(new ItemQueue()); + for (int id = 0; id < ITEM_COUNT; id++) { + queue.put(new Item("producer", id)); + } + + reset(queue); // Don't count the preparation above as interactions with the queue + final Consumer consumer = new Consumer("consumer", queue); + + for (int id = 0; id < ITEM_COUNT; id++) { + consumer.consume(); + } + + verify(queue, times(ITEM_COUNT)).take(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java new file mode 100644 index 0000000000..c8fe60e094 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.jupiter.api.Test; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/28/15 - 12:12 AM + * + * @author Jeroen Meulemeester + */ +public class ProducerTest { + + @Test + public void testProduce() throws Exception { + assertTimeout(ofMillis(6000), () -> { + final ItemQueue queue = mock(ItemQueue.class); + final Producer producer = new Producer("producer", queue); + + producer.produce(); + verify(queue).put(any(Item.class)); + + verifyNoMoreInteractions(queue); + }); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/AppTest.java new file mode 100644 index 0000000000..eb8790a4a3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.promise; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.ExecutionException; + +/** + * + * Application test. + */ +public class AppTest { + + @Test + public void testApp() throws InterruptedException, ExecutionException { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/PromiseTest.java new file mode 100644 index 0000000000..68868bd1e3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/promise/src/test/java/com/iluwatar/promise/PromiseTest.java @@ -0,0 +1,261 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.promise; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Tests Promise class. + */ +public class PromiseTest { + + private Executor executor; + private Promise promise; + + @BeforeEach + public void setUp() { + executor = Executors.newSingleThreadExecutor(); + promise = new Promise<>(); + } + + @Test + public void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() + throws InterruptedException, ExecutionException { + promise.fulfillInAsync(new NumberCrunchingTask(), executor); + + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, promise.get()); + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + @Test + public void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() + throws InterruptedException, ExecutionException, TimeoutException { + testWaitingForeverForPromiseToBeFulfilled(); + testWaitingSomeTimeForPromiseToBeFulfilled(); + } + + private void testWaitingForeverForPromiseToBeFulfilled() + throws InterruptedException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfillInAsync(new Callable() { + + @Override + public Integer call() throws Exception { + throw new RuntimeException("Barf!"); + } + }, executor); + + try { + promise.get(); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + promise.get(1000, TimeUnit.SECONDS); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + private void testWaitingSomeTimeForPromiseToBeFulfilled() + throws InterruptedException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfillInAsync(new Callable() { + + @Override + public Integer call() throws Exception { + throw new RuntimeException("Barf!"); + } + }, executor); + + try { + promise.get(1000, TimeUnit.SECONDS); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + promise.get(); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + } + + @Test + public void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise() + throws InterruptedException, ExecutionException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept(value -> { + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + }); + + + dependentPromise.get(); + assertTrue(dependentPromise.isDone()); + assertFalse(dependentPromise.isCancelled()); + } + + @Test + public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException() + throws InterruptedException, ExecutionException, TimeoutException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept(new Consumer() { + + @Override + public void accept(Integer value) { + throw new RuntimeException("Barf!"); + } + }); + + try { + dependentPromise.get(); + fail("Fetching dependent promise should result in exception " + + "if the action threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + dependentPromise.get(1000, TimeUnit.SECONDS); + fail("Fetching dependent promise should result in exception " + + "if the action threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + @Test + public void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise() + throws InterruptedException, ExecutionException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply(value -> { + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + return String.valueOf(value); + }); + + + assertEquals(String.valueOf(NumberCrunchingTask.CRUNCHED_NUMBER), dependentPromise.get()); + assertTrue(dependentPromise.isDone()); + assertFalse(dependentPromise.isCancelled()); + } + + @Test + public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException() + throws InterruptedException, ExecutionException, TimeoutException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply(new Function() { + + @Override + public String apply(Integer value) { + throw new RuntimeException("Barf!"); + } + }); + + try { + dependentPromise.get(); + fail("Fetching dependent promise should result in exception " + + "if the function threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + dependentPromise.get(1000, TimeUnit.SECONDS); + fail("Fetching dependent promise should result in exception " + + "if the function threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + @Test + public void fetchingAnAlreadyFulfilledPromiseReturnsTheFulfilledValueImmediately() + throws InterruptedException, ExecutionException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfill(NumberCrunchingTask.CRUNCHED_NUMBER); + + promise.get(1000, TimeUnit.SECONDS); + } + + @SuppressWarnings("unchecked") + @Test + public void exceptionHandlerIsCalledWhenPromiseIsFulfilledExceptionally() { + Promise promise = new Promise<>(); + Consumer exceptionHandler = mock(Consumer.class); + promise.onError(exceptionHandler); + + Exception exception = new Exception("barf!"); + promise.fulfillExceptionally(exception); + + verify(exceptionHandler).accept(eq(exception)); + } + + private static class NumberCrunchingTask implements Callable { + + private static final Integer CRUNCHED_NUMBER = Integer.MAX_VALUE; + + @Override + public Integer call() throws Exception { + // Do number crunching + Thread.sleep(100); + return CRUNCHED_NUMBER; + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/AppTest.java new file mode 100644 index 0000000000..4bc0beba41 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.property; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/CharacterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/CharacterTest.java new file mode 100644 index 0000000000..95a66a2fbe --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/property/src/test/java/com/iluwatar/property/CharacterTest.java @@ -0,0 +1,125 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.property; + +import org.junit.jupiter.api.Test; + +import static com.iluwatar.property.Character.Type; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/28/15 - 7:46 PM + * + * @author Jeroen Meulemeester + */ +public class CharacterTest { + + @Test + public void testPrototypeStats() throws Exception { + final Character prototype = new Character(); + + for (final Stats stat : Stats.values()) { + assertFalse(prototype.has(stat)); + assertNull(prototype.get(stat)); + + final Integer expectedValue = stat.ordinal(); + prototype.set(stat, expectedValue); + assertTrue(prototype.has(stat)); + assertEquals(expectedValue, prototype.get(stat)); + + prototype.remove(stat); + assertFalse(prototype.has(stat)); + assertNull(prototype.get(stat)); + } + + } + + @Test + public void testCharacterStats() throws Exception { + final Character prototype = new Character(); + for (final Stats stat : Stats.values()) { + prototype.set(stat, stat.ordinal()); + } + + final Character mage = new Character(Type.MAGE, prototype); + for (final Stats stat : Stats.values()) { + final Integer expectedValue = stat.ordinal(); + assertTrue(mage.has(stat)); + assertEquals(expectedValue, mage.get(stat)); + } + } + + @Test + public void testToString() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.AGILITY, 2); + prototype.set(Stats.INTELLECT, 3); + assertEquals("Stats:\n - AGILITY:2\n - ARMOR:1\n - INTELLECT:3\n", prototype.toString()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertEquals("Character type: ROGUE\nStats:\n - AGILITY:2\n - ARMOR:1\n", stupid.toString()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertEquals("Player: weak\nStats:\n - AGILITY:2\n - INTELLECT:3\n", weak.toString()); + + } + + @Test + public void testName() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.INTELLECT, 2); + assertNull(prototype.name()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertNull(stupid.name()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertEquals("weak", weak.name()); + } + + @Test + public void testType() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.INTELLECT, 2); + assertNull(prototype.type()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertEquals(Type.ROGUE, stupid.type()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertNull(weak.type()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/AppTest.java new file mode 100644 index 0000000000..e7a8c81aee --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java new file mode 100644 index 0000000000..ea164befd6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/28/15 - 8:34 PM + * + * @author Jeroen Meulemeester + */ +public class HeroFactoryImplTest { + + @Test + public void testFactory() throws Exception { + final Mage mage = mock(Mage.class); + final Warlord warlord = mock(Warlord.class); + final Beast beast = mock(Beast.class); + + when(mage.clone()).thenThrow(CloneNotSupportedException.class); + when(warlord.clone()).thenThrow(CloneNotSupportedException.class); + when(beast.clone()).thenThrow(CloneNotSupportedException.class); + + final HeroFactoryImpl factory = new HeroFactoryImpl(mage, warlord, beast); + assertNull(factory.createMage()); + assertNull(factory.createWarlord()); + assertNull(factory.createBeast()); + + verify(mage).clone(); + verify(warlord).clone(); + verify(beast).clone(); + verifyNoMoreInteractions(mage, warlord, beast); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java new file mode 100644 index 0000000000..0102428c65 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** + * Date: 12/28/15 - 8:45 PM + * @param

Prototype + * @author Jeroen Meulemeester + */ +public class PrototypeTest

{ + static Collection dataProvider() { + return Arrays.asList( + new Object[]{new OrcBeast(), "Orcish wolf"}, + new Object[]{new OrcMage(), "Orcish mage"}, + new Object[]{new OrcWarlord(), "Orcish warlord"}, + new Object[]{new ElfBeast(), "Elven eagle"}, + new Object[]{new ElfMage(), "Elven mage"}, + new Object[]{new ElfWarlord(), "Elven warlord"} + ); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testPrototype(P testedPrototype, String expectedToString) throws Exception { + assertEquals(expectedToString, testedPrototype.toString()); + + final Object clone = testedPrototype.clone(); + assertNotNull(clone); + assertNotSame(clone, testedPrototype); + assertSame(testedPrototype.getClass(), clone.getClass()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/AppTest.java new file mode 100644 index 0000000000..45bb38adca --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java new file mode 100644 index 0000000000..728223fa9f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link IvoryTower} + */ +public class IvoryTowerTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(IvoryTower.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testEnter() throws Exception { + final Wizard[] wizards = new Wizard[]{ + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin") + }; + + IvoryTower tower = new IvoryTower(); + for (Wizard wizard : wizards) { + tower.enter(wizard); + } + + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin enters the tower.")); + assertEquals(4, appender.getLogSize()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java new file mode 100644 index 0000000000..f6bbe4a2d0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Tests for {@link Wizard} + */ +public class WizardTest { + + @Test + public void testToString() throws Exception { + final String[] wizardNames = {"Gandalf", "Dumbledore", "Oz", "Merlin"}; + for (String name : wizardNames) { + assertEquals(name, new Wizard(name).toString()); + } + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java new file mode 100644 index 0000000000..b8c6c9ff50 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Tests for {@link WizardTowerProxy} + */ +public class WizardTowerProxyTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testEnter() throws Exception { + final Wizard[] wizards = new Wizard[]{ + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin") + }; + + final WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); + for (Wizard wizard : wizards) { + proxy.enter(wizard); + } + + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin is not allowed to enter!")); + assertEquals(4, appender.getLogSize()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java new file mode 100644 index 0000000000..128385faf9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.publish.subscribe; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java new file mode 100644 index 0000000000..8200625740 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Application Test + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java new file mode 100644 index 0000000000..13a1db7066 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -0,0 +1,48 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * + * Test case for submitting and retrieving messages from Blocking Queue. + * + */ +public class MessageQueueTest { + + @Test + public void messageQueueTest() { + + MessageQueue msgQueue = new MessageQueue(); + + // submit message + msgQueue.submitMsg(new Message("MessageQueue Test")); + + // retrieve message + assertEquals(msgQueue.retrieveMsg().getMsg(), "MessageQueue Test"); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java new file mode 100644 index 0000000000..d6b0167cf0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * + * Test case for creating and checking the Message. + * + */ +public class MessageTest { + + @Test + public void messageTest() { + + // Parameterized constructor test. + String testMsg = "Message Test"; + Message msg = new Message(testMsg); + assertEquals(msg.getMsg(), testMsg); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java new file mode 100644 index 0000000000..12fb4bf332 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.jupiter.api.Test; + +/** + * + * Test case for submitting Message to Blocking Queue by TaskGenerator + * and retrieve the message by ServiceExecutor. + * + */ +public class TaskGenSrvExeTest { + + @Test + public void taskGeneratorTest() { + MessageQueue msgQueue = new MessageQueue(); + + // Create a task generator thread with 1 job to submit. + Runnable taskRunnable = new TaskGenerator(msgQueue, 1); + Thread taskGenThr = new Thread(taskRunnable); + taskGenThr.start(); + + // Create a service executor thread. + Runnable srvRunnable = new ServiceExecutor(msgQueue); + Thread srvExeThr = new Thread(srvRunnable); + srvExeThr.start(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java new file mode 100644 index 0000000000..7b45c60532 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reactor.app; + +import com.iluwatar.reactor.framework.SameThreadDispatcher; +import com.iluwatar.reactor.framework.ThreadPoolDispatcher; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +/** + * + * This class tests the Distributed Logging service by starting a Reactor and then sending it + * concurrent logging requests using multiple clients. + */ +public class ReactorTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReactorTest.class); + + /** + * Test the application using pooled thread dispatcher. + * + * @throws IOException if any I/O error occurs. + * @throws InterruptedException if interrupted while stopping the application. + */ + @Test + public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingThreadPoolDispatcher start"); + App app = new App(new ThreadPoolDispatcher(2)); + app.start(); + + AppClient client = new AppClient(); + client.start(); + + // allow clients to send requests. Artificial delay. + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("sleep interrupted", e); + } + + client.stop(); + + app.stop(); + LOGGER.info("testAppUsingThreadPoolDispatcher stop"); + } + + /** + * Test the application using same thread dispatcher. + * + * @throws IOException if any I/O error occurs. + * @throws InterruptedException if interrupted while stopping the application. + */ + @Test + public void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingSameThreadDispatcher start"); + App app = new App(new SameThreadDispatcher()); + app.start(); + + AppClient client = new AppClient(); + client.start(); + + // allow clients to send requests. Artificial delay. + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("sleep interrupted", e); + } + + client.stop(); + + app.stop(); + LOGGER.info("testAppUsingSameThreadDispatcher stop"); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java new file mode 100644 index 0000000000..fbdf3f846a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import org.junit.jupiter.api.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java new file mode 100644 index 0000000000..c8de8c511b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -0,0 +1,118 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * @author hongshuwei@gmail.com + */ +public class ReaderAndWriterTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderAndWriterTest.class); + + /** + * Verify reader and writer can only get the lock to read and write orderly + */ + @Test + public void testReadAndWrite() throws Exception { + + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = new Reader("Reader 1", lock.readLock()); + Writer writer1 = new Writer("Writer 1", lock.writeLock()); + + ExecutorService executeService = Executors.newFixedThreadPool(2); + executeService.submit(reader1); + // Let reader1 execute first + Thread.sleep(150); + executeService.submit(writer1); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + } + + /** + * Verify reader and writer can only get the lock to read and write orderly + */ + @Test + public void testWriteAndRead() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = new Reader("Reader 1", lock.readLock()); + Writer writer1 = new Writer("Writer 1", lock.writeLock()); + + executeService.submit(writer1); + // Let writer1 execute first + Thread.sleep(150); + executeService.submit(reader1); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + } +} + diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java new file mode 100644 index 0000000000..8fe5912ea3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; + +/** + * @author hongshuwei@gmail.com + */ +public class ReaderTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Reader.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderTest.class); + + /** + * Verify that multiple readers can get the read lock concurrently + */ + @Test + public void testRead() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = spy(new Reader("Reader 1", lock.readLock())); + Reader reader2 = spy(new Reader("Reader 2", lock.readLock())); + + executeService.submit(reader1); + Thread.sleep(150); + executeService.submit(reader2); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + // Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads + // can be performed in the same time. + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 2 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Reader 2 finish")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java new file mode 100644 index 0000000000..bb01e11b09 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -0,0 +1,89 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.spy; + +/** + * @author hongshuwei@gmail.com + */ +public class WriterTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(Writer.class); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(WriterTest.class); + + /** + * Verify that multiple writers will get the lock in order. + */ + @Test + public void testWrite() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Writer writer1 = spy(new Writer("Writer 1", lock.writeLock())); + Writer writer2 = spy(new Writer("Writer 2", lock.writeLock())); + + executeService.submit(writer1); + // Let write1 execute first + Thread.sleep(150); + executeService.submit(writer2); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + // Write operation will hold the write lock 250 milliseconds, so here we verify that when two + // writer execute concurrently, the second writer can only writes only when the first one is + // finished. + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Writer 2 begin")); + assertTrue(appender.logContains("Writer 2 finish")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java new file mode 100644 index 0000000000..4cfb6e022f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -0,0 +1,132 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Resource; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.google.common.collect.Lists; + +/** + * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query + * by {@link org.springframework.data.jpa.domain.Specification} are also test. + * + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +public class AnnotationBasedRepositoryTest { + + @Resource + private PersonRepository repository; + + Person peter = new Person("Peter", "Sagan", 17); + Person nasta = new Person("Nasta", "Kuzminova", 25); + Person john = new Person("John", "lawrence", 35); + Person terry = new Person("Terry", "Law", 36); + + List persons = Arrays.asList(peter, nasta, john, terry); + + /** + * Prepare data for test + */ + @BeforeEach + public void setup() { + + repository.save(persons); + } + + @Test + public void testFindAll() { + + List actuals = Lists.newArrayList(repository.findAll()); + assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); + } + + @Test + public void testSave() { + + Person terry = repository.findByName("Terry"); + terry.setSurname("Lee"); + terry.setAge(47); + repository.save(terry); + + terry = repository.findByName("Terry"); + assertEquals(terry.getSurname(), "Lee"); + assertEquals(47, terry.getAge()); + } + + @Test + public void testDelete() { + + Person terry = repository.findByName("Terry"); + repository.delete(terry); + + assertEquals(3, repository.count()); + assertNull(repository.findByName("Terry")); + } + + @Test + public void testCount() { + + assertEquals(4, repository.count()); + } + + @Test + public void testFindAllByAgeBetweenSpec() { + + List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + + assertEquals(3, persons.size()); + assertTrue(persons.stream().allMatch((item) -> { + return item.getAge() > 20 && item.getAge() < 40; + })); + } + + @Test + public void testFindOneByNameEqualSpec() { + + Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual); + } + + @AfterEach + public void cleanup() { + + repository.deleteAll(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java new file mode 100644 index 0000000000..882d2bef72 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.annotation.Transactional; + +/** + * This case is Just for test the Annotation Based configuration + * + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +public class AppConfigTest { + + @Autowired + DataSource dataSource; + + /** + * Test for bean instance + */ + @Test + public void testDataSource() { + assertNotNull(dataSource); + } + + /** + * Test for correct query execution + */ + @Test + @Transactional + public void testQuery() throws SQLException { + ResultSet resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); + String result = null; + String expected = "1"; + while (resultSet.next()) { + result = resultSet.getString(1); + + } + assertTrue(result.equals(expected)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppTest.java new file mode 100644 index 0000000000..17052b51e5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Tests that Repository example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java new file mode 100644 index 0000000000..6a347ffd43 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -0,0 +1,130 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Resource; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.google.common.collect.Lists; + +/** + * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query + * by {@link org.springframework.data.jpa.domain.Specification} are also test. + */ +@ExtendWith(SpringExtension.class) +@ContextConfiguration(locations = { "classpath:applicationContext.xml" }) +public class RepositoryTest { + + @Resource + private PersonRepository repository; + + Person peter = new Person("Peter", "Sagan", 17); + Person nasta = new Person("Nasta", "Kuzminova", 25); + Person john = new Person("John", "lawrence", 35); + Person terry = new Person("Terry", "Law", 36); + + List persons = Arrays.asList(peter, nasta, john, terry); + + /** + * Prepare data for test + */ + @BeforeEach + public void setup() { + + repository.save(persons); + } + + @Test + public void testFindAll() { + + List actuals = Lists.newArrayList(repository.findAll()); + assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); + } + + @Test + public void testSave() { + + Person terry = repository.findByName("Terry"); + terry.setSurname("Lee"); + terry.setAge(47); + repository.save(terry); + + terry = repository.findByName("Terry"); + assertEquals(terry.getSurname(), "Lee"); + assertEquals(47, terry.getAge()); + } + + @Test + public void testDelete() { + + Person terry = repository.findByName("Terry"); + repository.delete(terry); + + assertEquals(3, repository.count()); + assertNull(repository.findByName("Terry")); + } + + @Test + public void testCount() { + + assertEquals(4, repository.count()); + } + + @Test + public void testFindAllByAgeBetweenSpec() { + + List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + + assertEquals(3, persons.size()); + assertTrue(persons.stream().allMatch((item) -> { + return item.getAge() > 20 && item.getAge() < 40; + })); + } + + @Test + public void testFindOneByNameEqualSpec() { + + Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual); + } + + @AfterEach + public void cleanup() { + + repository.deleteAll(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java new file mode 100644 index 0000000000..f2b0cdbe0c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.resource.acquisition.is.initialization; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java new file mode 100644 index 0000000000..4bfdf4a8be --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.resource.acquisition.is.initialization; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/28/15 - 9:31 PM + * + * @author Jeroen Meulemeester + */ +public class ClosableTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testOpenClose() throws Exception { + try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) { + assertTrue(appender.logContains("Sliding door opens.")); + assertTrue(appender.logContains("Treasure chest opens.")); + } + assertTrue(appender.logContains("Treasure chest closes.")); + assertTrue(appender.logContains("Sliding door closes.")); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java new file mode 100644 index 0000000000..46c4c62e6e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -0,0 +1,90 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.retry; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit tests for {@link FindCustomer}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class FindCustomerTest { + /** + * Returns the given result with no exceptions. + */ + @Test + public void noExceptions() throws Exception { + assertThat( + new FindCustomer("123").perform(), + is("123") + ); + } + + /** + * Throws the given exception. + * + * @throws Exception the expected exception + */ + @Test + public void oneException() throws Exception { + assertThrows(BusinessException.class, () -> { + new FindCustomer("123", new BusinessException("test")).perform(); + }); + } + + /** + * Should first throw the given exceptions, then return the given result. + * + * @throws Exception not an expected exception + */ + @Test + public void resultAfterExceptions() throws Exception { + final BusinessOperation op = new FindCustomer( + "123", + new CustomerNotFoundException("not found"), + new DatabaseNotAvailableException("not available") + ); + try { + op.perform(); + } catch (CustomerNotFoundException e) { + //ignore + } + try { + op.perform(); + } catch (DatabaseNotAvailableException e) { + //ignore + } + + assertThat( + op.perform(), + is("123") + ); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/RetryTest.java new file mode 100644 index 0000000000..233e0e5883 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -0,0 +1,111 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.retry; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Unit tests for {@link Retry}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class RetryTest { + /** + * Should contain all errors thrown. + */ + @Test + public void errors() throws Exception { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.errors(), + hasItem(e) + ); + } + + /** + * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking + * it to attempt twice. + */ + @Test + public void attempts() { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(1) + ); + } + + /** + * Final number of attempts should be equal to the number of attempts asked because we are + * asking it to ignore the exception that will be thrown. + */ + @Test + public void ignore() throws Exception { + final BusinessException e = new CustomerNotFoundException("customer not found"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0, + ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(2) + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java new file mode 100644 index 0000000000..6ad023e5d1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +/** + * Application Test Entrypoint + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java new file mode 100644 index 0000000000..7bc391478d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Test taking from and putting Fruit into a FruitBowl + */ +public class FruitBowlTest { + + @Test + public void fruitBowlTest() { + FruitBowl fbowl = new FruitBowl(); + + assertEquals(fbowl.countFruit(), 0); + + for (int i = 1; i <= 10; i++) { + fbowl.put(new Fruit(Fruit.FruitType.LEMON)); + assertEquals(fbowl.countFruit(), i); + } + + for (int i = 9; i >= 0; i--) { + assertNotNull(fbowl.take()); + assertEquals(fbowl.countFruit(), i); + } + + assertNull(fbowl.take()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java new file mode 100644 index 0000000000..ad67026ae7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Test case for acquiring and releasing a Semaphore + */ +public class SemaphoreTest { + + @Test + public void acquireReleaseTest() { + Semaphore sphore = new Semaphore(3); + + assertEquals(sphore.getAvailableLicenses(), 3); + + for (int i = 2; i >= 0; i--) { + try { + sphore.acquire(); + assertEquals(sphore.getAvailableLicenses(), i); + } catch (InterruptedException e) { + fail(e.toString()); + } + } + + for (int i = 1; i <= 3; i++) { + sphore.release(); + assertEquals(sphore.getAvailableLicenses(), i); + } + + sphore.release(); + assertEquals(sphore.getAvailableLicenses(), 3); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/AppTest.java new file mode 100644 index 0000000000..6226c272d6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/KingTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/KingTest.java new file mode 100644 index 0000000000..969cc3d43b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/KingTest.java @@ -0,0 +1,105 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/28/15 - 9:40 PM + * + * @author Jeroen Meulemeester + */ +public class KingTest { + + @Test + public void testHungrySoberUncomplimentedKing() { + final King king = new King(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedSoberUncomplimentedKing() { + final King king = new King(); + king.getFed(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungryDrunkUncomplimentedKing() { + final King king = new King(); + king.getDrink(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungrySoberComplimentedKing() { + final King king = new King(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedDrunkUncomplimentedKing() { + final King king = new King(); + king.getFed(); + king.getDrink(); + king.changeMood(); + assertTrue(king.getMood()); + } + + @Test + public void testFedSoberComplimentedKing() { + final King king = new King(); + king.getFed(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedDrunkComplimentedKing() { + final King king = new King(); + king.getFed(); + king.getDrink(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungryDrunkComplimentedKing() { + final King king = new King(); + king.getDrink(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/QueenTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/QueenTest.java new file mode 100644 index 0000000000..17498e248c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/QueenTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/28/15 - 9:52 PM + * + * @author Jeroen Meulemeester + */ +public class QueenTest { + + @Test + public void testNotFlirtyUncomplemented() throws Exception { + final Queen queen = new Queen(); + queen.setFlirtiness(false); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testNotFlirtyComplemented() throws Exception { + final Queen queen = new Queen(); + queen.setFlirtiness(false); + queen.receiveCompliments(); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testFlirtyUncomplemented() throws Exception { + final Queen queen = new Queen(); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testFlirtyComplemented() throws Exception { + final Queen queen = new Queen(); + queen.receiveCompliments(); + queen.changeMood(); + assertTrue(queen.getMood()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/ServantTest.java new file mode 100644 index 0000000000..16e1d3c00b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -0,0 +1,93 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/28/15 - 10:02 PM + * + * @author Jeroen Meulemeester + */ +public class ServantTest { + + @Test + public void testFeed() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.feed(royalty); + verify(royalty).getFed(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testGiveWine() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.giveWine(royalty); + verify(royalty).getDrink(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testGiveCompliments() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.giveCompliments(royalty); + verify(royalty).receiveCompliments(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testCheckIfYouWillBeHanged() throws Exception { + final Royalty goodMoodRoyalty = mock(Royalty.class); + when(goodMoodRoyalty.getMood()).thenReturn(true); + + final Royalty badMoodRoyalty = mock(Royalty.class); + when(badMoodRoyalty.getMood()).thenReturn(true); + + final List goodCompany = new ArrayList<>(); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + + final List badCompany = new ArrayList<>(); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(badMoodRoyalty); + + assertTrue(new Servant("test").checkIfYouWillBeHanged(goodCompany)); + assertTrue(new Servant("test").checkIfYouWillBeHanged(badCompany)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java new file mode 100644 index 0000000000..295383513a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java @@ -0,0 +1,47 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.app; + +import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + + @AfterEach + public void tearDown() throws Exception { + HibernateUtil.dropSession(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java new file mode 100644 index 0000000000..2bc557d759 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java @@ -0,0 +1,146 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.common; + +import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Date: 12/28/15 - 10:53 PM + * Test for Base Data Access Objects + * @param Type of Base Entity + * @param Type of Dao Base Implementation + * @author Jeroen Meulemeester + */ +public abstract class BaseDaoTest> { + + /** + * The number of entities stored before each test + */ + private static final int INITIAL_COUNT = 5; + + /** + * The unique id generator, shared between all entities + */ + private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); + + /** + * Factory, used to create new entity instances with the given name + */ + private final Function factory; + + /** + * The tested data access object + */ + private final D dao; + + /** + * Create a new test using the given factory and dao + * + * @param factory The factory, used to create new entity instances with the given name + * @param dao The tested data access object + */ + public BaseDaoTest(final Function factory, final D dao) { + this.factory = factory; + this.dao = dao; + } + + @BeforeEach + public void setUp() throws Exception { + for (int i = 0; i < INITIAL_COUNT; i++) { + final String className = dao.persistentClass.getSimpleName(); + final String entityName = String.format("%s%d", className, ID_GENERATOR.incrementAndGet()); + this.dao.persist(this.factory.apply(entityName)); + } + } + + @AfterEach + public void tearDown() throws Exception { + HibernateUtil.dropSession(); + } + + protected final D getDao() { + return this.dao; + } + + @Test + public void testFind() throws Exception { + final List all = this.dao.findAll(); + for (final E entity : all) { + final E byId = this.dao.find(entity.getId()); + assertNotNull(byId); + assertEquals(byId.getId(), byId.getId()); + } + } + + @Test + public void testDelete() throws Exception { + final List originalEntities = this.dao.findAll(); + this.dao.delete(originalEntities.get(1)); + this.dao.delete(originalEntities.get(2)); + + final List entitiesLeft = this.dao.findAll(); + assertNotNull(entitiesLeft); + assertEquals(INITIAL_COUNT - 2, entitiesLeft.size()); + } + + @Test + public void testFindAll() throws Exception { + final List all = this.dao.findAll(); + assertNotNull(all); + assertEquals(INITIAL_COUNT, all.size()); + } + + @Test + public void testSetId() throws Exception { + final E entity = this.factory.apply("name"); + assertNull(entity.getId()); + + final Long expectedId = Long.valueOf(1); + entity.setId(expectedId); + assertEquals(expectedId, entity.getId()); + } + + @Test + public void testSetName() throws Exception { + final E entity = this.factory.apply("name"); + assertEquals("name", entity.getName()); + assertEquals("name", entity.toString()); + + final String expectedName = "new name"; + entity.setName(expectedName); + assertEquals(expectedName, entity.getName()); + assertEquals(expectedName, entity.toString()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java new file mode 100644 index 0000000000..66750c5b26 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -0,0 +1,159 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.magic; + +import com.iluwatar.servicelayer.spell.Spell; +import com.iluwatar.servicelayer.spell.SpellDao; +import com.iluwatar.servicelayer.spellbook.Spellbook; +import com.iluwatar.servicelayer.spellbook.SpellbookDao; +import com.iluwatar.servicelayer.wizard.Wizard; +import com.iluwatar.servicelayer.wizard.WizardDao; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 12:06 AM + * + * @author Jeroen Meulemeester + */ +public class MagicServiceImplTest { + + @Test + public void testFindAllWizards() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllWizards(); + verify(wizardDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindAllSpellbooks() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllSpellbooks(); + verify(spellbookDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindAllSpells() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllSpells(); + verify(spellDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindWizardsWithSpellbook() throws Exception { + final String bookname = "bookname"; + final Spellbook spellbook = mock(Spellbook.class); + final Set wizards = new HashSet<>(); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + + when(spellbook.getWizards()).thenReturn(wizards); + + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + when(spellbookDao.findByName(eq(bookname))).thenReturn(spellbook); + + final WizardDao wizardDao = mock(WizardDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); + + final List result = service.findWizardsWithSpellbook(bookname); + verify(spellbookDao).findByName(eq(bookname)); + verify(spellbook).getWizards(); + + assertNotNull(result); + assertEquals(3, result.size()); + + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindWizardsWithSpell() throws Exception { + final Set wizards = new HashSet<>(); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + + final Spellbook spellbook = mock(Spellbook.class); + when(spellbook.getWizards()).thenReturn(wizards); + + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final WizardDao wizardDao = mock(WizardDao.class); + + final Spell spell = mock(Spell.class); + when(spell.getSpellbook()).thenReturn(spellbook); + + final String spellName = "spellname"; + final SpellDao spellDao = mock(SpellDao.class); + when(spellDao.findByName(eq(spellName))).thenReturn(spell); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); + + final List result = service.findWizardsWithSpell(spellName); + verify(spellDao).findByName(eq(spellName)); + verify(spellbook).getWizards(); + + assertNotNull(result); + assertEquals(3, result.size()); + + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java new file mode 100644 index 0000000000..e4a5bfa65e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.spell; + +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/28/15 - 11:02 PM + * + * @author Jeroen Meulemeester + */ +public class SpellDaoImplTest extends BaseDaoTest { + + public SpellDaoImplTest() { + super(Spell::new, new SpellDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final SpellDaoImpl dao = getDao(); + final List allSpells = dao.findAll(); + for (final Spell spell : allSpells) { + final Spell spellByName = dao.findByName(spell.getName()); + assertNotNull(spellByName); + assertEquals(spell.getId(), spellByName.getId()); + assertEquals(spell.getName(), spellByName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java new file mode 100644 index 0000000000..a6f1b3ea35 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.spellbook; + +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/28/15 - 11:44 PM + * + * @author Jeroen Meulemeester + */ +public class SpellbookDaoImplTest extends BaseDaoTest { + + public SpellbookDaoImplTest() { + super(Spellbook::new, new SpellbookDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final SpellbookDaoImpl dao = getDao(); + final List allBooks = dao.findAll(); + for (final Spellbook book : allBooks) { + final Spellbook spellByName = dao.findByName(book.getName()); + assertNotNull(spellByName); + assertEquals(book.getId(), spellByName.getId()); + assertEquals(book.getName(), spellByName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java new file mode 100644 index 0000000000..d8a0933198 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.wizard; + +import com.iluwatar.servicelayer.common.BaseDaoTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/28/15 - 11:46 PM + * + * @author Jeroen Meulemeester + */ +public class WizardDaoImplTest extends BaseDaoTest { + + public WizardDaoImplTest() { + super(Wizard::new, new WizardDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final WizardDaoImpl dao = getDao(); + final List allWizards = dao.findAll(); + for (final Wizard spell : allWizards) { + final Wizard byName = dao.findByName(spell.getName()); + assertNotNull(byName); + assertEquals(spell.getId(), byName.getId()); + assertEquals(spell.getName(), byName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java new file mode 100644 index 0000000000..be844b16a4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelocator; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java new file mode 100644 index 0000000000..1741f6d948 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelocator; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/29/15 - 19:07 PM + * + * @author Jeroen Meulemeester + */ +public class ServiceLocatorTest { + + /** + * Verify if we just receive 'null' when requesting a non-existing service + */ + @Test + public void testGetNonExistentService() { + assertNull(ServiceLocator.getService("fantastic/unicorn/service")); + assertNull(ServiceLocator.getService("another/fantastic/unicorn/service")); + } + + /** + * Verify if we get the same cached instance when requesting the same service twice + */ + @Test + public void testServiceCache() { + final String[] serviceNames = new String[]{ + "jndi/serviceA", "jndi/serviceB" + }; + + for (final String serviceName : serviceNames) { + final Service service = ServiceLocator.getService(serviceName); + assertNotNull(service); + assertEquals(serviceName, service.getName()); + assertTrue(service.getId() > 0); // The id is generated randomly, but the minimum value is '1' + assertSame(service, ServiceLocator.getService(serviceName)); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/AppTest.java new file mode 100644 index 0000000000..2452b923d7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.singleton; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java new file mode 100644 index 0000000000..ff90453397 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -0,0 +1,114 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.singleton; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Supplier; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTimeout; + +/** + * This class provides several test case that test singleton construction. + * + * The first proves that multiple calls to the singleton getInstance object are the same when called + * in the SAME thread. The second proves that multiple calls to the singleton getInstance object are + * the same when called in the DIFFERENT thread. + * + * Date: 12/29/15 - 19:25 PM + * @param Supplier method generating singletons + * @author Jeroen Meulemeester + * @author Richard Jones + */ +public abstract class SingletonTest { + + /** + * The singleton's getInstance method + */ + private final Supplier singletonInstanceMethod; + + /** + * Create a new singleton test instance using the given 'getInstance' method + * + * @param singletonInstanceMethod The singleton's getInstance method + */ + public SingletonTest(final Supplier singletonInstanceMethod) { + this.singletonInstanceMethod = singletonInstanceMethod; + } + + /** + * Test the singleton in a non-concurrent setting + */ + @Test + public void testMultipleCallsReturnTheSameObjectInSameThread() { + // Create several instances in the same calling thread + S instance1 = this.singletonInstanceMethod.get(); + S instance2 = this.singletonInstanceMethod.get(); + S instance3 = this.singletonInstanceMethod.get(); + // now check they are equal + assertSame(instance1, instance2); + assertSame(instance1, instance3); + assertSame(instance2, instance3); + } + + /** + * Test singleton instance in a concurrent setting + */ + @Test + public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { + assertTimeout(ofMillis(10000), () -> { + // Create 10000 tasks and inside each callable instantiate the singleton class + final List> tasks = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + tasks.add(this.singletonInstanceMethod::get); + } + + // Use up to 8 concurrent threads to handle the tasks + final ExecutorService executorService = Executors.newFixedThreadPool(8); + final List> results = executorService.invokeAll(tasks); + + // wait for all of the threads to complete + final S expectedInstance = this.singletonInstanceMethod.get(); + for (Future res : results) { + final S instance = res.get(); + assertNotNull(instance); + assertSame(expectedInstance, instance); + } + + // tidy up the executor + executorService.shutdown(); + }); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/app/AppTest.java new file mode 100644 index 0000000000..8cd648e583 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.app; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java new file mode 100644 index 0000000000..2d43c8d598 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -0,0 +1,94 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.creature; + +import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Movement; +import com.iluwatar.specification.property.Size; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/29/15 - 7:47 PM + * + * @author Jeroen Meulemeester + */ +public class CreatureTest { + + /** + * @return The tested {@link Creature} instance and its expected specs + */ + public static Collection dataProvider() { + return Arrays.asList( + new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED}, + new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN}, + new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT}, + new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK}, + new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT}, + new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK} + ); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetName(Creature testedCreature, String name) throws Exception { + assertEquals(name, testedCreature.getName()); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetSize(Creature testedCreature, String name, Size size) throws Exception { + assertEquals(size, testedCreature.getSize()); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetMovement(Creature testedCreature, String name, Size size, Movement movement) throws Exception { + assertEquals(movement, testedCreature.getMovement()); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testGetColor(Creature testedCreature, String name, Size size, Movement movement, + Color color) throws Exception { + assertEquals(color, testedCreature.getColor()); + } + + @ParameterizedTest + @MethodSource("dataProvider") + public void testToString(Creature testedCreature, String name, Size size, Movement movement, + Color color) throws Exception { + final String toString = testedCreature.toString(); + assertNotNull(toString); + assertEquals( + String.format("%s [size=%s, movement=%s, color=%s]", name, size, movement, color), + toString + ); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java new file mode 100644 index 0000000000..5765c1c56a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Color; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:35 PM + * + * @author Jeroen Meulemeester + */ +public class ColorSelectorTest { + + /** + * Verify if the color selector gives the correct results + */ + @Test + public void testColor() { + final Creature greenCreature = mock(Creature.class); + when(greenCreature.getColor()).thenReturn(Color.GREEN); + + final Creature redCreature = mock(Creature.class); + when(redCreature.getColor()).thenReturn(Color.RED); + + final ColorSelector greenSelector = new ColorSelector(Color.GREEN); + assertTrue(greenSelector.test(greenCreature)); + assertFalse(greenSelector.test(redCreature)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java new file mode 100644 index 0000000000..8c7c0a54e4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Movement; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:37 PM + * + * @author Jeroen Meulemeester + */ +public class MovementSelectorTest { + + /** + * Verify if the movement selector gives the correct results + */ + @Test + public void testMovement() { + final Creature swimmingCreature = mock(Creature.class); + when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING); + + final Creature flyingCreature = mock(Creature.class); + when(flyingCreature.getMovement()).thenReturn(Movement.FLYING); + + final MovementSelector swimmingSelector = new MovementSelector(Movement.SWIMMING); + assertTrue(swimmingSelector.test(swimmingCreature)); + assertFalse(swimmingSelector.test(flyingCreature)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java new file mode 100644 index 0000000000..c15e932bc5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -0,0 +1,57 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Size; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:43 PM + * + * @author Jeroen Meulemeester + */ +public class SizeSelectorTest { + + /** + * Verify if the size selector gives the correct results + */ + @Test + public void testMovement() { + final Creature normalCreature = mock(Creature.class); + when(normalCreature.getSize()).thenReturn(Size.NORMAL); + + final Creature smallCreature = mock(Creature.class); + when(smallCreature.getSize()).thenReturn(Size.SMALL); + + final SizeSelector normalSelector = new SizeSelector(Size.NORMAL); + assertTrue(normalSelector.test(normalCreature)); + assertFalse(normalSelector.test(smallCreature)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/AppTest.java new file mode 100644 index 0000000000..16bffb2af0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/MammothTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/MammothTest.java new file mode 100644 index 0000000000..5c3bf3e699 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -0,0 +1,120 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * Date: 12/29/15 - 8:27 PM + * + * @author Jeroen Meulemeester + */ +public class MammothTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * Switch to a complete mammoth 'mood'-cycle and verify if the observed mood matches the expected + * value. + */ + @Test + public void testTimePasses() { + final Mammoth mammoth = new Mammoth(); + + mammoth.observe(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(1 , appender.getLogSize()); + + mammoth.timePasses(); + assertEquals("The mammoth gets angry!", appender.getLastMessage()); + assertEquals(2 , appender.getLogSize()); + + mammoth.observe(); + assertEquals("The mammoth is furious!", appender.getLastMessage()); + assertEquals(3 , appender.getLogSize()); + + mammoth.timePasses(); + assertEquals("The mammoth calms down.", appender.getLastMessage()); + assertEquals(4 , appender.getLogSize()); + + mammoth.observe(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(5 , appender.getLogSize()); + + } + + /** + * Verify if {@link Mammoth#toString()} gives the expected value + */ + @Test + public void testToString() { + final String toString = new Mammoth().toString(); + assertNotNull(toString); + assertEquals("The mammoth", toString); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java new file mode 100644 index 0000000000..a5b7c952f8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.stepbuilder; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java new file mode 100644 index 0000000000..220e3f89ad --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java @@ -0,0 +1,177 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.stepbuilder; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/29/15 - 9:21 PM + * + * @author Jeroen Meulemeester + */ +public class CharacterStepBuilderTest { + + /** + * Build a new wizard {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .withAbility("invisibility") + .withAbility("wisdom") + .noMoreAbilities() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertEquals("poison", character.getSpell()); + assertNotNull(character.toString()); + + final List abilities = character.getAbilities(); + assertNotNull(abilities); + assertEquals(2, abilities.size()); + assertTrue(abilities.contains("invisibility")); + assertTrue(abilities.contains("wisdom")); + + } + + /** + * Build a new wizard {@link Character} without spell or abilities and verify if it has the + * expected attributes + */ + @Test + public void testBuildPoorWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .noSpell() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertNull(character.getSpell()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + /** + * Build a new wizard {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWeakWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .noAbilities() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertEquals("poison", character.getSpell()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + + /** + * Build a new warrior {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Cuauhtemoc") + .fighterClass("aztec") + .withWeapon("spear") + .withAbility("speed") + .withAbility("strength") + .noMoreAbilities() + .build(); + + assertEquals("Cuauhtemoc", character.getName()); + assertEquals("aztec", character.getFighterClass()); + assertEquals("spear", character.getWeapon()); + assertNotNull(character.toString()); + + final List abilities = character.getAbilities(); + assertNotNull(abilities); + assertEquals(2, abilities.size()); + assertTrue(abilities.contains("speed")); + assertTrue(abilities.contains("strength")); + + } + + /** + * Build a new wizard {@link Character} without weapon and abilities and verify if it has the + * expected attributes + */ + @Test + public void testBuildPoorWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Poor warrior") + .fighterClass("none") + .noWeapon() + .build(); + + assertEquals("Poor warrior", character.getName()); + assertEquals("none", character.getFighterClass()); + assertNull(character.getWeapon()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + /** + * Build a new warrior {@link Character} without any abilities, but with a weapon and verify if it + * has the expected attributes + */ + @Test + public void testBuildWeakWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Weak warrior") + .fighterClass("none") + .withWeapon("Slingshot") + .noAbilities() + .build(); + + assertEquals("Weak warrior", character.getName()); + assertEquals("none", character.getFighterClass()); + assertEquals("Slingshot", character.getWeapon()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/AppTest.java new file mode 100644 index 0000000000..c14af1bde1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java new file mode 100644 index 0000000000..d22bf4235e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/29/15 - 10:50 PM + * + * @author Jeroen Meulemeester + */ +public class DragonSlayerTest { + + /** + * Verify if the dragon slayer uses the strategy during battle + */ + @Test + public void testGoToBattle() { + final DragonSlayingStrategy strategy = mock(DragonSlayingStrategy.class); + final DragonSlayer dragonSlayer = new DragonSlayer(strategy); + + dragonSlayer.goToBattle(); + verify(strategy).execute(); + verifyNoMoreInteractions(strategy); + } + + /** + * Verify if the dragon slayer uses the new strategy during battle after a change of strategy + */ + @Test + public void testChangeStrategy() throws Exception { + final DragonSlayingStrategy initialStrategy = mock(DragonSlayingStrategy.class); + final DragonSlayer dragonSlayer = new DragonSlayer(initialStrategy); + + dragonSlayer.goToBattle(); + verify(initialStrategy).execute(); + + final DragonSlayingStrategy newStrategy = mock(DragonSlayingStrategy.class); + dragonSlayer.changeStrategy(newStrategy); + + dragonSlayer.goToBattle(); + verify(newStrategy).execute(); + + verifyNoMoreInteractions(initialStrategy, newStrategy); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java new file mode 100644 index 0000000000..c988ad2f61 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -0,0 +1,113 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/29/15 - 10:58 PM + * + * @author Jeroen Meulemeester + */ +public class DragonSlayingStrategyTest { + + /** + * @return The test parameters for each cycle + */ + static Collection dataProvider() { + return Arrays.asList( + new Object[]{ + new MeleeStrategy(), + "With your Excalibur you sever the dragon's head!" + }, + new Object[]{ + new ProjectileStrategy(), + "You shoot the dragon with the magical crossbow and it falls dead on the ground!" + }, + new Object[]{ + new SpellStrategy(), + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" + } + ); + } + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + + /** + * Test if executing the strategy gives the correct response + */ + @ParameterizedTest + @MethodSource("dataProvider") + public void testExecute(DragonSlayingStrategy strategy, String expectedResult) { + strategy.execute(); + assertEquals(expectedResult, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java new file mode 100644 index 0000000000..2974117ea4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java new file mode 100644 index 0000000000..86a823386e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -0,0 +1,72 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/29/15 - 18:15 PM + * + * @author Jeroen Meulemeester + */ +public class HalflingThiefTest { + + /** + * Verify if the thief uses the provided stealing method + */ + @Test + public void testSteal() { + final StealingMethod method = mock(StealingMethod.class); + final HalflingThief thief = new HalflingThief(method); + + thief.steal(); + verify(method).steal(); + + verifyNoMoreInteractions(method); + } + + /** + * Verify if the thief uses the provided stealing method, and the new method after changing it + */ + @Test + public void testChangeMethod() { + final StealingMethod initialMethod = mock(StealingMethod.class); + final HalflingThief thief = new HalflingThief(initialMethod); + + thief.steal(); + verify(initialMethod).steal(); + + final StealingMethod newMethod = mock(StealingMethod.class); + thief.changeMethod(newMethod); + + thief.steal(); + verify(newMethod).steal(); + + verifyNoMoreInteractions(initialMethod, newMethod); + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java new file mode 100644 index 0000000000..884ffe6eed --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -0,0 +1,171 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Date: 12/30/15 - 18:12 PM + * @param Type of StealingMethod + * @author Jeroen Meulemeester + */ +public abstract class StealingMethodTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * The tested stealing method + */ + private final M method; + + /** + * The expected target + */ + private final String expectedTarget; + + /** + * The expected target picking result + */ + private final String expectedTargetResult; + + /** + * The expected confusion method + */ + private final String expectedConfuseMethod; + + /** + * The expected stealing method + */ + private final String expectedStealMethod; + + /** + * Create a new test for the given stealing method, together with the expected results + * + * @param method The tested stealing method + * @param expectedTarget The expected target name + * @param expectedTargetResult The expected target picking result + * @param expectedConfuseMethod The expected confusion method + * @param expectedStealMethod The expected stealing method + */ + public StealingMethodTest(final M method, String expectedTarget, final String expectedTargetResult, + final String expectedConfuseMethod, final String expectedStealMethod) { + + this.method = method; + this.expectedTarget = expectedTarget; + this.expectedTargetResult = expectedTargetResult; + this.expectedConfuseMethod = expectedConfuseMethod; + this.expectedStealMethod = expectedStealMethod; + } + + /** + * Verify if the thief picks the correct target + */ + @Test + public void testPickTarget() { + assertEquals(expectedTarget, this.method.pickTarget()); + } + + /** + * Verify if the target confusing step goes as planned + */ + @Test + public void testConfuseTarget() { + assertEquals(0, appender.getLogSize()); + + this.method.confuseTarget(this.expectedTarget); + assertEquals(this.expectedConfuseMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Verify if the stealing step goes as planned + */ + @Test + public void testStealTheItem() { + assertEquals(0, appender.getLogSize()); + + this.method.stealTheItem(this.expectedTarget); + assertEquals(this.expectedStealMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Verify if the complete steal process goes as planned + */ + @Test + public void testSteal() { + this.method.steal(); + + assertTrue(appender.logContains(this.expectedTargetResult)); + assertTrue(appender.logContains(this.expectedConfuseMethod)); + assertTrue(appender.logContains(this.expectedStealMethod)); + assertEquals(3, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java new file mode 100644 index 0000000000..fafbce15e8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import org.junit.jupiter.api.Test; + +/** + * Application test + * + * @author ilkka + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java new file mode 100644 index 0000000000..099cdc6e81 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java @@ -0,0 +1,147 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.IntFunction; +import java.util.stream.Collectors; + +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; + +/** + * Date: 12/30/15 - 18:22 PM + * Test for Tasks using a Thread Pool + * @param Type of Task + * @author Jeroen Meulemeester + */ +public abstract class TaskTest { + + /** + * The number of tasks used during the concurrency test + */ + private static final int TASK_COUNT = 128 * 1024; + + /** + * The number of threads used during the concurrency test + */ + private static final int THREAD_COUNT = 8; + + /** + * The task factory, used to create new test items + */ + private final IntFunction factory; + + /** + * The expected time needed to run the task 1 single time, in milli seconds + */ + private final int expectedExecutionTime; + + /** + * Create a new test instance + * + * @param factory The task factory, used to create new test items + * @param expectedExecutionTime The expected time needed to run the task 1 time, in milli seconds + */ + public TaskTest(final IntFunction factory, final int expectedExecutionTime) { + this.factory = factory; + this.expectedExecutionTime = expectedExecutionTime; + } + + /** + * Verify if the generated id is unique for each task, even if the tasks are created in separate + * threads + */ + @Test + public void testIdGeneration() throws Exception { + assertTimeout(ofMillis(10000), () -> { + final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); + + final List> tasks = new ArrayList<>(); + for (int i = 0; i < TASK_COUNT; i++) { + tasks.add(() -> factory.apply(1).getId()); + } + + final List ids = service.invokeAll(tasks) + .stream() + .map(TaskTest::get) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + service.shutdownNow(); + + final long uniqueIdCount = ids.stream() + .distinct() + .count(); + + assertEquals(TASK_COUNT, ids.size()); + assertEquals(TASK_COUNT, uniqueIdCount); + }); + } + + /** + * Verify if the time per execution of a task matches the actual time required to execute the task + * a given number of times + */ + @Test + public void testTimeMs() { + for (int i = 0; i < 10; i++) { + assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs()); + } + } + + /** + * Verify if the task has some sort of {@link T#toString()}, different from 'null' + */ + @Test + public void testToString() { + assertNotNull(this.factory.apply(0).toString()); + } + + /** + * Extract the result from a future or returns 'null' when an exception occurred + * + * @param future The future we want the result from + * @param The result type + * @return The result or 'null' when a checked exception occurred + */ + private static O get(Future future) { + try { + return future.get(); + } catch (InterruptedException | ExecutionException e) { + return null; + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java new file mode 100644 index 0000000000..3b7186e986 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/30/15 - 18:21 PM + * + * @author Jeroen Meulemeester + */ +public class WorkerTest { + + /** + * Verify if a worker does the actual job + */ + @Test + public void testRun() { + final Task task = mock(Task.class); + final Worker worker = new Worker(task); + verifyZeroInteractions(task); + + worker.run(); + verify(task).getTimeMs(); + verifyNoMoreInteractions(task); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/AppTest.java new file mode 100644 index 0000000000..97a54864c6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import org.junit.jupiter.api.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java new file mode 100644 index 0000000000..0c15bac6e2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java @@ -0,0 +1,48 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import com.iluwatar.throttling.timer.ThrottleTimerImpl; +import com.iluwatar.throttling.timer.Throttler; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * B2BServiceTest class to test the B2BService + */ +public class B2BServiceTest { + + @Test + public void dummyCustomerApiTest() { + Tenant tenant = new Tenant("testTenant", 2); + Throttler timer = new ThrottleTimerImpl(100); + B2BService service = new B2BService(timer); + + for (int i = 0; i < 5; i++) { + service.dummyCustomerApi(tenant); + } + long counter = CallsCount.getCount(tenant.getName()); + assertTrue(counter == 2, "Counter limit must be reached"); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java new file mode 100644 index 0000000000..00e546d02e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java @@ -0,0 +1,42 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import org.junit.jupiter.api.Test; + +import java.security.InvalidParameterException; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * TenantTest to test the creation of Tenant with valid parameters. + */ +public class TenantTest { + + @Test + public void constructorTest() { + assertThrows(InvalidParameterException.class, () -> { + Tenant tenant = new Tenant("FailTenant", -1); + }); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/AppTest.java new file mode 100644 index 0000000000..12bb1ea3cb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import org.junit.jupiter.api.Test; + +/** + * Tests that thread local storage example runs without errors. + * + * @author Thomas Bauer, January 2017 + * + */ +public class AppTest { + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java new file mode 100644 index 0000000000..bb2dfafb72 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -0,0 +1,145 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * After a successful run 5 date values should be in the result object. All dates should have + * the same value (15.11.2015). To avoid problems with time zone not the date instances themselves + * are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTest { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdDateValues = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by the run of DateFormatRunnalbe + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeAll + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + createdDateValues = convertDatesToString(result); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new ArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + */ + @Test + public void testDateValues() { + assertEquals(expectedDateValues, createdDateValues); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver 5 date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should deliver + * no exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java new file mode 100644 index 0000000000..da1b9c2645 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -0,0 +1,128 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * An incorrect formatted date is passed to the Callable + * After a successful run 0 date values and 5 exceptions should be in the result object. + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestIncorrectDateFormat { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdExceptions = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 0; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 5; + + /** + * Expected content of the list containing the exceptions created by the run of DateFormatRunnalbe + */ + List expectedExceptions = Arrays.asList("class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\""); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeAll + public static void setup() { + // Create a callable. Pass a string date value not matching the format string + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15.12.2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + /** + * Test Exceptions after the run of DateFormatRunnalbe. A correct run should deliver 5 times the + * same exception + */ + @Test + public void testExecptions() { + assertEquals(expectedExceptions, result.getExceptionList()); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver no date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java new file mode 100644 index 0000000000..845ab366da --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -0,0 +1,165 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is used by 4 threads in parallel + *

+ * After a successful run 5 date values should be in the result object of each thread. All dates + * should have the same value (15.11.2015). To avoid problems with time zone not the date instances + * themselves are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestMultiThread { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable, one for each thread + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result[] result = new Result[4]; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + @SuppressWarnings("serial") + static class StringArrayList extends ArrayList { + /* nothing needed here */ + } + static List[] createdDateValues = new StringArrayList[4]; + + /** + * Expected number of date values in the date value list created by each thread + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by each thread + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by each thread + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeAll + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult1 = executor.submit(callableDf); + Future futureResult2 = executor.submit(callableDf); + Future futureResult3 = executor.submit(callableDf); + Future futureResult4 = executor.submit(callableDf); + try { + result[0] = futureResult1.get(); + result[1] = futureResult2.get(); + result[2] = futureResult3.get(); + result[3] = futureResult4.get(); + for (int i = 0; i < result.length; i++) { + createdDateValues[i] = convertDatesToString(result[i]); + } + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new StringArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + * by each thread + */ + @Test + public void testDateValues() { + for (int i = 0; i < createdDateValues.length; i++) { + assertEquals(expectedDateValues, createdDateValues[i]); + } + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 date values by each thread + */ + @Test + public void testCounterDateValues() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterDateValues, result[i].getDateList().size()); + } + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver no exceptions + */ + @Test + public void testCounterExceptions() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterExceptions, result[i].getExceptionList().size()); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java new file mode 100644 index 0000000000..07e6f6b891 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.tolerantreader; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.io.IOException; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws ClassNotFoundException, IOException { + String[] args = {}; + App.main(args); + } + + @BeforeEach + @AfterEach + public void cleanup() { + File file1 = new File("fish1.out"); + file1.delete(); + File file2 = new File("fish2.out"); + file2.delete(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java new file mode 100644 index 0000000000..2785c8374a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java @@ -0,0 +1,92 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.tolerantreader; + +import org.junit.Rule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.rules.TemporaryFolder; + +import java.io.File; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +/** + * Date: 12/30/15 - 18:39 PM + * + * @author Jeroen Meulemeester + */ +@EnableRuleMigrationSupport +public class RainbowFishSerializerTest { + + /** + * Create a temporary folder, used to generate files in during this test + */ + @Rule + public final TemporaryFolder testFolder = new TemporaryFolder(); + + /** + * Rainbow fish version 1 used during the tests + */ + private static final RainbowFish V1 = new RainbowFish("version1", 1, 2, 3); + + /** + * Rainbow fish version 2 used during the tests + */ + private static final RainbowFishV2 V2 = new RainbowFishV2("version2", 4, 5, 6, true, false, true); + + /** + * Verify if a fish, written as version 1 can be read back as version 1 + */ + @Test + public void testWriteV1ReadV1() throws Exception { + final File outputFile = this.testFolder.newFile(); + RainbowFishSerializer.writeV1(V1, outputFile.getPath()); + + final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + assertNotSame(V1, fish); + assertEquals(V1.getName(), fish.getName()); + assertEquals(V1.getAge(), fish.getAge()); + assertEquals(V1.getLengthMeters(), fish.getLengthMeters()); + assertEquals(V1.getWeightTons(), fish.getWeightTons()); + + } + + /** + * Verify if a fish, written as version 2 can be read back as version 1 + */ + @Test + public void testWriteV2ReadV1() throws Exception { + final File outputFile = this.testFolder.newFile(); + RainbowFishSerializer.writeV2(V2, outputFile.getPath()); + + final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + assertNotSame(V2, fish); + assertEquals(V2.getName(), fish.getName()); + assertEquals(V2.getAge(), fish.getAge()); + assertEquals(V2.getLengthMeters(), fish.getLengthMeters()); + assertEquals(V2.getWeightTons(), fish.getWeightTons()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/AppTest.java new file mode 100644 index 0000000000..76f189f3f3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallItemTest.java new file mode 100644 index 0000000000..3c443ef623 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -0,0 +1,133 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/30/15 - 18:44 PM + * + * @author Jeroen Meulemeester + */ +public class BallItemTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + @Test + public void testClick() { + final BallThread ballThread = mock(BallThread.class); + final BallItem ballItem = new BallItem(); + ballItem.setTwin(ballThread); + + final InOrder inOrder = inOrder(ballThread); + + for (int i = 0; i < 10; i++) { + ballItem.click(); + inOrder.verify(ballThread).suspendMe(); + + ballItem.click(); + inOrder.verify(ballThread).resumeMe(); + } + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testDoDraw() { + final BallItem ballItem = new BallItem(); + final BallThread ballThread = mock(BallThread.class); + ballItem.setTwin(ballThread); + + ballItem.draw(); + assertTrue(appender.logContains("draw")); + assertTrue(appender.logContains("doDraw")); + + verifyNoMoreInteractions(ballThread); + assertEquals(2, appender.getLogSize()); + } + + @Test + public void testMove() { + final BallItem ballItem = new BallItem(); + final BallThread ballThread = mock(BallThread.class); + ballItem.setTwin(ballThread); + + ballItem.move(); + assertTrue(appender.logContains("move")); + + verifyNoMoreInteractions(ballThread); + assertEquals(1, appender.getLogSize()); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java new file mode 100644 index 0000000000..010e6c7e2b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java @@ -0,0 +1,119 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import org.junit.jupiter.api.Test; + +import static java.lang.Thread.UncaughtExceptionHandler; +import static java.lang.Thread.sleep; +import static java.time.Duration.ofMillis; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/30/15 - 18:55 PM + * + * @author Jeroen Meulemeester + */ +public class BallThreadTest { + + /** + * Verify if the {@link BallThread} can be resumed + */ + @Test + public void testSuspend() throws Exception { + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); + + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); + + ballThread.start(); + + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); + ballThread.suspendMe(); + + sleep(1000); + + ballThread.stopMe(); + ballThread.join(); + + verifyNoMoreInteractions(ballItem); + }); + } + + /** + * Verify if the {@link BallThread} can be resumed + */ + @Test + public void testResume() throws Exception { + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); + + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); + + ballThread.suspendMe(); + ballThread.start(); + + sleep(1000); + + verifyZeroInteractions(ballItem); + + ballThread.resumeMe(); + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); + + ballThread.stopMe(); + ballThread.join(); + + verifyNoMoreInteractions(ballItem); + }); + } + + /** + * Verify if the {@link BallThread} is interruptible + */ + @Test + public void testInterrupt() throws Exception { + assertTimeout(ofMillis(5000), () -> { + final BallThread ballThread = new BallThread(); + final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); + ballThread.setUncaughtExceptionHandler(exceptionHandler); + ballThread.setTwin(mock(BallItem.class)); + ballThread.start(); + ballThread.interrupt(); + ballThread.join(); + + verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); + verifyNoMoreInteractions(exceptionHandler); + }); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/AppTest.java new file mode 100644 index 0000000000..86dcb5be3e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.value.object; + +import org.junit.jupiter.api.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java new file mode 100644 index 0000000000..f19382d4e3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.value.object; + +import com.google.common.testing.EqualsTester; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.junit.Assert.assertThat; + +/** + * Unit test for HeroStat. + */ +public class HeroStatTest { + + /** + * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. + * + * @see http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/ + * EqualsTester.html + */ + @Test + public void testEquals() { + HeroStat heroStatA = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatB = HeroStat.valueOf(3, 9, 2); + new EqualsTester().addEqualityGroup(heroStatA, heroStatB).testEquals(); + } + + /** + * The toString() for two equal values must be the same. For two non-equal values it must be + * different. + */ + @Test + public void testToString() { + HeroStat heroStatA = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatB = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatC = HeroStat.valueOf(3, 9, 8); + + assertThat(heroStatA.toString(), is(heroStatB.toString())); + assertThat(heroStatA.toString(), is(not(heroStatC.toString()))); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/AppTest.java new file mode 100644 index 0000000000..0fc97cc563 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import org.junit.jupiter.api.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java new file mode 100644 index 0000000000..57fe193976 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -0,0 +1,83 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.function.Function; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/30/15 - 18:59 PM + * Test related to Units + * @param Type of Unit + * @author Jeroen Meulemeester + */ +public abstract class UnitTest { + + /** + * Factory to create new instances of the tested unit + */ + private final Function factory; + + /** + * Create a new test instance for the given unit type {@link U} + * + * @param factory Factory to create new instances of the tested unit + */ + public UnitTest(final Function factory) { + this.factory = factory; + } + + @Test + public void testAccept() throws Exception { + final Unit[] children = new Unit[5]; + Arrays.setAll(children, (i) -> mock(Unit.class)); + + final U unit = this.factory.apply(children); + final UnitVisitor visitor = mock(UnitVisitor.class); + unit.accept(visitor); + verifyVisit(unit, visitor); + + for (final Unit child : children) { + verify(child).accept(eq(visitor)); + } + + verifyNoMoreInteractions(children); + verifyNoMoreInteractions(visitor); + } + + /** + * Verify if the correct visit method is called on the mock, depending on the tested instance + * + * @param unit The tested unit instance + * @param mockedVisitor The mocked {@link UnitVisitor} who should have gotten a visit by the unit + */ + abstract void verifyVisit(final U unit, final UnitVisitor mockedVisitor); + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java new file mode 100644 index 0000000000..68f4681c61 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-6694d742a370e0f181530734481284de8d5dd8ef/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -0,0 +1,143 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Date: 12/30/15 - 18:59 PM + * Test case for Visitor Pattern + * @param Type of UnitVisitor + * @author Jeroen Meulemeester + */ +public abstract class VisitorTest { + + private InMemoryAppender appender; + + @BeforeEach + public void setUp() { + appender = new InMemoryAppender(); + } + + @AfterEach + public void tearDown() { + appender.stop(); + } + + /** + * The tested visitor instance + */ + private final V visitor; + + /** + * The optional expected response when being visited by a commander + */ + private final Optional commanderResponse; + + /** + * The optional expected response when being visited by a sergeant + */ + private final Optional sergeantResponse; + + /** + * The optional expected response when being visited by a soldier + */ + private final Optional soldierResponse; + + /** + * Create a new test instance for the given visitor + * + * @param commanderResponse The optional expected response when being visited by a commander + * @param sergeantResponse The optional expected response when being visited by a sergeant + * @param soldierResponse The optional expected response when being visited by a soldier + */ + public VisitorTest(final V visitor, final Optional commanderResponse, + final Optional sergeantResponse, final Optional soldierResponse) { + + this.visitor = visitor; + this.commanderResponse = commanderResponse; + this.sergeantResponse = sergeantResponse; + this.soldierResponse = soldierResponse; + } + + @Test + public void testVisitCommander() { + this.visitor.visitCommander(new Commander()); + if (this.commanderResponse.isPresent()) { + assertEquals(this.commanderResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + @Test + public void testVisitSergeant() { + this.visitor.visitSergeant(new Sergeant()); + if (this.sergeantResponse.isPresent()) { + assertEquals(this.sergeantResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + @Test + public void testVisitSoldier() { + this.visitor.visitSoldier(new Soldier()); + if (this.soldierResponse.isPresent()) { + assertEquals(this.soldierResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java new file mode 100644 index 0000000000..f6686ff8fd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotNull; + +/** + * AbstractDocument test class + */ +public class AbstractDocumentTest { + + private static final String KEY = "key"; + private static final String VALUE = "value"; + + private class DocumentImplementation extends AbstractDocument { + + DocumentImplementation(Map properties) { + super(properties); + } + } + + private DocumentImplementation document = new DocumentImplementation(new HashMap<>()); + + @Test + public void shouldPutAndGetValue() { + document.put(KEY, VALUE); + assertEquals(VALUE, document.get(KEY)); + } + + @Test + public void shouldRetrieveChildren() { + Map child1 = new HashMap<>(); + Map child2 = new HashMap<>(); + List> children = Arrays.asList(child1, child2); + + document.put(KEY, children); + + Stream childrenStream = document.children(KEY, DocumentImplementation::new); + assertNotNull(children); + assertEquals(2, childrenStream.count()); + } + + @Test + public void shouldRetrieveEmptyStreamForNonExistingChildren() { + Stream children = document.children(KEY, DocumentImplementation::new); + assertNotNull(children); + assertEquals(0, children.count()); + } + + @Test + public void shouldIncludePropsInToString() { + Map props = new HashMap<>(); + props.put(KEY, VALUE); + DocumentImplementation document = new DocumentImplementation(props); + assertNotNull(document.toString().contains(KEY)); + assertNotNull(document.toString().contains(VALUE)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java new file mode 100644 index 0000000000..b91f57b274 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import org.junit.Test; + +/** + * Simple App test + */ +public class AppTest { + + @Test + public void shouldExecuteAppWithoutException() { + App.main(null); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java new file mode 100644 index 0000000000..03d75d5e5e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractdocument; + +import com.iluwatar.abstractdocument.domain.Car; +import com.iluwatar.abstractdocument.domain.HasModel; +import com.iluwatar.abstractdocument.domain.HasParts; +import com.iluwatar.abstractdocument.domain.HasPrice; +import com.iluwatar.abstractdocument.domain.HasType; +import com.iluwatar.abstractdocument.domain.Part; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static junit.framework.TestCase.assertEquals; + +/** + * Test for Part and Car + */ +public class DomainTest { + + private static final String TEST_PART_TYPE = "test-part-type"; + private static final String TEST_PART_MODEL = "test-part-model"; + private static final long TEST_PART_PRICE = 0L; + + private static final String TEST_CAR_MODEL = "test-car-model"; + private static final long TEST_CAR_PRICE = 1L; + + @Test + public void shouldConstructPart() { + Map partProperties = new HashMap<>(); + partProperties.put(HasType.PROPERTY, TEST_PART_TYPE); + partProperties.put(HasModel.PROPERTY, TEST_PART_MODEL); + partProperties.put(HasPrice.PROPERTY, TEST_PART_PRICE); + Part part = new Part(partProperties); + + assertEquals(TEST_PART_TYPE, part.getType().get()); + assertEquals(TEST_PART_MODEL, part.getModel().get()); + assertEquals(TEST_PART_PRICE, part.getPrice().get()); + } + + @Test + public void shouldConstructCar() { + Map carProperties = new HashMap<>(); + carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL); + carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE); + carProperties.put(HasParts.PROPERTY, Arrays.asList(new HashMap<>(), new HashMap<>())); + Car car = new Car(carProperties); + + assertEquals(TEST_CAR_MODEL, car.getModel().get()); + assertEquals(TEST_CAR_PRICE, car.getPrice().get()); + assertEquals(2, car.getParts().count()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java new file mode 100644 index 0000000000..7613edf65f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AbstractFactoryTest.java @@ -0,0 +1,106 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractfactory; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.iluwatar.abstractfactory.App.FactoryMaker; +import com.iluwatar.abstractfactory.App.FactoryMaker.KingdomType; + +import org.junit.Before; +import org.junit.Test; + +/** + * Test for abstract factory + */ +public class AbstractFactoryTest { + + private App app = new App(); + private KingdomFactory elfFactory; + private KingdomFactory orcFactory; + + @Before + public void setUp() { + elfFactory = FactoryMaker.makeFactory(KingdomType.ELF); + orcFactory = FactoryMaker.makeFactory(KingdomType.ORC); + } + + @Test + public void king() { + final King elfKing = app.getKing(elfFactory); + assertTrue(elfKing instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, elfKing.getDescription()); + final King orcKing = app.getKing(orcFactory); + assertTrue(orcKing instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, orcKing.getDescription()); + } + + @Test + public void castle() { + final Castle elfCastle = app.getCastle(elfFactory); + assertTrue(elfCastle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, elfCastle.getDescription()); + final Castle orcCastle = app.getCastle(orcFactory); + assertTrue(orcCastle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, orcCastle.getDescription()); + } + + @Test + public void army() { + final Army elfArmy = app.getArmy(elfFactory); + assertTrue(elfArmy instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, elfArmy.getDescription()); + final Army orcArmy = app.getArmy(orcFactory); + assertTrue(orcArmy instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, orcArmy.getDescription()); + } + + @Test + public void createElfKingdom() { + app.createKingdom(elfFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof ElfKing); + assertEquals(ElfKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof ElfCastle); + assertEquals(ElfCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof ElfArmy); + assertEquals(ElfArmy.DESCRIPTION, army.getDescription()); + } + + @Test + public void createOrcKingdom() { + app.createKingdom(orcFactory); + final King king = app.getKing(); + final Castle castle = app.getCastle(); + final Army army = app.getArmy(); + assertTrue(king instanceof OrcKing); + assertEquals(OrcKing.DESCRIPTION, king.getDescription()); + assertTrue(castle instanceof OrcCastle); + assertEquals(OrcCastle.DESCRIPTION, castle.getDescription()); + assertTrue(army instanceof OrcArmy); + assertEquals(OrcArmy.DESCRIPTION, army.getDescription()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java new file mode 100644 index 0000000000..b9d5f7d906 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/abstract-factory/src/test/java/com/iluwatar/abstractfactory/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.abstractfactory; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Abstract Factory example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java new file mode 100644 index 0000000000..9938f05596 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.adapter; + +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Test class + * + */ +public class AdapterPatternTest { + + private Map beans; + + private static final String FISHING_BEAN = "fisher"; + + private static final String ROWING_BEAN = "captain"; + + /** + * This method runs before the test execution and sets the bean objects in the beans Map. + */ + @Before + public void setup() { + beans = new HashMap<>(); + + FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter()); + beans.put(FISHING_BEAN, fishingBoatAdapter); + + Captain captain = new Captain(); + captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN)); + beans.put(ROWING_BEAN, captain); + } + + /** + * This test asserts that when we use the row() method on a captain bean(client), it is + * internally calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter} + * ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one + * expected by the client ({@link Captain} ). + */ + @Test + public void testAdapter() { + RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN); + + // when captain moves + captain.row(); + + // the captain internally calls the battleship object to move + RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN); + verify(adapter).row(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AppTest.java new file mode 100644 index 0000000000..2130356276 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/adapter/src/test/java/com/iluwatar/adapter/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.adapter; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Adapter example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java new file mode 100644 index 0000000000..2955f6781d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/aggregator-service/src/test/java/com/iluwatar/aggregator/microservices/AggregatorTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.aggregator.microservices; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * Test Aggregation of domain objects + */ +public class AggregatorTest { + + @InjectMocks + private Aggregator aggregator; + + @Mock + private ProductInformationClient informationClient; + + @Mock + private ProductInventoryClient inventoryClient; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + /** + * Tests getting the data for a desktop client + */ + @Test + public void testGetProduct() { + String title = "The Product Title."; + int inventories = 5; + + when(informationClient.getProductTitle()).thenReturn(title); + when(inventoryClient.getProductInventories()).thenReturn(inventories); + + Product testProduct = aggregator.getProduct(); + + assertEquals(title, testProduct.getTitle()); + assertEquals(inventories, testProduct.getProductInventories()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java new file mode 100644 index 0000000000..127dd39563 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/information-microservice/src/test/java/com/iluwatar/information/microservice/InformationControllerTest.java @@ -0,0 +1,42 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.information.microservice; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for Information Rest Controller + */ +public class InformationControllerTest { + + @Test + public void shouldGetProductTitle() { + InformationController infoController = new InformationController(); + + String title = infoController.getProductTitle(); + + Assert.assertEquals("The Product Title.", title); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java new file mode 100644 index 0000000000..b04370fba2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/aggregator-microservices/inventory-microservice/src/test/java/com/iluwatar/inventory/microservice/InventoryControllerTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.inventory.microservice; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test Inventory Rest Controller + */ +public class InventoryControllerTest { + @Test + public void testGetProductInventories() throws Exception { + InventoryController inventoryController = new InventoryController(); + + int numberOfInventories = inventoryController.getProductInventories(); + + Assert.assertEquals(5, numberOfInventories); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java new file mode 100644 index 0000000000..6a79e5d002 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/api-gateway-service/src/test/java/com/iluwatar/api/gateway/ApiGatewayTest.java @@ -0,0 +1,81 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.api.gateway; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +/** + * Test API Gateway Pattern + */ +public class ApiGatewayTest { + + @InjectMocks + private ApiGateway apiGateway; + + @Mock + private ImageClient imageClient; + + @Mock + private PriceClient priceClient; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + /** + * Tests getting the data for a desktop client + */ + @Test + public void testGetProductDesktop() { + String imagePath = "/product-image.png"; + String price = "20"; + when(imageClient.getImagePath()).thenReturn(imagePath); + when(priceClient.getPrice()).thenReturn(price); + + DesktopProduct desktopProduct = apiGateway.getProductDesktop(); + + assertEquals(price, desktopProduct.getPrice()); + assertEquals(imagePath, desktopProduct.getImagePath()); + } + + /** + * Tests getting the data for a mobile client + */ + @Test + public void testGetProductMobile() { + String price = "20"; + when(priceClient.getPrice()).thenReturn(price); + + MobileProduct mobileProduct = apiGateway.getProductMobile(); + + assertEquals(price, mobileProduct.getPrice()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java new file mode 100644 index 0000000000..1b934014a4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/image-microservice/src/test/java/com/iluwatar/image/microservice/ImageControllerTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.image.microservice; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test for Image Rest Controller + */ +public class ImageControllerTest { + @Test + public void testGetImagePath() { + ImageController imageController = new ImageController(); + + String imagePath = imageController.getImagePath(); + + Assert.assertEquals("/product-image.png", imagePath); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java new file mode 100644 index 0000000000..b1fe66d42f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/api-gateway/price-microservice/src/test/java/com/iluwatar/price/microservice/PriceControllerTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.price.microservice; + +import org.junit.Assert; +import org.junit.Test; + + +/** + * Test for Price Rest Controller + */ +public class PriceControllerTest { + @Test + public void testgetPrice() { + PriceController priceController = new PriceController(); + + String price = priceController.getPrice(); + + Assert.assertEquals("20", price); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java new file mode 100644 index 0000000000..ef2649f8af --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.async.method.invocation; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java new file mode 100644 index 0000000000..d0e730344b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/async-method-invocation/src/test/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutorTest.java @@ -0,0 +1,311 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.async.method.invocation; + +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; + +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Date: 12/6/15 - 10:49 AM + * + * @author Jeroen Meulemeester + */ +public class ThreadAsyncExecutorTest { + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} + */ + @Test(timeout = 3000) + public void testSuccessfulTaskWithoutCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} + */ + @Test(timeout = 3000) + public void testSuccessfulTaskWithCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenReturn(result); + + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + // Our task should only execute once ... + verify(task, times(1)).call(); + + // ... same for the callback, we expect our object + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(eq(result), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute + */ + @Test(timeout = 5000) + public void testLongRunningTaskWithoutCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when a task + * takes a while to execute + */ + @Test(timeout = 5000) + public void testLongRunningTaskWithCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(task, callback); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + verifyZeroInteractions(callback); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + // Our task should only execute once, but it can take a while ... + verify(task, timeout(3000).times(1)).call(); + + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, timeout(3000).times(1)).onComplete(eq(result), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertFalse(optionalException.isPresent()); + + // Prevent timing issues, and wait until the result is available + asyncResult.await(); + assertTrue(asyncResult.isCompleted()); + verifyNoMoreInteractions(task, callback); + + // ... and the result should be exactly the same object + assertSame(result, asyncResult.getValue()); + } + + /** + * Test used to verify the happy path of {@link ThreadAsyncExecutor#startProcess(Callable)} when a task takes a while + * to execute, while waiting on the result using {@link ThreadAsyncExecutor#endProcess(AsyncResult)} + */ + @Test(timeout = 5000) + public void testEndProcess() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + + final Object result = new Object(); + final Callable task = mock(Callable.class); + when(task.call()).thenAnswer(i -> { + Thread.sleep(1500); + return result; + }); + + final AsyncResult asyncResult = executor.startProcess(task); + assertNotNull(asyncResult); + assertFalse(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected IllegalStateException when calling AsyncResult#getValue on a non-completed task"); + } catch (IllegalStateException e) { + assertNotNull(e.getMessage()); + } + + assertSame(result, executor.endProcess(asyncResult)); + verify(task, times(1)).call(); + assertTrue(asyncResult.isCompleted()); + + // Calling end process a second time while already finished should give the same result + assertSame(result, executor.endProcess(asyncResult)); + verifyNoMoreInteractions(task); + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable)} when the callable is 'null' + */ + @Test(timeout = 3000) + public void testNullTask() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null); + + assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when the + * callable is 'null', but the asynchronous callback is provided + */ + @Test(timeout = 3000) + public void testNullTaskWithCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncCallback callback = mock(AsyncCallback.class); + final AsyncResult asyncResult = executor.startProcess(null, callback); + + assertNotNull("The AsyncResult should not be 'null', even though the task was 'null'.", asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + final ArgumentCaptor> optionalCaptor = ArgumentCaptor.forClass((Class) Optional.class); + verify(callback, times(1)).onComplete(Matchers.isNull(), optionalCaptor.capture()); + + final Optional optionalException = optionalCaptor.getValue(); + assertNotNull(optionalException); + assertTrue(optionalException.isPresent()); + + final Exception exception = optionalException.get(); + assertNotNull(exception); + assertEquals(NullPointerException.class, exception.getClass()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + + } + + /** + * Test used to verify the behaviour of {@link ThreadAsyncExecutor#startProcess(Callable, AsyncCallback)} when both + * the callable and the asynchronous callback are 'null' + */ + @Test(timeout = 3000) + public void testNullTaskWithNullCallback() throws Exception { + // Instantiate a new executor and start a new 'null' task ... + final ThreadAsyncExecutor executor = new ThreadAsyncExecutor(); + final AsyncResult asyncResult = executor.startProcess(null, null); + + assertNotNull("The AsyncResult should not be 'null', even though the task and callback were 'null'.", asyncResult); + asyncResult.await(); // Prevent timing issues, and wait until the result is available + assertTrue(asyncResult.isCompleted()); + + try { + asyncResult.getValue(); + fail("Expected ExecutionException with NPE as cause"); + } catch (final ExecutionException e) { + assertNotNull(e.getMessage()); + assertNotNull(e.getCause()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/AppTest.java new file mode 100644 index 0000000000..df104b9016 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.balking; + +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void main() throws Exception { + String[] args = {}; + App.main(args); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java new file mode 100644 index 0000000000..ecf81f409e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/balking/src/test/java/com/iluwatar/balking/WashingMachineTest.java @@ -0,0 +1,65 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.balking; + +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +/** + * Tests for {@link WashingMachine} + */ +public class WashingMachineTest { + + private volatile WashingMachineState machineStateGlobal; + + @Test + public void wash() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.execute(washingMachine::wash); + executorService.execute(() -> { + washingMachine.wash(); + machineStateGlobal = washingMachine.getWashingMachineState(); + }); + executorService.shutdown(); + try { + executorService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + assertEquals(WashingMachineState.WASHING, machineStateGlobal); + } + + @Test + public void endOfWashing() throws Exception { + WashingMachine washingMachine = new WashingMachine(); + washingMachine.wash(); + assertEquals(WashingMachineState.ENABLED, washingMachine.getWashingMachineState()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/AppTest.java new file mode 100644 index 0000000000..fcf7e44cef --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java new file mode 100644 index 0000000000..a650bae04d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Tests for hammer + */ +public class HammerTest extends WeaponTest { + + /** + * Invoke all possible actions on the weapon and check if the actions are executed on the actual + * underlying weapon implementation. + */ + @Test + public void testHammer() throws Exception { + final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class))); + testBasicWeaponActions(hammer); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java new file mode 100644 index 0000000000..7ffd0e492c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Tests for sword + */ +public class SwordTest extends WeaponTest { + + /** + * Invoke all possible actions on the weapon and check if the actions are executed on the actual + * underlying weapon implementation. + */ + @Test + public void testSword() throws Exception { + final Sword sword = spy(new Sword(mock(FlyingEnchantment.class))); + testBasicWeaponActions(sword); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java new file mode 100644 index 0000000000..0e62374be7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -0,0 +1,59 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.bridge; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Base class for weapon tests + */ +public abstract class WeaponTest { + + /** + * Invoke the basic actions of the given weapon, and test if the underlying enchantment implementation + * is invoked + * + */ + protected final void testBasicWeaponActions(final Weapon weapon) { + assertNotNull(weapon); + Enchantment enchantment = weapon.getEnchantment(); + assertNotNull(enchantment); + assertNotNull(weapon.getEnchantment()); + + weapon.swing(); + verify(enchantment).apply(); + verifyNoMoreInteractions(enchantment); + + weapon.wield(); + verify(enchantment).onActivate(); + verifyNoMoreInteractions(enchantment); + + weapon.unwield(); + verify(enchantment).onDeactivate(); + verifyNoMoreInteractions(enchantment); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/AppTest.java new file mode 100644 index 0000000000..b30c50cda4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.builder; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/HeroTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/HeroTest.java new file mode 100644 index 0000000000..c111fb853b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/builder/src/test/java/com/iluwatar/builder/HeroTest.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.builder; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/6/15 - 11:01 PM + * + * @author Jeroen Meulemeester + */ +public class HeroTest { + + /** + * Test if we get the expected exception when trying to create a hero without a profession + */ + @Test(expected = IllegalArgumentException.class) + public void testMissingProfession() throws Exception { + new Hero.Builder(null, "Sir without a job"); + } + + /** + * Test if we get the expected exception when trying to create a hero without a name + */ + @Test(expected = IllegalArgumentException.class) + public void testMissingName() throws Exception { + new Hero.Builder(Profession.THIEF, null); + } + + /** + * Test if the hero build by the builder has the correct attributes, as requested + */ + @Test + public void testBuildHero() throws Exception { + final String heroName = "Sir Lancelot"; + + final Hero hero = new Hero.Builder(Profession.WARRIOR, heroName) + .withArmor(Armor.CHAIN_MAIL) + .withWeapon(Weapon.SWORD) + .withHairType(HairType.LONG_CURLY) + .withHairColor(HairColor.BLOND) + .build(); + + assertNotNull(hero); + assertNotNull(hero.toString()); + assertEquals(Profession.WARRIOR, hero.getProfession()); + assertEquals(heroName, hero.getName()); + assertEquals(Armor.CHAIN_MAIL, hero.getArmor()); + assertEquals(Weapon.SWORD, hero.getWeapon()); + assertEquals(HairType.LONG_CURLY, hero.getHairType()); + assertEquals(HairColor.BLOND, hero.getHairColor()); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java new file mode 100644 index 0000000000..d02109d37d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.business.delegate; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Business Delegate example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java new file mode 100644 index 0000000000..48d576319a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/business-delegate/src/test/java/com/iluwatar/business/delegate/BusinessDelegateTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.business.delegate; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.Before; +import org.junit.Test; + +/** + * The Business Delegate pattern adds an abstraction layer between the presentation and business + * tiers. By using the pattern we gain loose coupling between the tiers. The Business Delegate + * encapsulates knowledge about how to locate, connect to, and interact with the business objects + * that make up the application. + * + *

Some of the services the Business Delegate uses are instantiated directly, and some can be + * retrieved through service lookups. The Business Delegate itself may contain business logic too + * potentially tying together multiple service calls, exception handling, retrying etc. + */ +public class BusinessDelegateTest { + + private EjbService ejbService; + + private JmsService jmsService; + + private BusinessLookup businessLookup; + + private BusinessDelegate businessDelegate; + + /** + * This method sets up the instance variables of this test class. It is executed before the + * execution of every test. + */ + @Before + public void setup() { + ejbService = spy(new EjbService()); + jmsService = spy(new JmsService()); + + businessLookup = spy(new BusinessLookup()); + businessLookup.setEjbService(ejbService); + businessLookup.setJmsService(jmsService); + + businessDelegate = spy(new BusinessDelegate()); + businessDelegate.setLookupService(businessLookup); + } + + /** + * In this example the client ({@link Client}) utilizes a business delegate ( + * {@link BusinessDelegate}) to execute a task. The Business Delegate then selects the appropriate + * service and makes the service call. + */ + @Test + public void testBusinessDelegate() { + + // setup a client object + Client client = new Client(businessDelegate); + + // set the service type + businessDelegate.setServiceType(ServiceType.EJB); + + // action + client.doTask(); + + // verifying that the businessDelegate was used by client during doTask() method. + verify(businessDelegate).doTask(); + verify(ejbService).doProcessing(); + + // set the service type + businessDelegate.setServiceType(ServiceType.JMS); + + // action + client.doTask(); + + // verifying that the businessDelegate was used by client during doTask() method. + verify(businessDelegate, times(2)).doTask(); + verify(jmsService).doProcessing(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/AppTest.java new file mode 100644 index 0000000000..3ac5130335 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.caching; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Caching example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/CachingTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/CachingTest.java new file mode 100644 index 0000000000..4d8dea7a48 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/caching/src/test/java/com/iluwatar/caching/CachingTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.caching; + +import org.junit.Before; +import org.junit.Test; + +/** + * + * Application test + * + */ +public class CachingTest { + App app; + + /** + * Setup of application test includes: initializing DB connection and cache size/capacity. + */ + @Before + public void setUp() { + AppManager.initDb(false); // VirtualDB (instead of MongoDB) was used in running the JUnit tests + // to avoid Maven compilation errors. Set flag to true to run the + // tests with MongoDB (provided that MongoDB is installed and socket + // connection is open). + AppManager.initCacheCapacity(3); + app = new App(); + } + + @Test + public void testReadAndWriteThroughStrategy() { + app.useReadAndWriteThroughStrategy(); + } + + @Test + public void testReadThroughAndWriteAroundStrategy() { + app.useReadThroughAndWriteAroundStrategy(); + } + + @Test + public void testReadThroughAndWriteBehindStrategy() { + app.useReadThroughAndWriteBehindStrategy(); + } + + @Test + public void testCacheAsideStrategy() { + app.useCacheAsideStategy(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/AppTest.java new file mode 100644 index 0000000000..9e3355f472 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.callback; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Callback example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/CallbackTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/CallbackTest.java new file mode 100644 index 0000000000..d6f804f450 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/callback/src/test/java/com/iluwatar/callback/CallbackTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.callback; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Add a field as a counter. Every time the callback method is called increment this field. Unit + * test checks that the field is being incremented. + * + * Could be done with mock objects as well where the call method call is verified. + */ +public class CallbackTest { + + private Integer callingCount = 0; + + @Test + public void test() { + Callback callback = new Callback() { + @Override + public void call() { + callingCount++; + } + }; + + Task task = new SimpleTask(); + + assertEquals("Initial calling count of 0", new Integer(0), callingCount); + + task.executeWith(callback); + + assertEquals("Callback called once", new Integer(1), callingCount); + + task.executeWith(callback); + + assertEquals("Callback called twice", new Integer(2), callingCount); + + } + + @Test + public void testWithLambdasExample() { + Callback callback = () -> callingCount++; + + Task task = new SimpleTask(); + + assertEquals("Initial calling count of 0", new Integer(0), callingCount); + + task.executeWith(callback); + + assertEquals("Callback called once", new Integer(1), callingCount); + + task.executeWith(callback); + + assertEquals("Callback called twice", new Integer(2), callingCount); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/AppTest.java new file mode 100644 index 0000000000..2a3b6b1970 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.chain; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java new file mode 100644 index 0000000000..208e6ecb62 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/chain/src/test/java/com/iluwatar/chain/OrcKingTest.java @@ -0,0 +1,59 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.chain; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/6/15 - 9:29 PM + * + * @author Jeroen Meulemeester + */ +public class OrcKingTest { + + /** + * All possible requests + */ + private static final Request[] REQUESTS = new Request[]{ + new Request(RequestType.DEFEND_CASTLE, "Don't let the barbarians enter my castle!!"), + new Request(RequestType.TORTURE_PRISONER, "Don't just stand there, tickle him!"), + new Request(RequestType.COLLECT_TAX, "Don't steal, the King hates competition ..."), + }; + + @Test + public void testMakeRequest() throws Exception { + final OrcKing king = new OrcKing(); + + for (final Request request : REQUESTS) { + king.makeRequest(request); + assertTrue( + "Expected all requests from King to be handled, but [" + request + "] was not!", + request.isHandled() + ); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/AppTest.java new file mode 100644 index 0000000000..5b4b742d8e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.command; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Command example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/CommandTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/CommandTest.java new file mode 100644 index 0000000000..9b8436a77c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/command/src/test/java/com/iluwatar/command/CommandTest.java @@ -0,0 +1,93 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.command; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * The Command pattern is a behavioral design pattern in which an object is used to encapsulate all + * information needed to perform an action or trigger an event at a later time. This information + * includes the method name, the object that owns the method and values for the method parameters. + * + *

Four terms always associated with the command pattern are command, receiver, invoker and + * client. A command object (spell) knows about the receiver (target) and invokes a method of + * the receiver.Values for parameters of the receiver method are stored in the command. The receiver + * then does the work. An invoker object (wizard) knows how to execute a command, and optionally + * does bookkeeping about the command execution. The invoker does not know anything about a + * concrete command, it knows only about command interface. Both an invoker object and several + * command objects are held by a client object (app). The client decides which commands to execute + * at which points. To execute a command, it passes the command object to the invoker object. + */ +public class CommandTest { + + private static final String GOBLIN = "Goblin"; + + /** + * This test verifies that when the wizard casts spells on the goblin. The wizard keeps track of + * the previous spells cast, so it is easy to undo them. In addition, it also verifies that the + * wizard keeps track of the spells undone, so they can be redone. + */ + @Test + public void testCommand() { + + Wizard wizard = new Wizard(); + Goblin goblin = new Goblin(); + + wizard.castSpell(new ShrinkSpell(), goblin); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.castSpell(new InvisibilitySpell(), goblin); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); + + wizard.undoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.undoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.NORMAL, Visibility.VISIBLE); + + wizard.redoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.VISIBLE); + + wizard.redoLastSpell(); + verifyGoblin(goblin, GOBLIN, Size.SMALL, Visibility.INVISIBLE); + } + + /** + * This method asserts that the passed goblin object has the name as expectedName, size as + * expectedSize and visibility as expectedVisibility. + * + * @param goblin a goblin object whose state is to be verified against other parameters + * @param expectedName expectedName of the goblin + * @param expectedSize expected size of the goblin + * @param expectedVisibility expected visibility of the goblin + */ + private void verifyGoblin(Goblin goblin, String expectedName, Size expectedSize, + Visibility expectedVisibility) { + assertEquals("Goblin's name must be same as expectedName", expectedName, goblin.toString()); + assertEquals("Goblin's size must be same as expectedSize", expectedSize, goblin.getSize()); + assertEquals("Goblin's visibility must be same as expectedVisibility", expectedVisibility, + goblin.getVisibility()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/AppTest.java new file mode 100644 index 0000000000..0862d5c20a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.composite; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/MessengerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/MessengerTest.java new file mode 100644 index 0000000000..3746b236ad --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/composite/src/test/java/com/iluwatar/composite/MessengerTest.java @@ -0,0 +1,112 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.composite; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/11/15 - 8:12 PM + * + * @author Jeroen Meulemeester + */ +public class MessengerTest { + + /** + * The buffer used to capture every write to {@link System#out} + */ + private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream(); + + /** + * Keep the original std-out so it can be restored after the test + */ + private final PrintStream realStdOut = System.out; + + /** + * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test + */ + @Before + public void setUp() { + this.stdOutBuffer = new ByteArrayOutputStream(); + System.setOut(new PrintStream(stdOutBuffer)); + } + + /** + * Removed the mocked std-out {@link PrintStream} again from the {@link System} class + */ + @After + public void tearDown() { + System.setOut(realStdOut); + } + + /** + * Test the message from the orcs + */ + @Test + public void testMessageFromOrcs() { + final Messenger messenger = new Messenger(); + testMessage( + messenger.messageFromOrcs(), + "Where there is a whip there is a way." + ); + } + + /** + * Test the message from the elves + */ + @Test + public void testMessageFromElves() { + final Messenger messenger = new Messenger(); + testMessage( + messenger.messageFromElves(), + "Much wind pours from your mouth." + ); + } + + /** + * Test if the given composed message matches the expected message + * + * @param composedMessage The composed message, received from the messenger + * @param message The expected message + */ + private void testMessage(final LetterComposite composedMessage, final String message) { + // Test is the composed message has the correct number of words + final String[] words = message.split(" "); + assertNotNull(composedMessage); + assertEquals(words.length, composedMessage.count()); + + // Print the message to the mocked stdOut ... + composedMessage.print(); + + // ... and verify if the message matches with the expected one + assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/AppTest.java new file mode 100644 index 0000000000..091fbe2cac --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.converter; + +import org.junit.Test; + +/** + * App running test + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/ConverterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/ConverterTest.java new file mode 100644 index 0000000000..9fc2e2a0c2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/converter/src/test/java/com/iluwatar/converter/ConverterTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.converter; + +import com.google.common.collect.Lists; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static junit.framework.TestCase.assertEquals; + +/** + * Tests for {@link Converter} + */ +public class ConverterTest { + + private UserConverter userConverter = new UserConverter(); + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test public void testConversionsStartingFromDomain() { + User u1 = new User("Tom", "Hanks", true, "tom@hanks.com"); + User u2 = userConverter.convertFromDto(userConverter.convertFromEntity(u1)); + assertEquals(u1, u2); + } + + /** + * Tests whether a converter created of opposite functions holds equality as a bijection. + */ + @Test public void testConversionsStartingFromDto() { + UserDto u1 = new UserDto("Tom", "Hanks", true, "tom@hanks.com"); + UserDto u2 = userConverter.convertFromEntity(userConverter.convertFromDto(u1)); + assertEquals(u1, u2); + } + + /** + * Tests the custom users converter. Thanks to Java8 lambdas, converter can be easily and + * cleanly instantiated allowing various different conversion strategies to be implemented. + */ + @Test public void testCustomConverter() { + Converter converter = new Converter<>( + userDto -> new User(userDto.getFirstName(), userDto.getLastName(), userDto.isActive(), + String.valueOf(new Random().nextInt())), + user -> new UserDto(user.getFirstName(), user.getLastName(), user.isActive(), + user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); + User u1 = new User("John", "Doe", false, "12324"); + UserDto userDto = converter.convertFromEntity(u1); + assertEquals(userDto.getEmail(), "johndoe@whatever.com"); + } + + /** + * Test whether converting a collection of Users to DTO Users and then converting them back to domain + * users returns an equal collection. + */ + @Test public void testCollectionConversion() { + ArrayList users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), + new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); + List fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); + assertEquals(fromDtos, users); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java new file mode 100644 index 0000000000..dd10f658d0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java @@ -0,0 +1,120 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.cqrs; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.iluwatar.cqrs.commandes.CommandServiceImpl; +import com.iluwatar.cqrs.commandes.ICommandService; +import com.iluwatar.cqrs.dto.Author; +import com.iluwatar.cqrs.dto.Book; +import com.iluwatar.cqrs.queries.IQueryService; +import com.iluwatar.cqrs.queries.QueryServiceImpl; + +/** + * Integration test of IQueryService and ICommandService with h2 data + * + */ +public class IntegrationTest { + + private static IQueryService queryService; + private static ICommandService commandService; + + @BeforeClass + public static void initialize() { + commandService = new CommandServiceImpl(); + queryService = new QueryServiceImpl(); + } + + @BeforeClass + public static void populateDatabase() { + // create first author1 + commandService.authorCreated("username1", "name1", "email1"); + + // create author1 and update all its data + commandService.authorCreated("username2", "name2", "email2"); + commandService.authorEmailUpdated("username2", "new_email2"); + commandService.authorNameUpdated("username2", "new_name2"); + commandService.authorUsernameUpdated("username2", "new_username2"); + + // add book1 to author1 + commandService.bookAddedToAuthor("title1", 10, "username1"); + + // add book2 to author1 and update all its data + commandService.bookAddedToAuthor("title2", 20, "username1"); + commandService.bookPriceUpdated("title2", 30); + commandService.bookTitleUpdated("title2", "new_title2"); + + } + + @Test + public void testGetAuthorByUsername() { + Author author = queryService.getAuthorByUsername("username1"); + assertEquals("username1", author.getUsername()); + assertEquals("name1", author.getName()); + assertEquals("email1", author.getEmail()); + } + + @Test + public void testGetUpdatedAuthorByUsername() { + Author author = queryService.getAuthorByUsername("new_username2"); + Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2"); + assertEquals(expectedAuthor, author); + + } + + @Test + public void testGetBook() { + Book book = queryService.getBook("title1"); + assertEquals("title1", book.getTitle()); + assertEquals(10, book.getPrice(), 0); + } + + @Test + public void testGetAuthorBooks() { + List books = queryService.getAuthorBooks("username1"); + assertTrue(books.size() == 2); + assertTrue(books.contains(new Book("title1", 10))); + assertTrue(books.contains(new Book("new_title2", 30))); + } + + @Test + public void testGetAuthorBooksCount() { + BigInteger bookCount = queryService.getAuthorBooksCount("username1"); + assertEquals(new BigInteger("2"), bookCount); + } + + @Test + public void testGetAuthorsCount() { + BigInteger authorCount = queryService.getAuthorsCount(); + assertEquals(new BigInteger("2"), authorCount); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/AppTest.java new file mode 100644 index 0000000000..73534eb022 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import org.junit.Test; + +/** + * Tests that DAO example runs without errors. + */ +public class AppTest { + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/CustomerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/CustomerTest.java new file mode 100644 index 0000000000..8122c369fa --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/CustomerTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import org.junit.Before; +import org.junit.Test; + +/** + * Tests {@link Customer}. + */ +public class CustomerTest { + + private Customer customer; + private static final int ID = 1; + private static final String FIRSTNAME = "Winston"; + private static final String LASTNAME = "Churchill"; + + @Before + public void setUp() { + customer = new Customer(ID, FIRSTNAME, LASTNAME); + } + + @Test + public void getAndSetId() { + final int newId = 2; + customer.setId(newId); + assertEquals(newId, customer.getId()); + } + + @Test + public void getAndSetFirstname() { + final String newFirstname = "Bill"; + customer.setFirstName(newFirstname); + assertEquals(newFirstname, customer.getFirstName()); + } + + @Test + public void getAndSetLastname() { + final String newLastname = "Clinton"; + customer.setLastName(newLastname); + assertEquals(newLastname, customer.getLastName()); + } + + @Test + public void notEqualWithDifferentId() { + final int newId = 2; + final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME); + assertNotEquals(customer, otherCustomer); + assertNotEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + public void equalsWithSameObjectValues() { + final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME); + assertEquals(customer, otherCustomer); + assertEquals(customer.hashCode(), otherCustomer.hashCode()); + } + + @Test + public void equalsWithSameObjects() { + assertEquals(customer, customer); + assertEquals(customer.hashCode(), customer.hashCode()); + } + + @Test + public void testToString() { + final StringBuffer buffer = new StringBuffer(); + buffer.append("Customer{id=") + .append("" + customer.getId()) + .append(", firstName='") + .append(customer.getFirstName()) + .append("\', lastName='") + .append(customer.getLastName() + "\'}"); + assertEquals(buffer.toString(), customer.toString()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java new file mode 100644 index 0000000000..213aef2067 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java @@ -0,0 +1,269 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.stream.Stream; + +import javax.sql.DataSource; + +import org.h2.jdbcx.JdbcDataSource; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mockito; + +import de.bechte.junit.runners.context.HierarchicalContextRunner; + +/** + * Tests {@link DbCustomerDao}. + */ +@RunWith(HierarchicalContextRunner.class) +public class DbCustomerDaoTest { + + private static final String DB_URL = "jdbc:h2:~/dao"; + private DbCustomerDao dao; + private Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); + + /** + * Creates customers schema. + * @throws SQLException if there is any error while creating schema. + */ + @Before + public void createSchema() throws SQLException { + try (Connection connection = DriverManager.getConnection(DB_URL); + Statement statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.CREATE_SCHEMA_SQL); + } + } + + /** + * Represents the scenario where DB connectivity is present. + */ + public class ConnectionSuccess { + + /** + * Setup for connection success scenario. + * @throws Exception if any error occurs. + */ + @Before + public void setUp() throws Exception { + JdbcDataSource dataSource = new JdbcDataSource(); + dataSource.setURL(DB_URL); + dao = new DbCustomerDao(dataSource); + boolean result = dao.add(existingCustomer); + assertTrue(result); + } + + /** + * Represents the scenario when DAO operations are being performed on a non existing customer. + */ + public class NonExistingCustomer { + + @Test + public void addingShouldResultInSuccess() throws Exception { + try (Stream allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final int nonExistingId = getNonExistingCustomerId(); + final String newFirstname = "Douglas"; + final String newLastname = "MacArthur"; + final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); + boolean result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + public void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents a scenario where DAO operations are being performed on an already existing + * customer. + * + */ + public class ExistingCustomer { + + @Test + public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + Customer existingCustomer = new Customer(1, "Freddy", "Krueger"); + + boolean result = dao.add(existingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + boolean result = dao.delete(existingCustomer); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(existingCustomer.getId()).isPresent()); + } + + @Test + public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname); + boolean result = dao.update(customer); + + assertTrue(result); + + final Customer cust = dao.getById(existingCustomer.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + } + } + + /** + * Represents a scenario where DB connectivity is not present due to network issue, or + * DB service unavailable. + * + */ + public class ConnectivityIssue { + + private static final String EXCEPTION_CAUSE = "Connection not available"; + @Rule public ExpectedException exception = ExpectedException.none(); + + /** + * setup a connection failure scenario. + * @throws SQLException if any error occurs. + */ + @Before + public void setUp() throws SQLException { + dao = new DbCustomerDao(mockedDatasource()); + exception.expect(Exception.class); + exception.expectMessage(EXCEPTION_CAUSE); + } + + private DataSource mockedDatasource() throws SQLException { + DataSource mockedDataSource = mock(DataSource.class); + Connection mockedConnection = mock(Connection.class); + SQLException exception = new SQLException(EXCEPTION_CAUSE); + doThrow(exception).when(mockedConnection).prepareStatement(Mockito.anyString()); + doReturn(mockedConnection).when(mockedDataSource).getConnection(); + return mockedDataSource; + } + + @Test + public void addingACustomerFailsWithExceptionAsFeedbackToClient() throws Exception { + dao.add(new Customer(2, "Bernard", "Montgomery")); + } + + @Test + public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() throws Exception { + dao.delete(existingCustomer); + } + + @Test + public void updatingACustomerFailsWithFeedbackToTheClient() throws Exception { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + + dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname)); + } + + @Test + public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() throws Exception { + dao.getById(existingCustomer.getId()); + } + + @Test + public void retrievingAllCustomersFailsWithExceptionAsFeedbackToClient() throws Exception { + dao.getAll(); + } + + } + + /** + * Delete customer schema for fresh setup per test. + * @throws SQLException if any error occurs. + */ + @After + public void deleteSchema() throws SQLException { + try (Connection connection = DriverManager.getConnection(DB_URL); + Statement statement = connection.createStatement()) { + statement.execute(CustomerSchemaSql.DELETE_SCHEMA_SQL); + } + } + + private void assertCustomerCountIs(int count) throws Exception { + try (Stream allCustomers = dao.getAll()) { + assertTrue(allCustomers.count() == count); + } + } + + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java new file mode 100644 index 0000000000..2532b2fad4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java @@ -0,0 +1,164 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import de.bechte.junit.runners.context.HierarchicalContextRunner; + +/** + * Tests {@link InMemoryCustomerDao}. + */ +@RunWith(HierarchicalContextRunner.class) +public class InMemoryCustomerDaoTest { + + private InMemoryCustomerDao dao; + private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger"); + + @Before + public void setUp() { + dao = new InMemoryCustomerDao(); + assertTrue(dao.add(CUSTOMER)); + } + + /** + * Represents the scenario when the DAO operations are being performed on a non existent + * customer. + */ + public class NonExistingCustomer { + + @Test + public void addingShouldResultInSuccess() throws Exception { + try (Stream allCustomers = dao.getAll()) { + assumeTrue(allCustomers.count() == 1); + } + + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.add(nonExistingCustomer); + assertTrue(result); + + assertCustomerCountIs(2); + assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get()); + } + + @Test + public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund"); + boolean result = dao.delete(nonExistingCustomer); + + assertFalse(result); + assertCustomerCountIs(1); + } + + @Test + public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception { + final int nonExistingId = getNonExistingCustomerId(); + final String newFirstname = "Douglas"; + final String newLastname = "MacArthur"; + final Customer customer = new Customer(nonExistingId, newFirstname, newLastname); + boolean result = dao.update(customer); + + assertFalse(result); + assertFalse(dao.getById(nonExistingId).isPresent()); + } + + @Test + public void retrieveShouldReturnNoCustomer() throws Exception { + assertFalse(dao.getById(getNonExistingCustomerId()).isPresent()); + } + } + + /** + * Represents the scenario when the DAO operations are being performed on an already existing + * customer. + */ + public class ExistingCustomer { + + @Test + public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception { + boolean result = dao.add(CUSTOMER); + + assertFalse(result); + assertCustomerCountIs(1); + assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get()); + } + + @Test + public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception { + boolean result = dao.delete(CUSTOMER); + + assertTrue(result); + assertCustomerCountIs(0); + assertFalse(dao.getById(CUSTOMER.getId()).isPresent()); + } + + @Test + public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception { + final String newFirstname = "Bernard"; + final String newLastname = "Montgomery"; + final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname); + boolean result = dao.update(customer); + + assertTrue(result); + + final Customer cust = dao.getById(CUSTOMER.getId()).get(); + assertEquals(newFirstname, cust.getFirstName()); + assertEquals(newLastname, cust.getLastName()); + } + + @Test + public void retriveShouldReturnTheCustomer() { + Optional optionalCustomer = dao.getById(CUSTOMER.getId()); + + assertTrue(optionalCustomer.isPresent()); + assertEquals(CUSTOMER, optionalCustomer.get()); + } + } + + /** + * An arbitrary number which does not correspond to an active Customer id. + * + * @return an int of a customer id which doesn't exist + */ + private int getNonExistingCustomerId() { + return 999; + } + + private void assertCustomerCountIs(int count) throws Exception { + try (Stream allCustomers = dao.getAll()) { + assertTrue(allCustomers.count() == count); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java new file mode 100644 index 0000000000..f986e1681f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/DataBusTest.java @@ -0,0 +1,74 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.never; + +/** + * Tests for {@link DataBus}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class DataBusTest { + + @Mock + private Member member; + + @Mock + private DataType event; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void publishedEventIsReceivedBySubscribedMember() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + //when + dataBus.publish(event); + //then + then(member).should().accept(event); + } + + @Test + public void publishedEventIsNotReceivedByMemberAfterUnsubscribing() { + //given + final DataBus dataBus = DataBus.getInstance(); + dataBus.subscribe(member); + dataBus.unsubscribe(member); + //when + dataBus.publish(event); + //then + then(member).should(never()).accept(event); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java new file mode 100644 index 0000000000..35deeb5fbc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/MessageCollectorMemberTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus.members; + +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDateTime; + +/** + * Tests for {@link MessageCollectorMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class MessageCollectorMemberTest { + + @Test + public void collectMessageFromMessageData() { + //given + final String message = "message"; + final MessageData messageData = new MessageData(message); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(messageData); + //then + Assert.assertTrue(collector.getMessages().contains(message)); + } + + @Test + public void collectIgnoresMessageFromOtherDataTypes() { + //given + final StartingData startingData = new StartingData(LocalDateTime.now()); + final MessageCollectorMember collector = new MessageCollectorMember("collector"); + //when + collector.accept(startingData); + //then + Assert.assertEquals(0, collector.getMessages().size()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java new file mode 100644 index 0000000000..d5afbd1329 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-bus/src/test/java/com/iluwatar/databus/members/StatusMemberTest.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.databus.members; + +import com.iluwatar.databus.DataBus; +import com.iluwatar.databus.data.MessageData; +import com.iluwatar.databus.data.StartingData; +import com.iluwatar.databus.data.StoppingData; +import org.junit.Assert; +import org.junit.Test; + +import java.time.LocalDateTime; +import java.time.Month; + +/** + * Tests for {@link StatusMember}. + * + * @author Paul Campbell (pcampbell@kemitix.net) + */ +public class StatusMemberTest { + + @Test + public void statusRecordsTheStartTime() { + //given + final LocalDateTime startTime = LocalDateTime.of(2017, Month.APRIL, 1, 19, 9); + final StartingData startingData = new StartingData(startTime); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(startingData); + //then + Assert.assertEquals(startTime, statusMember.getStarted()); + } + + @Test + public void statusRecordsTheStopTime() { + //given + final LocalDateTime stop = LocalDateTime.of(2017, Month.APRIL, 1, 19, 12); + final StoppingData stoppingData = new StoppingData(stop); + stoppingData.setDataBus(DataBus.getInstance()); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(stoppingData); + //then + Assert.assertEquals(stop, statusMember.getStopped()); + } + + @Test + public void statusIgnoresMessageData() { + //given + final MessageData messageData = new MessageData("message"); + final StatusMember statusMember = new StatusMember(1); + //when + statusMember.accept(messageData); + //then + Assert.assertNull(statusMember.getStarted()); + Assert.assertNull(statusMember.getStopped()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java new file mode 100644 index 0000000000..f2858100ef --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/AppTest.java @@ -0,0 +1,34 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import com.iluwatar.datamapper.App; +import org.junit.Test; + +/** + * Tests that Data-Mapper example runs without errors. + */ +public final class AppTest { + + @Test + public void test() { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java new file mode 100644 index 0000000000..17f4d39224 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/DataMapperTest.java @@ -0,0 +1,73 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.iluwatar.datamapper.Student; +import com.iluwatar.datamapper.StudentDataMapper; +import com.iluwatar.datamapper.StudentDataMapperImpl; + +/** + * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the + * database. Its responsibility is to transfer data between the two and also to isolate them from + * each other. With Data Mapper the in-memory objects needn't know even that there's a database + * present; they need no SQL interface code, and certainly no knowledge of the database schema. (The + * database schema is always ignorant of the objects that use it.) Since it's a form of Mapper , + * Data Mapper itself is even unknown to the domain layer. + *

+ */ +public class DataMapperTest { + + /** + * This test verify that first data mapper is able to perform all CRUD operations on Student + */ + @Test + public void testFirstDataMapper() { + + /* Create new data mapper of first type */ + final StudentDataMapper mapper = new StudentDataMapperImpl(); + + /* Create new student */ + Student student = new Student(1, "Adam", 'A'); + + /* Add student in respectibe db */ + mapper.insert(student); + + /* Check if student is added in db */ + assertEquals(student.getStudentId(), mapper.find(student.getStudentId()).get().getStudentId()); + + /* Update existing student object */ + student = new Student(student.getStudentId(), "AdamUpdated", 'A'); + + /* Update student in respectibe db */ + mapper.update(student); + + /* Check if student is updated in db */ + assertEquals(mapper.find(student.getStudentId()).get().getName(), "AdamUpdated"); + + /* Delete student in db */ + mapper.delete(student); + + /* Result should be false */ + assertEquals(false, mapper.find(student.getStudentId()).isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java new file mode 100644 index 0000000000..ec35b21de8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-mapper/src/test/java/com/iluwatar/datamapper/StudentTest.java @@ -0,0 +1,55 @@ +/** + * The MIT License Copyright (c) 2016 Amit Dixit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.datamapper; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Tests {@link Student}. + */ +public final class StudentTest { + + @Test + /** + * This API tests the equality behaviour of Student object + * Object Equality should work as per logic defined in equals method + * + * @throws Exception if any execution error during test + */ + public void testEquality() throws Exception { + + /* Create some students */ + final Student firstStudent = new Student(1, "Adam", 'A'); + final Student secondStudent = new Student(2, "Donald", 'B'); + final Student secondSameStudent = new Student(2, "Donald", 'B'); + final Student firstSameStudent = firstStudent; + + /* Check equals functionality: should return 'true' */ + assertTrue(firstStudent.equals(firstSameStudent)); + + /* Check equals functionality: should return 'false' */ + assertFalse(firstStudent.equals(secondStudent)); + + /* Check equals functionality: should return 'true' */ + assertTrue(secondStudent.equals(secondSameStudent)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java new file mode 100644 index 0000000000..adfe66b7db --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java @@ -0,0 +1,81 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.datatransfer; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * tests {@link CustomerResource}. + */ +public class CustomerResourceTest { + @Test + public void shouldGetAllCustomers() { + CustomerDto customer = new CustomerDto("1", "Melody", "Yates"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + List allCustomers = customerResource.getAllCustomers(); + + assertEquals(allCustomers.size(), 1); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Melody"); + assertEquals(allCustomers.get(0).getLastName(), "Yates"); + } + + @Test + public void shouldSaveCustomer() { + CustomerDto customer = new CustomerDto("1", "Rita", "Reynolds"); + CustomerResource customerResource = new CustomerResource(new ArrayList<>()); + + customerResource.save(customer); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Rita"); + assertEquals(allCustomers.get(0).getLastName(), "Reynolds"); + } + + @Test + public void shouldDeleteCustomer() { + CustomerDto customer = new CustomerDto("1", "Terry", "Nguyen"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + customerResource.delete(customer.getId()); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.size(), 0); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/AppTest.java new file mode 100644 index 0000000000..466fa15524 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java new file mode 100644 index 0000000000..fb86615c68 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +/** + * Tests for {@link ClubbedTroll} + */ +public class ClubbedTrollTest { + + @Test + public void testClubbedTroll() throws Exception { + // Create a normal troll first, but make sure we can spy on it later on. + final Troll simpleTroll = spy(new SimpleTroll()); + + // Now we want to decorate the troll to make it stronger ... + final Troll clubbed = new ClubbedTroll(simpleTroll); + assertEquals(20, clubbed.getAttackPower()); + verify(simpleTroll, times(1)).getAttackPower(); + + // Check if the clubbed troll actions are delegated to the decorated troll + clubbed.attack(); + verify(simpleTroll, times(1)).attack(); + + clubbed.fleeBattle(); + verify(simpleTroll, times(1)).fleeBattle(); + verifyNoMoreInteractions(simpleTroll); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java new file mode 100644 index 0000000000..5c6b2bbe79 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/decorator/src/test/java/com/iluwatar/decorator/SimpleTrollTest.java @@ -0,0 +1,91 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.decorator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Tests for {@link SimpleTroll} + */ +public class SimpleTrollTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(SimpleTroll.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testTrollActions() throws Exception { + final SimpleTroll troll = new SimpleTroll(); + assertEquals(10, troll.getAttackPower()); + + troll.attack(); + assertEquals("The troll tries to grab you!", appender.getLastMessage()); + + troll.fleeBattle(); + assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage()); + + assertEquals(2, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java new file mode 100644 index 0000000000..434d94baa4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.delegation.simple; + +import org.junit.Test; +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java new file mode 100644 index 0000000000..fd99a30dd3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/delegation/src/test/java/com/iluwatar/delegation/simple/DelegateTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.delegation.simple; + +import static org.junit.Assert.assertEquals; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import com.iluwatar.delegation.simple.printers.CanonPrinter; +import com.iluwatar.delegation.simple.printers.EpsonPrinter; +import com.iluwatar.delegation.simple.printers.HpPrinter; +import java.util.LinkedList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * Test for Delegation Pattern + */ +public class DelegateTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final String MESSAGE = "Test Message Printed"; + + @Test + public void testCanonPrinter() throws Exception { + PrinterController printerController = new PrinterController(new CanonPrinter()); + printerController.print(MESSAGE); + + assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage()); + } + + @Test + public void testHpPrinter() throws Exception { + PrinterController printerController = new PrinterController(new HpPrinter()); + printerController.print(MESSAGE); + + assertEquals("HP Printer : Test Message Printed", appender.getLastMessage()); + } + + @Test + public void testEpsonPrinter() throws Exception { + PrinterController printerController = new PrinterController(new EpsonPrinter()); + printerController.print(MESSAGE); + + assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage()); + } + + /** + * Logging Appender + */ + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java new file mode 100644 index 0000000000..b2a701d0b0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedSorceressTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 28/04/17 - 7:40 AM + * + * @author Stanislav Kapinus + */ + +public class AdvancedSorceressTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedSorceress} smokes whatever instance of {@link Tobacco} is passed to her + * through the setter's parameter + */ + @Test + public void testSmokeEveryThing() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final AdvancedSorceress advancedSorceress = new AdvancedSorceress(); + advancedSorceress.setTobacco(tobacco); + advancedSorceress.smoke(); + // Verify if the sorceress is smoking the correct tobacco ... + assertEquals("AdvancedSorceress smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java new file mode 100644 index 0000000000..2d68579126 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AdvancedWizardTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/10/15 - 8:40 PM + * + * @author Jeroen Meulemeester + */ +public class AdvancedWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link AdvancedWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the constructor parameter + */ + @Test + public void testSmokeEveryThing() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final AdvancedWizard advancedWizard = new AdvancedWizard(tobacco); + advancedWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java new file mode 100644 index 0000000000..41f04c9b3c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java new file mode 100644 index 0000000000..e58a9f3b54 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/GuiceWizardTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/10/15 - 8:57 PM + * + * @author Jeroen Meulemeester + */ +public class GuiceWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the constructor parameter + */ + @Test + public void testSmokeEveryThingThroughConstructor() throws Exception { + + final Tobacco[] tobaccos = { + new OldTobyTobacco(), new RivendellTobacco(), new SecondBreakfastTobacco() + }; + + for (final Tobacco tobacco : tobaccos) { + final GuiceWizard guiceWizard = new GuiceWizard(tobacco); + guiceWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage()); + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + } + + /** + * Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him + * through the Guice google inject framework + */ + @Test + public void testSmokeEveryThingThroughInjectionFramework() throws Exception { + + @SuppressWarnings("unchecked") + final Class[] tobaccos = new Class[]{ + OldTobyTobacco.class, RivendellTobacco.class, SecondBreakfastTobacco.class + }; + + for (final Class tobaccoClass : tobaccos) { + // Configure the tobacco in the injection framework ... + final Injector injector = Guice.createInjector(new AbstractModule() { + @Override + protected void configure() { + bind(Tobacco.class).to(tobaccoClass); + } + }); + + // ... and create a new wizard with it + final GuiceWizard guiceWizard = injector.getInstance(GuiceWizard.class); + guiceWizard.smoke(); + + // Verify if the wizard is smoking the correct tobacco ... + assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage()); + } + + // ... and nothing else is happening. + assertEquals(tobaccos.length, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java new file mode 100644 index 0000000000..4ce69e0950 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/dependency-injection/src/test/java/com/iluwatar/dependency/injection/SimpleWizardTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.dependency.injection; + +import com.iluwatar.dependency.injection.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/10/15 - 8:26 PM + * + * @author Jeroen Meulemeester + */ +public class SimpleWizardTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Tobacco.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test if the {@link SimpleWizard} does the only thing it can do: Smoke it's {@link + * OldTobyTobacco} + */ + @Test + public void testSmoke() { + final SimpleWizard simpleWizard = new SimpleWizard(); + simpleWizard.smoke(); + assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java new file mode 100644 index 0000000000..672d83f0ac --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doublechecked.locking; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java new file mode 100644 index 0000000000..0b1487e112 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-checked-locking/src/test/java/com/iluwatar/doublechecked/locking/InventoryTest.java @@ -0,0 +1,127 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doublechecked.locking; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/10/15 - 9:34 PM + * + * @author Jeroen Meulemeester + */ +public class InventoryTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Inventory.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * The number of threads used to stress test the locking of the {@link Inventory#addItem(Item)} + * method + */ + private static final int THREAD_COUNT = 8; + + /** + * The maximum number of {@link Item}s allowed in the {@link Inventory} + */ + private static final int INVENTORY_SIZE = 1000; + + /** + * Concurrently add multiple items to the inventory, and check if the items were added in order by + * checking the stdOut for continuous growth of the inventory. When 'items.size()=xx' shows up out + * of order, it means that the locking is not ok, increasing the risk of going over the inventory + * item limit. + */ + @Test(timeout = 10000) + public void testAddItem() throws Exception { + // Create a new inventory with a limit of 1000 items and put some load on the add method + final Inventory inventory = new Inventory(INVENTORY_SIZE); + final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); + for (int i = 0; i < THREAD_COUNT; i++) { + executorService.execute(() -> { + while (inventory.addItem(new Item())) {}; + }); + } + + // Wait until all threads have finished + executorService.shutdown(); + executorService.awaitTermination(5, TimeUnit.SECONDS); + + // Check the number of items in the inventory. It should not have exceeded the allowed maximum + final List items = inventory.getItems(); + assertNotNull(items); + assertEquals(INVENTORY_SIZE, items.size()); + + assertEquals(INVENTORY_SIZE, appender.getLogSize()); + + // ... and check if the inventory size is increasing continuously + for (int i = 0; i < items.size(); i++) { + assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); + } + } + + + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java new file mode 100644 index 0000000000..dce6afd863 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java new file mode 100644 index 0000000000..3dc32905a6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/CollisionTest.java @@ -0,0 +1,111 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import static org.junit.Assert.assertEquals; + +import java.util.Objects; + +/** + * Date: 12/10/15 - 8:37 PM + * Test for Collision + * @param Type of GameObject + * @author Jeroen Meulemeester + */ +public abstract class CollisionTest { + + /** + * Get the tested object + * + * @return The tested object, should never return 'null' + */ + abstract O getTestedObject(); + + /** + * Collide the tested item with the other given item and verify if the damage and fire state is as + * expected + * + * @param other The other object we have to collide with + * @param otherDamaged Indicates if the other object should be damaged after the collision + * @param otherOnFire Indicates if the other object should be burning after the collision + * @param thisDamaged Indicates if the test object should be damaged after the collision + * @param thisOnFire Indicates if the other object should be burning after the collision + * @param description The expected description of the collision + */ + void testCollision(final GameObject other, final boolean otherDamaged, final boolean otherOnFire, + final boolean thisDamaged, final boolean thisOnFire, final String description) { + + Objects.requireNonNull(other); + Objects.requireNonNull(getTestedObject()); + + final O tested = getTestedObject(); + + tested.collision(other); + + testOnFire(other, tested, otherOnFire); + testDamaged(other, tested, otherDamaged); + + testOnFire(tested, other, thisOnFire); + testDamaged(tested, other, thisDamaged); + + } + + /** + * Test if the fire state of the target matches the expected state after colliding with the given + * object + * + * @param target The target object + * @param other The other object + * @param expectTargetOnFire The expected state of fire on the target object + */ + private void testOnFire(final GameObject target, final GameObject other, final boolean expectTargetOnFire) { + final String targetName = target.getClass().getSimpleName(); + final String otherName = other.getClass().getSimpleName(); + + final String errorMessage = expectTargetOnFire + ? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!" + : "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!"; + + assertEquals(errorMessage, expectTargetOnFire, target.isOnFire()); + } + + /** + * Test if the damage state of the target matches the expected state after colliding with the + * given object + * + * @param target The target object + * @param other The other object + * @param expectedDamage The expected state of damage on the target object + */ + private void testDamaged(final GameObject target, final GameObject other, final boolean expectedDamage) { + final String targetName = target.getClass().getSimpleName(); + final String otherName = other.getClass().getSimpleName(); + + final String errorMessage = expectedDamage + ? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!" + : "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!"; + + assertEquals(errorMessage, expectedDamage, target.isDamaged()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java new file mode 100644 index 0000000000..120c9a8832 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/FlamingAsteroidTest.java @@ -0,0 +1,110 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class FlamingAsteroidTest extends CollisionTest { + + @Override + final FlamingAsteroid getTestedObject() { + return new FlamingAsteroid(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final FlamingAsteroid asteroid = new FlamingAsteroid(1, 2, 3, 4); + assertEquals(1, asteroid.getLeft()); + assertEquals(2, asteroid.getTop()); + assertEquals(3, asteroid.getRight()); + assertEquals(4, asteroid.getBottom()); + assertTrue(asteroid.isOnFire()); + assertFalse(asteroid.isDamaged()); + assertEquals("FlamingAsteroid at [1,2,3,4] damaged=false onFire=true", asteroid.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 2, 3, 4), + false, true, + false, true, + "FlamingAsteroid hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, true, + "FlamingAsteroid hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, true, + false, true, + "FlamingAsteroid hits SpaceStationIss. SpaceStationIss is damaged! SpaceStationIss is set on fire!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, true, + false, true, + "FlamingAsteroid hits SpaceStationMir. SpaceStationMir is damaged! SpaceStationMir is set on fire!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java new file mode 100644 index 0000000000..8eed497c0e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/MeteoroidTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class MeteoroidTest extends CollisionTest { + + @Override + final Meteoroid getTestedObject() { + return new Meteoroid(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final Meteoroid meteoroid = new Meteoroid(1, 2, 3, 4); + assertEquals(1, meteoroid.getLeft()); + assertEquals(2, meteoroid.getTop()); + assertEquals(3, meteoroid.getRight()); + assertEquals(4, meteoroid.getBottom()); + assertFalse(meteoroid.isOnFire()); + assertFalse(meteoroid.isDamaged()); + assertEquals("Meteoroid at [1,2,3,4] damaged=false onFire=false", meteoroid.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "Meteoroid hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "Meteoroid hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "Meteoroid hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "Meteoroid hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java new file mode 100644 index 0000000000..1f4e476de1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/RectangleTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Unit test for Rectangle + */ +public class RectangleTest { + + /** + * Test if the values passed through the constructor matches the values fetched from the getters + */ + @Test + public void testConstructor() { + final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + assertEquals(1, rectangle.getLeft()); + assertEquals(2, rectangle.getTop()); + assertEquals(3, rectangle.getRight()); + assertEquals(4, rectangle.getBottom()); + } + + /** + * Test if the values passed through the constructor matches the values in the {@link + * #toString()} + */ + @Test + public void testToString() throws Exception { + final Rectangle rectangle = new Rectangle(1, 2, 3, 4); + assertEquals("[1,2,3,4]", rectangle.toString()); + } + + /** + * Test if the {@link Rectangle} class can detect if it intersects with another rectangle. + */ + @Test + public void testIntersection() { + assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(0, 0, 1, 1))); + assertTrue(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-1, -5, 7, 8))); + assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(2, 2, 3, 3))); + assertFalse(new Rectangle(0, 0, 1, 1).intersectsWith(new Rectangle(-2, -2, -1, -1))); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java new file mode 100644 index 0000000000..8cde65d110 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationIssTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class SpaceStationIssTest extends CollisionTest { + + @Override + final SpaceStationIss getTestedObject() { + return new SpaceStationIss(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final SpaceStationIss iss = new SpaceStationIss(1, 2, 3, 4); + assertEquals(1, iss.getLeft()); + assertEquals(2, iss.getTop()); + assertEquals(3, iss.getRight()); + assertEquals(4, iss.getBottom()); + assertFalse(iss.isOnFire()); + assertFalse(iss.isDamaged()); + assertEquals("SpaceStationIss at [1,2,3,4] damaged=false onFire=false", iss.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "SpaceStationIss hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "SpaceStationIss hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationIss hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationIss hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java new file mode 100644 index 0000000000..3dbab58baa --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/double-dispatch/src/test/java/com/iluwatar/doubledispatch/SpaceStationMirTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.doubledispatch; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +/** + * Date: 12/10/15 - 11:31 PM + * + * @author Jeroen Meulemeester + */ +public class SpaceStationMirTest extends CollisionTest { + + @Override + final SpaceStationMir getTestedObject() { + return new SpaceStationMir(1, 2, 3, 4); + } + + /** + * Test the constructor parameters + */ + @Test + public void testConstructor() { + final SpaceStationMir mir = new SpaceStationMir(1, 2, 3, 4); + assertEquals(1, mir.getLeft()); + assertEquals(2, mir.getTop()); + assertEquals(3, mir.getRight()); + assertEquals(4, mir.getBottom()); + assertFalse(mir.isOnFire()); + assertFalse(mir.isDamaged()); + assertEquals("SpaceStationMir at [1,2,3,4] damaged=false onFire=false", mir.toString()); + } + + /** + * Test what happens we collide with an asteroid + */ + @Test + public void testCollideFlamingAsteroid() { + testCollision( + new FlamingAsteroid(1, 1, 3, 4), + false, true, + false, false, + "SpaceStationMir hits FlamingAsteroid." + ); + } + + /** + * Test what happens we collide with an meteoroid + */ + @Test + public void testCollideMeteoroid() { + testCollision( + new Meteoroid(1, 1, 3, 4), + false, false, + false, false, + "SpaceStationMir hits Meteoroid." + ); + } + + /** + * Test what happens we collide with ISS + */ + @Test + public void testCollideSpaceStationIss() { + testCollision( + new SpaceStationIss(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationMir hits SpaceStationIss. SpaceStationIss is damaged!" + ); + } + + /** + * Test what happens we collide with MIR + */ + @Test + public void testCollideSpaceStationMir() { + testCollision( + new SpaceStationMir(1, 1, 3, 4), + true, false, + false, false, + "SpaceStationMir hits SpaceStationMir. SpaceStationMir is damaged!" + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java new file mode 100644 index 0000000000..39a3c1ab38 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator; + +import org.junit.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java new file mode 100644 index 0000000000..eb7846b9c4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/AggregatorRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertEquals; + +/** + * Test class for AggregatorRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = AggregatorRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class AggregatorRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody("TEST1"); + entry.sendBody("TEST2"); + entry.sendBody("TEST3"); + entry.sendBody("TEST4"); + entry.sendBody("TEST5"); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(2); + endpoint.assertIsSatisfied(); + + String body = (String) endpoint.getReceivedExchanges().get(0).getIn().getBody(); + assertEquals(3, body.split(";").length); + + String body2 = (String) endpoint.getReceivedExchanges().get(1).getIn().getBody(); + assertEquals(2, body2.split(";").length); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java new file mode 100644 index 0000000000..59aa2955d4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-aggregator/src/test/java/com/iluwatar/eip/aggregator/routes/MessageAggregationStrategyTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.aggregator.routes; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Tests MessageAggregationStrategy + */ +public class MessageAggregationStrategyTest { + + @Test + public void testAggregate() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + Exchange oldExchange = new DefaultExchange((CamelContext) null); + oldExchange.getIn().setBody("TEST1"); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(oldExchange, newExchange); + String outputBody = (String) output.getIn().getBody(); + assertEquals("TEST1;TEST2", outputBody); + } + + @Test + public void testAggregateOldNull() { + MessageAggregationStrategy mas = new MessageAggregationStrategy(); + + Exchange newExchange = new DefaultExchange((CamelContext) null); + newExchange.getIn().setBody("TEST2"); + + Exchange output = mas.aggregate(null, newExchange); + String outputBody = (String) output.getIn().getBody(); + + assertEquals(newExchange, output); + assertEquals("TEST2", outputBody); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java new file mode 100644 index 0000000000..264e39c467 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.splitter; + +import org.junit.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java new file mode 100644 index 0000000000..5bc59cc1ae --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-splitter/src/test/java/com/iluwatar/eip/splitter/routes/SplitterRouteTest.java @@ -0,0 +1,75 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.splitter.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertEquals; + +/** + * Test class for SplitterRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = SplitterRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class SplitterRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + /** + * Test if endpoint receives three separate messages. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testSplitter() throws Exception { + + // Three items in one entry message + entry.sendBody(new String[] {"TEST1", "TEST2", "TEST3"}); + + // Endpoint should have three different messages in the end order of the messages is not important + endpoint.expectedMessageCount(3); + endpoint.assertIsSatisfied(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java new file mode 100644 index 0000000000..31b4436601 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.wiretap; + +import org.junit.Test; + +/** + * Test for App class + */ +public class AppTest { + + @Test + public void testMain() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java new file mode 100644 index 0000000000..71c487bd82 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/eip-wire-tap/src/test/java/com/iluwatar/eip/wiretap/routes/WireTapRouteTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eip.wiretap.routes; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.assertEquals; + +/** + * Test class for WireTapRoute. + *

+ * In order for it to work we have to mock endpoints we want to read/write to. To mock those we need to substitute + * original endpoint names to mocks. + *

+ */ +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = WireTapRouteTest.class) +@ActiveProfiles("test") +@EnableAutoConfiguration +@ComponentScan +public class WireTapRouteTest { + + @EndpointInject(uri = "{{entry}}") + private ProducerTemplate entry; + + @EndpointInject(uri = "{{endpoint}}") + private MockEndpoint endpoint; + + @EndpointInject(uri = "{{wireTapEndpoint}}") + private MockEndpoint wireTapEndpoint; + + /** + * Test if both endpoints receive exactly one message containing the same, unchanged body. + * @throws Exception in case of en exception during the test + */ + @Test + @DirtiesContext + public void testWireTap() throws Exception { + entry.sendBody("TEST"); + + endpoint.expectedMessageCount(1); + wireTapEndpoint.expectedMessageCount(1); + + endpoint.assertIsSatisfied(); + wireTapEndpoint.assertIsSatisfied(); + + Message endpointIn = endpoint.getExchanges().get(0).getIn(); + Message wireTapEndpointIn = wireTapEndpoint.getExchanges().get(0).getIn(); + + assertEquals("TEST", endpointIn.getBody()); + assertEquals("TEST", wireTapEndpointIn.getBody()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java new file mode 100644 index 0000000000..6cd678704c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java new file mode 100644 index 0000000000..a67272789c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventEmitterTest.java @@ -0,0 +1,155 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Supplier; +import org.junit.Test; + +/** + * Date: 12/12/15 - 10:58 PM + * Tests for Event Emitter + * @param Type of Event Emitter + * @author Jeroen Meulemeester + */ +public abstract class EventEmitterTest { + + /** + * Factory used to create a new instance of the test object with a default observer + */ + private final Function factoryWithDefaultObserver; + + /** + * Factory used to create a new instance of the test object without passing a default observer + */ + private final Supplier factoryWithoutDefaultObserver; + + /** + * The day of the week an event is expected + */ + private final Weekday specialDay; + + /** + * The expected event, emitted on the special day + */ + private final Event event; + + /** + * Create a new event emitter test, using the given test object factories, special day and event + */ + EventEmitterTest(final Weekday specialDay, final Event event, + final Function factoryWithDefaultObserver, + final Supplier factoryWithoutDefaultObserver) { + + this.specialDay = specialDay; + this.event = event; + this.factoryWithDefaultObserver = Objects.requireNonNull(factoryWithDefaultObserver); + this.factoryWithoutDefaultObserver = Objects.requireNonNull(factoryWithoutDefaultObserver); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. This test + * is executed twice, once without a default emitter and once with + */ + @Test + public void testAllDays() { + testAllDaysWithoutDefaultObserver(specialDay, event); + testAllDaysWithDefaultObserver(specialDay, event); + } + + /** + * Pass each week of the day, day by day to the event emitter and verify of the given observers + * received the correct event on the special day. + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + * @param emitter The event emitter + * @param observers The registered observer mocks + */ + private void testAllDays(final Weekday specialDay, final Event event, final E emitter, + final EventObserver... observers) { + + for (final Weekday weekday : Weekday.values()) { + // Pass each week of the day, day by day to the event emitter + emitter.timePasses(weekday); + + if (weekday == specialDay) { + // On a special day, every observer should have received the event + for (final EventObserver observer : observers) { + verify(observer, times(1)).onEvent(eq(event)); + } + } else { + // On any other normal day, the observers should have received nothing at all + verifyZeroInteractions(observers); + } + } + + // The observers should not have received any additional events after the week + verifyNoMoreInteractions(observers); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. Use an + * event emitter without a default observer + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + */ + private void testAllDaysWithoutDefaultObserver(final Weekday specialDay, final Event event) { + final EventObserver observer1 = mock(EventObserver.class); + final EventObserver observer2 = mock(EventObserver.class); + + final E emitter = this.factoryWithoutDefaultObserver.get(); + emitter.registerObserver(observer1); + emitter.registerObserver(observer2); + + testAllDays(specialDay, event, emitter, observer1, observer2); + } + + /** + * Go over every day of the month, and check if the event is emitted on the given day. + * + * @param specialDay The special day on which an event is emitted + * @param event The expected event emitted by the test object + */ + private void testAllDaysWithDefaultObserver(final Weekday specialDay, final Event event) { + final EventObserver defaultObserver = mock(EventObserver.class); + final EventObserver observer1 = mock(EventObserver.class); + final EventObserver observer2 = mock(EventObserver.class); + + final E emitter = this.factoryWithDefaultObserver.apply(defaultObserver); + emitter.registerObserver(observer1); + emitter.registerObserver(observer2); + + testAllDays(specialDay, event, emitter, defaultObserver, observer1, observer2); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java new file mode 100644 index 0000000000..54c511f8c7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/EventTest.java @@ -0,0 +1,49 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/12/15 - 2:52 PM + * + * @author Jeroen Meulemeester + */ +public class EventTest { + + /** + * Verify if every event has a non-null, non-empty description + */ + @Test + public void testToString() { + for (final Event event : Event.values()) { + final String toString = event.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java new file mode 100644 index 0000000000..1743c32118 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingJoffreyTest.java @@ -0,0 +1,98 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/12/15 - 3:04 PM + * + * @author Jeroen Meulemeester + */ +public class KingJoffreyTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(KingJoffrey.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test if {@link KingJoffrey} tells us what event he received + */ + @Test + public void testOnEvent() { + final KingJoffrey kingJoffrey = new KingJoffrey(); + + for (int i = 0; i < Event.values().length; ++i) { + assertEquals(i, appender.getLogSize()); + Event event = Event.values()[i]; + kingJoffrey.onEvent(event); + + final String expectedMessage = "Received event from the King's Hand: " + event.toString(); + assertEquals(expectedMessage, appender.getLastMessage()); + assertEquals(i + 1, appender.getLogSize()); + } + + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java new file mode 100644 index 0000000000..ba13271821 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/KingsHandTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.Test; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:57 AM + * + * @author Jeroen Meulemeester + */ +public class KingsHandTest extends EventEmitterTest { + + /** + * Create a new test instance, using the correct object factory + */ + public KingsHandTest() { + super(null, null, KingsHand::new, KingsHand::new); + } + + /** + * The {@link KingsHand} is both an {@link EventEmitter} as an {@link EventObserver} so verify if every + * event received is passed up to it's superior, in most cases {@link KingJoffrey} but now just a + * mocked observer. + */ + @Test + public void testPassThrough() throws Exception { + final EventObserver observer = mock(EventObserver.class); + final KingsHand kingsHand = new KingsHand(observer); + + // The kings hand should not pass any events before he received one + verifyZeroInteractions(observer); + + // Verify if each event is passed on to the observer, nothing less, nothing more. + for (final Event event : Event.values()) { + kingsHand.onEvent(event); + verify(observer, times(1)).onEvent(eq(event)); + verifyNoMoreInteractions(observer); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java new file mode 100644 index 0000000000..ab25d7ccc2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-aggregator/src/test/java/com/iluwatar/event/aggregator/WeekdayTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.event.aggregator; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/12/15 - 2:12 PM + * + * @author Jeroen Meulemeester + */ +public class WeekdayTest { + + @Test + public void testToString() throws Exception { + for (final Weekday weekday : Weekday.values()) { + final String toString = weekday.toString(); + assertNotNull(toString); + assertEquals(weekday.name(), toString.toUpperCase()); + } + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java new file mode 100644 index 0000000000..2056dcf185 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/AppTest.java @@ -0,0 +1,32 @@ +/** + * The MIT License Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.event.asynchronous; + +import java.io.IOException; + +import org.junit.Test; + +/** + * Tests that EventAsynchronous example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java new file mode 100644 index 0000000000..8e0860286d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-asynchronous/src/test/java/com/iluwatar/event/asynchronous/EventAsynchronousTest.java @@ -0,0 +1,139 @@ +/** + * The MIT License Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.event.asynchronous; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.Assert.assertTrue; + +/** + * + * Application test + * + */ +public class EventAsynchronousTest { + App app; + + private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); + + @Before + public void setUp() { + app = new App(); + } + + @Test + public void testAsynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int aEventId = eventManager.createAsync(60); + eventManager.start(aEventId); + assertTrue(eventManager.getEventPool().size() == 1); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() == -1); + eventManager.cancel(aEventId); + assertTrue(eventManager.getEventPool().size() == 0); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testSynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int sEventId = eventManager.create(60); + eventManager.start(sEventId); + assertTrue(eventManager.getEventPool().size() == 1); + assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); + assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() != -1); + eventManager.cancel(sEventId); + assertTrue(eventManager.getEventPool().size() == 0); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException + | InvalidOperationException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test(expected = InvalidOperationException.class) + public void testUnsuccessfulSynchronousEvent() throws InvalidOperationException { + EventManager eventManager = new EventManager(); + try { + int sEventId = eventManager.create(60); + eventManager.start(sEventId); + sEventId = eventManager.create(60); + eventManager.start(sEventId); + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testFullSynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int eventTime = 1; + + int sEventId = eventManager.create(eventTime); + assertTrue(eventManager.getEventPool().size() == 1); + eventManager.start(sEventId); + + long currentTime = System.currentTimeMillis(); + long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to + // complete + // properly. + while (System.currentTimeMillis() < endTime) { + } + + assertTrue(eventManager.getEventPool().size() == 0); + + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException + | InvalidOperationException e) { + LOGGER.error(e.getMessage()); + } + } + + @Test + public void testFullAsynchronousEvent() { + EventManager eventManager = new EventManager(); + try { + int eventTime = 1; + + int aEventId1 = eventManager.createAsync(eventTime); + int aEventId2 = eventManager.createAsync(eventTime); + int aEventId3 = eventManager.createAsync(eventTime); + assertTrue(eventManager.getEventPool().size() == 3); + + eventManager.start(aEventId1); + eventManager.start(aEventId2); + eventManager.start(aEventId3); + + long currentTime = System.currentTimeMillis(); + long endTime = currentTime + (eventTime + 2 * 1000); // +2 to give a bit of buffer time for event to complete + // properly. + while (System.currentTimeMillis() < endTime) { + } + + assertTrue(eventManager.getEventPool().size() == 0); + + } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { + LOGGER.error(e.getMessage()); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java new file mode 100644 index 0000000000..e7d642b952 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Event Driven Architecture example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java new file mode 100644 index 0000000000..6e95f5fd2f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/event/UserCreatedEventTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda.event; + +import com.iluwatar.eda.model.User; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * {@link UserCreatedEventTest} tests and verifies {@link AbstractEvent} behaviour. + */ +public class UserCreatedEventTest { + + /** + * This unit test should correctly return the {@link AbstractEvent} class type when calling the + * {@link AbstractEvent#getType() getType} method. + */ + @Test + public void testGetEventType() { + User user = new User("iluwatar"); + UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); + assertEquals(UserCreatedEvent.class, userCreatedEvent.getType()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java new file mode 100644 index 0000000000..7501653f68 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-driven-architecture/src/test/java/com/iluwatar/eda/framework/EventDispatcherTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.eda.framework; + +import com.iluwatar.eda.event.UserCreatedEvent; +import com.iluwatar.eda.event.UserUpdatedEvent; +import com.iluwatar.eda.handler.UserCreatedEventHandler; +import com.iluwatar.eda.handler.UserUpdatedEventHandler; +import com.iluwatar.eda.model.User; + +import org.junit.Test; + +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Event Dispatcher unit tests to assert and verify correct event dispatcher behaviour + */ +public class EventDispatcherTest { + + /** + * This unit test should register events and event handlers correctly with the event dispatcher + * and events should be dispatched accordingly. + */ + @Test + public void testEventDriverPattern() { + + EventDispatcher dispatcher = spy(new EventDispatcher()); + UserCreatedEventHandler userCreatedEventHandler = spy(new UserCreatedEventHandler()); + UserUpdatedEventHandler userUpdatedEventHandler = spy(new UserUpdatedEventHandler()); + dispatcher.registerHandler(UserCreatedEvent.class, userCreatedEventHandler); + dispatcher.registerHandler(UserUpdatedEvent.class, userUpdatedEventHandler); + + User user = new User("iluwatar"); + + UserCreatedEvent userCreatedEvent = new UserCreatedEvent(user); + UserUpdatedEvent userUpdatedEvent = new UserUpdatedEvent(user); + + //fire a userCreatedEvent and verify that userCreatedEventHandler has been invoked. + dispatcher.dispatch(userCreatedEvent); + verify(userCreatedEventHandler).onEvent(userCreatedEvent); + verify(dispatcher).dispatch(userCreatedEvent); + + //fire a userCreatedEvent and verify that userUpdatedEventHandler has been invoked. + dispatcher.dispatch(userUpdatedEvent); + verify(userUpdatedEventHandler).onEvent(userUpdatedEvent); + verify(dispatcher).dispatch(userUpdatedEvent); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java new file mode 100644 index 0000000000..8e31ec6c38 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-queue/src/test/java/com/iluwatar/event/queue/AudioTest.java @@ -0,0 +1,77 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.event.queue; +import static org.junit.Assert.*; + +import java.io.IOException; + +import javax.sound.sampled.UnsupportedAudioFileException; + +import org.junit.Test; + +/** + * Testing the Audio service of the Queue + * @author mkuprivecz + * + */ +public class AudioTest { + + /** + * Test here that the playSound method works correctly + * @throws UnsupportedAudioFileException when the audio file is not supported + * @throws IOException when the file is not readable + * @throws InterruptedException when the test is interrupted externally + */ + @Test + public void testPlaySound() throws UnsupportedAudioFileException, IOException, InterruptedException { + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); + // test that service is started + assertTrue(Audio.isServiceRunning()); + // adding a small pause to be sure that the sound is ended + Thread.sleep(5000); + // test that service is finished + assertFalse(!Audio.isServiceRunning()); + } + + /** + * Test here that the Queue + * @throws UnsupportedAudioFileException when the audio file is not supported + * @throws IOException when the file is not readable + * @throws InterruptedException when the test is interrupted externally + */ + @Test + public void testQueue() throws UnsupportedAudioFileException, IOException, InterruptedException { + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + Audio.playSound(Audio.getAudioStream("./etc/Bass-Drum-1.aif"), -10.0f); + assertTrue(Audio.getPendingAudio().length > 0); + // test that service is started + assertTrue(Audio.isServiceRunning()); + // adding a small pause to be sure that the sound is ended + Thread.sleep(10000); + // test that service is finished + assertFalse(!Audio.isServiceRunning()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-sourcing/src/test/java/IntegrationTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-sourcing/src/test/java/IntegrationTest.java new file mode 100644 index 0000000000..5a3f5718aa --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/event-sourcing/src/test/java/IntegrationTest.java @@ -0,0 +1,99 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import com.iluwatar.event.sourcing.processor.DomainEventProcessor; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Intergartion Test for Event Sourcing state recovery + * + * Created by Serdar Hamzaogullari on 19.08.2017. + */ +public class IntegrationTest { + + /** + * The Domain event processor. + */ + private DomainEventProcessor eventProcessor; + + /** + * Initialize. + */ + @Before + public void initialize() { + eventProcessor = new DomainEventProcessor(); + } + + /** + * Test state recovery. + */ + @Test + public void testStateRecovery() { + eventProcessor.reset(); + + eventProcessor.process(new AccountCreateEvent( + 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + + eventProcessor.process(new AccountCreateEvent( + 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + + eventProcessor.process(new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + + eventProcessor.process(new MoneyDepositEvent( + 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + + eventProcessor.process(new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, + ACCOUNT_OF_JON)); + + Account accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + AccountAggregate.resetState(); + + eventProcessor = new DomainEventProcessor(); + eventProcessor.recover(); + + Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + Assert.assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), + accountOfDaenerysAfterShotDown.getMoney()); + Assert + .assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java new file mode 100644 index 0000000000..7604db16d1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/AppTest.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.execute.around; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +/** + * + * Tests execute-around example. + * + */ +public class AppTest { + + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } + + @Before + @After + public void cleanup() { + File file = new File("testfile.txt"); + file.delete(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java new file mode 100644 index 0000000000..fd13a92a90 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/execute-around/src/test/java/com/iluwatar/execute/around/SimpleFileWriterTest.java @@ -0,0 +1,96 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.execute.around; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/12/15 - 3:21 PM + * + * @author Jeroen Meulemeester + */ +public class SimpleFileWriterTest { + + /** + * Create a temporary folder, used to generate files in during this test + */ + @Rule + public final TemporaryFolder testFolder = new TemporaryFolder(); + + /** + * Verify if the given writer is not 'null' + */ + @Test + public void testWriterNotNull() throws Exception { + final File temporaryFile = this.testFolder.newFile(); + new SimpleFileWriter(temporaryFile.getPath(), Assert::assertNotNull); + } + + /** + * Test if the {@link SimpleFileWriter} creates a file if it doesn't exist + */ + @Test + public void testNonExistentFile() throws Exception { + final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); + assertFalse(nonExistingFile.exists()); + + new SimpleFileWriter(nonExistingFile.getPath(), Assert::assertNotNull); + assertTrue(nonExistingFile.exists()); + } + + /** + * Test if the data written to the file writer actually gets in the file + */ + @Test + public void testActualWrite() throws Exception { + final String testMessage = "Test message"; + + final File temporaryFile = this.testFolder.newFile(); + assertTrue(temporaryFile.exists()); + + new SimpleFileWriter(temporaryFile.getPath(), writer -> writer.write(testMessage)); + assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); + } + + /** + * Verify if an {@link IOException} during the write ripples through + */ + @Test(expected = IOException.class) + public void testIoException() throws Exception { + final File temporaryFile = this.testFolder.newFile(); + new SimpleFileWriter(temporaryFile.getPath(), writer -> { + throw new IOException(""); + }); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/AppTest.java new file mode 100644 index 0000000000..4857881129 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/AppTest.java @@ -0,0 +1,36 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +import org.junit.Test; + +/** + * Created by Srdjan on 03-May-17. + */ +public class AppTest { + @Test + public void main() throws Exception { + + String[] args = {}; + App.main(args); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/CommanderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/CommanderTest.java new file mode 100644 index 0000000000..11f0cc60ec --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/CommanderTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.Test; +import units.CommanderUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class CommanderTest { + @Test + public void commanderReady() throws Exception { + final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest")); + + commander.commanderReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SergeantTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SergeantTest.java new file mode 100644 index 0000000000..2deddca90d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SergeantTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.Test; +import units.SergeantUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SergeantTest { + @Test + public void sergeantReady() throws Exception { + final Sergeant sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest")); + + sergeant.sergeantReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SoldierTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SoldierTest.java new file mode 100644 index 0000000000..affc6ee8ba --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/concreteextensions/SoldierTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package concreteextensions; + +import org.junit.Test; +import units.SoldierUnit; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SoldierTest { + @Test + public void soldierReady() throws Exception { + final Soldier soldier = new Soldier(new SoldierUnit("SoldierUnitTest")); + + soldier.soldierReady(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/CommanderUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/CommanderUnitTest.java new file mode 100644 index 0000000000..8f4c1ca8d9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/CommanderUnitTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.CommanderExtension; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class CommanderUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new CommanderUnit("CommanderUnitName"); + + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNotNull((CommanderExtension) unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SergeantUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SergeantUnitTest.java new file mode 100644 index 0000000000..de773b59e8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SergeantUnitTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.SergeantExtension; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SergeantUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new SergeantUnit("SergeantUnitName"); + + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNotNull((SergeantExtension) unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SoldierUnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SoldierUnitTest.java new file mode 100644 index 0000000000..06a1f7611d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/SoldierUnitTest.java @@ -0,0 +1,47 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import abstractextensions.SoldierExtension; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class SoldierUnitTest { + @Test + public void getUnitExtension() throws Exception { + + final Unit unit = new SoldierUnit("SoldierUnitName"); + + assertNotNull((SoldierExtension) unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/UnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/UnitTest.java new file mode 100644 index 0000000000..a7d5300326 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/extension-objects/src/test/java/units/UnitTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package units; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * Created by Srdjan on 03-May-17. + */ +public class UnitTest { + + @Test + public void testConstGetSet() throws Exception { + final String name = "testName"; + final Unit unit = new Unit(name); + assertEquals(name, unit.getName()); + + final String newName = "newName"; + unit.setName(newName); + assertEquals(newName, unit.getName()); + + + assertNull(unit.getUnitExtension("")); + assertNull(unit.getUnitExtension("SoldierExtension")); + assertNull(unit.getUnitExtension("SergeantExtension")); + assertNull(unit.getUnitExtension("CommanderExtension")); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/AppTest.java new file mode 100644 index 0000000000..e890f42d43 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java new file mode 100644 index 0000000000..6457307cf2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/facade/src/test/java/com/iluwatar/facade/DwarvenGoldmineFacadeTest.java @@ -0,0 +1,135 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.facade; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/9/15 - 9:40 PM + * + * @author Jeroen Meulemeester + */ +public class DwarvenGoldmineFacadeTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Test a complete day cycle in the gold mine by executing all three different steps: {@link + * DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link + * DwarvenGoldmineFacade#endDay()}. + * + * See if the workers are doing what's expected from them on each step. + */ + @Test + public void testFullWorkDay() { + final DwarvenGoldmineFacade goldMine = new DwarvenGoldmineFacade(); + goldMine.startNewDay(); + + // On the start of a day, all workers should wake up ... + assertTrue(appender.logContains("Dwarf gold digger wakes up.")); + assertTrue(appender.logContains("Dwarf cart operator wakes up.")); + assertTrue(appender.logContains("Dwarven tunnel digger wakes up.")); + + // ... and go to the mine + assertTrue(appender.logContains("Dwarf gold digger goes to the mine.")); + assertTrue(appender.logContains("Dwarf cart operator goes to the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to the mine.")); + + // No other actions were invoked, so the workers shouldn't have done (printed) anything else + assertEquals(6, appender.getLogSize()); + + // Now do some actual work, start digging gold! + goldMine.digOutGold(); + + // Since we gave the dig command, every worker should be doing it's job ... + assertTrue(appender.logContains("Dwarf gold digger digs for gold.")); + assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine.")); + assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel.")); + + // Again, they shouldn't be doing anything else. + assertEquals(9, appender.getLogSize()); + + // Enough gold, lets end the day. + goldMine.endDay(); + + // Check if the workers go home ... + assertTrue(appender.logContains("Dwarf gold digger goes home.")); + assertTrue(appender.logContains("Dwarf cart operator goes home.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes home.")); + + // ... and go to sleep. We need well rested workers the next day :) + assertTrue(appender.logContains("Dwarf gold digger goes to sleep.")); + assertTrue(appender.logContains("Dwarf cart operator goes to sleep.")); + assertTrue(appender.logContains("Dwarven tunnel digger goes to sleep.")); + + // Every worker should be sleeping now, no other actions allowed + assertEquals(15, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java new file mode 100644 index 0000000000..4d8691ef04 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factorykit.app; + +import com.iluwatar.factorykit.App; +import org.junit.Test; + +/** + * Application Test Entrypoint + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} + diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java new file mode 100644 index 0000000000..3f732546d5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-kit/src/test/java/com/iluwatar/factorykit/factorykit/FactoryKitTest.java @@ -0,0 +1,88 @@ + /** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factorykit.factorykit; + +import static org.junit.Assert.assertTrue; + +import com.iluwatar.factorykit.Axe; +import com.iluwatar.factorykit.Spear; +import com.iluwatar.factorykit.Sword; +import com.iluwatar.factorykit.Weapon; +import com.iluwatar.factorykit.WeaponFactory; +import com.iluwatar.factorykit.WeaponType; +import org.junit.Before; +import org.junit.Test; +/** + * Test Factory Kit Pattern + */ +public class FactoryKitTest { + + private WeaponFactory factory; + + @Before + public void init() { + factory = WeaponFactory.factory(builder -> { + builder.add(WeaponType.SPEAR, Spear::new); + builder.add(WeaponType.AXE, Axe::new); + builder.add(WeaponType.SWORD, Sword::new); + }); + } + + /** + * Testing {@link WeaponFactory} to produce a SPEAR asserting that the Weapon is an instance of {@link Spear} + */ + @Test + public void testSpearWeapon() { + Weapon weapon = factory.create(WeaponType.SPEAR); + verifyWeapon(weapon, Spear.class); + } + + /** + * Testing {@link WeaponFactory} to produce a AXE asserting that the Weapon is an instance of {@link Axe} + */ + @Test + public void testAxeWeapon() { + Weapon weapon = factory.create(WeaponType.AXE); + verifyWeapon(weapon, Axe.class); + } + + + /** + * Testing {@link WeaponFactory} to produce a SWORD asserting that the Weapon is an instance of {@link Sword} + */ + @Test + public void testWeapon() { + Weapon weapon = factory.create(WeaponType.SWORD); + verifyWeapon(weapon, Sword.class); + } + + /** + * This method asserts that the weapon object that is passed is an instance of the clazz + * + * @param weapon weapon object which is to be verified + * @param clazz expected class of the weapon + */ + private void verifyWeapon(Weapon weapon, Class clazz) { + assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java new file mode 100644 index 0000000000..88b40d4fe6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factory.method; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Factory Method example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java new file mode 100644 index 0000000000..71afc5549d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/factory-method/src/test/java/com/iluwatar/factory/method/FactoryMethodTest.java @@ -0,0 +1,101 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.factory.method; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * The Factory Method is a creational design pattern which uses factory methods to deal with the + * problem of creating objects without specifying the exact class of object that will be created. + * This is done by creating objects via calling a factory method either specified in an interface + * and implemented by child classes, or implemented in a base class and optionally overridden by + * derived classes—rather than by calling a constructor. + * + *

Factory produces the object of its liking. + * The weapon {@link Weapon} manufactured by the + * blacksmith depends on the kind of factory implementation it is referring to. + *

+ */ +public class FactoryMethodTest { + + /** + * Testing {@link OrcBlacksmith} to produce a SPEAR asserting that the Weapon is an instance + * of {@link OrcWeapon}. + */ + @Test + public void testOrcBlacksmithWithSpear() { + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + verifyWeapon(weapon, WeaponType.SPEAR, OrcWeapon.class); + } + + /** + * Testing {@link OrcBlacksmith} to produce an AXE asserting that the Weapon is an instance + * of {@link OrcWeapon}. + */ + @Test + public void testOrcBlacksmithWithAxe() { + Blacksmith blacksmith = new OrcBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.AXE); + verifyWeapon(weapon, WeaponType.AXE, OrcWeapon.class); + } + + /** + * Testing {@link ElfBlacksmith} to produce a SHORT_SWORD asserting that the Weapon is an + * instance of {@link ElfWeapon}. + */ + @Test + public void testElfBlacksmithWithShortSword() { + Blacksmith blacksmith = new ElfBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SHORT_SWORD); + verifyWeapon(weapon, WeaponType.SHORT_SWORD, ElfWeapon.class); + } + + /** + * Testing {@link ElfBlacksmith} to produce a SPEAR asserting that the Weapon is an instance + * of {@link ElfWeapon}. + */ + @Test + public void testElfBlacksmithWithSpear() { + Blacksmith blacksmith = new ElfBlacksmith(); + Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR); + verifyWeapon(weapon, WeaponType.SPEAR, ElfWeapon.class); + } + + /** + * This method asserts that the weapon object that is passed is an instance of the clazz and the + * weapon is of type expectedWeaponType. + * + * @param weapon weapon object which is to be verified + * @param expectedWeaponType expected WeaponType of the weapon + * @param clazz expected class of the weapon + */ + private void verifyWeapon(Weapon weapon, WeaponType expectedWeaponType, Class clazz) { + assertTrue("Weapon must be an object of: " + clazz.getName(), clazz.isInstance(weapon)); + assertEquals("Weapon must be of weaponType: " + expectedWeaponType, expectedWeaponType, + weapon.getWeaponType()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java new file mode 100644 index 0000000000..846b46bcf8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/propertiesversion/PropertiesFeatureToggleVersionTest.java @@ -0,0 +1,71 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.featuretoggle.pattern.propertiesversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.iluwatar.featuretoggle.pattern.Service; +import com.iluwatar.featuretoggle.user.User; +import java.util.Properties; +import org.junit.Test; + +/** + * Test Properties Toggle + */ +public class PropertiesFeatureToggleVersionTest { + + @Test(expected = IllegalArgumentException.class) + public void testNullPropertiesPassed() throws Exception { + new PropertiesFeatureToggleVersion(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testNonBooleanProperty() throws Exception { + final Properties properties = new Properties(); + properties.setProperty("enhancedWelcome", "Something"); + new PropertiesFeatureToggleVersion(properties); + } + + @Test + public void testFeatureTurnedOn() throws Exception { + final Properties properties = new Properties(); + properties.put("enhancedWelcome", true); + Service service = new PropertiesFeatureToggleVersion(properties); + assertTrue(service.isEnhanced()); + final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + assertEquals("Welcome Jamie No Code. You're using the enhanced welcome message.", welcomeMessage); + } + + @Test + public void testFeatureTurnedOff() throws Exception { + final Properties properties = new Properties(); + properties.put("enhancedWelcome", false); + Service service = new PropertiesFeatureToggleVersion(properties); + assertFalse(service.isEnhanced()); + final String welcomeMessage = service.getWelcomeMessage(new User("Jamie No Code")); + assertEquals("Welcome to the application.", welcomeMessage); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java new file mode 100644 index 0000000000..3966032d5e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/pattern/tieredversion/TieredFeatureToggleVersionTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.featuretoggle.pattern.tieredversion; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.iluwatar.featuretoggle.pattern.Service; +import com.iluwatar.featuretoggle.user.User; +import com.iluwatar.featuretoggle.user.UserGroup; +import org.junit.Before; +import org.junit.Test; + +/** + * Test Tiered Feature Toggle + */ +public class TieredFeatureToggleVersionTest { + + final User paidUser = new User("Jamie Coder"); + final User freeUser = new User("Alan Defect"); + final Service service = new TieredFeatureToggleVersion(); + + @Before + public void setUp() throws Exception { + UserGroup.addUserToPaidGroup(paidUser); + UserGroup.addUserToFreeGroup(freeUser); + } + + @Test + public void testGetWelcomeMessageForPaidUser() throws Exception { + final String welcomeMessage = service.getWelcomeMessage(paidUser); + final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; + assertEquals(expected, welcomeMessage); + } + + @Test + public void testGetWelcomeMessageForFreeUser() throws Exception { + final String welcomeMessage = service.getWelcomeMessage(freeUser); + final String expected = "I suppose you can use this software."; + assertEquals(expected, welcomeMessage); + } + + @Test + public void testIsEnhancedAlwaysTrueAsTiered() throws Exception { + assertTrue(service.isEnhanced()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java new file mode 100644 index 0000000000..b2c6e5859d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/feature-toggle/src/test/java/com/iluwatar/featuretoggle/user/UserGroupTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.featuretoggle.user; + +import static junit.framework.TestCase.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * Test User Group specific feature + */ +public class UserGroupTest { + + @Test + public void testAddUserToFreeGroup() throws Exception { + User user = new User("Free User"); + UserGroup.addUserToFreeGroup(user); + assertFalse(UserGroup.isPaid(user)); + } + + @Test + public void testAddUserToPaidGroup() throws Exception { + User user = new User("Paid User"); + UserGroup.addUserToPaidGroup(user); + assertTrue(UserGroup.isPaid(user)); + } + + @Test(expected = IllegalArgumentException.class) + public void testAddUserToPaidWhenOnFree() throws Exception { + User user = new User("Paid User"); + UserGroup.addUserToFreeGroup(user); + UserGroup.addUserToPaidGroup(user); + } + + @Test(expected = IllegalArgumentException.class) + public void testAddUserToFreeWhenOnPaid() throws Exception { + User user = new User("Free User"); + UserGroup.addUserToPaidGroup(user); + UserGroup.addUserToFreeGroup(user); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java new file mode 100644 index 0000000000..11740bf1af --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/app/AppTest.java @@ -0,0 +1,36 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fluentinterface.app; + +import org.junit.Test; +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java new file mode 100644 index 0000000000..4cc2b1a7a7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/fluentinterface/src/test/java/com/iluwatar/fluentinterface/fluentiterable/FluentIterableTest.java @@ -0,0 +1,192 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.fluentinterface.fluentiterable; + +import org.junit.Test; + +import java.util.*; +import java.util.function.Consumer; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +/** + * Date: 12/12/15 - 7:00 PM + * + * @author Jeroen Meulemeester + */ +public abstract class FluentIterableTest { + + /** + * Create a new {@link FluentIterable} from the given integers + * + * @param integers The integers + * @return The new iterable, use for testing + */ + protected abstract FluentIterable createFluentIterable(final Iterable integers); + + @Test + public void testFirst() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final Optional first = createFluentIterable(integers).first(); + assertNotNull(first); + assertTrue(first.isPresent()); + assertEquals(integers.get(0), first.get()); + } + + @Test + public void testFirstEmptyCollection() throws Exception { + final List integers = Collections.emptyList(); + final Optional first = createFluentIterable(integers).first(); + assertNotNull(first); + assertFalse(first.isPresent()); + } + + @Test + public void testFirstCount() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List first4 = createFluentIterable(integers) + .first(4) + .asList(); + + assertNotNull(first4); + assertEquals(4, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + assertEquals(integers.get(3), first4.get(3)); + } + + @Test + public void testFirstCountLessItems() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List first4 = createFluentIterable(integers) + .first(4) + .asList(); + + assertNotNull(first4); + assertEquals(3, first4.size()); + + assertEquals(integers.get(0), first4.get(0)); + assertEquals(integers.get(1), first4.get(1)); + assertEquals(integers.get(2), first4.get(2)); + } + + @Test + public void testLast() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final Optional last = createFluentIterable(integers).last(); + assertNotNull(last); + assertTrue(last.isPresent()); + assertEquals(integers.get(integers.size() - 1), last.get()); + } + + @Test + public void testLastEmptyCollection() throws Exception { + final List integers = Collections.emptyList(); + final Optional last = createFluentIterable(integers).last(); + assertNotNull(last); + assertFalse(last.isPresent()); + } + + @Test + public void testLastCount() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List last4 = createFluentIterable(integers) + .last(4) + .asList(); + + assertNotNull(last4); + assertEquals(4, last4.size()); + assertEquals(Integer.valueOf(3), last4.get(0)); + assertEquals(Integer.valueOf(10), last4.get(1)); + assertEquals(Integer.valueOf(9), last4.get(2)); + assertEquals(Integer.valueOf(8), last4.get(3)); + } + + @Test + public void testLastCountLessItems() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List last4 = createFluentIterable(integers) + .last(4) + .asList(); + + assertNotNull(last4); + assertEquals(3, last4.size()); + + assertEquals(Integer.valueOf(1), last4.get(0)); + assertEquals(Integer.valueOf(2), last4.get(1)); + assertEquals(Integer.valueOf(3), last4.get(2)); + } + + @Test + public void testFilter() throws Exception { + final List integers = Arrays.asList(1, 2, 3, 10, 9, 8); + final List evenItems = createFluentIterable(integers) + .filter(i -> i % 2 == 0) + .asList(); + + assertNotNull(evenItems); + assertEquals(3, evenItems.size()); + assertEquals(Integer.valueOf(2), evenItems.get(0)); + assertEquals(Integer.valueOf(10), evenItems.get(1)); + assertEquals(Integer.valueOf(8), evenItems.get(2)); + } + + @Test + public void testMap() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final List longs = createFluentIterable(integers) + .map(Integer::longValue) + .asList(); + + assertNotNull(longs); + assertEquals(integers.size(), longs.size()); + assertEquals(Long.valueOf(1), longs.get(0)); + assertEquals(Long.valueOf(2), longs.get(1)); + assertEquals(Long.valueOf(3), longs.get(2)); + } + + @Test + public void testForEach() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + + final Consumer consumer = mock(Consumer.class); + createFluentIterable(integers).forEach(consumer); + + verify(consumer, times(1)).accept(Integer.valueOf(1)); + verify(consumer, times(1)).accept(Integer.valueOf(2)); + verify(consumer, times(1)).accept(Integer.valueOf(3)); + verifyNoMoreInteractions(consumer); + + } + + @Test + public void testSpliterator() throws Exception { + final List integers = Arrays.asList(1, 2, 3); + final Spliterator split = createFluentIterable(integers).spliterator(); + assertNotNull(split); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java new file mode 100644 index 0000000000..3ddf7805c9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/ContentTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.action; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/12/15 - 10:11 PM + * + * @author Jeroen Meulemeester + */ +public class ContentTest { + + @Test + public void testToString() throws Exception { + for (final Content content : Content.values()) { + final String toString = content.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java new file mode 100644 index 0000000000..e40133586e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/action/MenuItemTest.java @@ -0,0 +1,46 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.action; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/12/15 - 10:15 PM + * + * @author Jeroen Meulemeester + */ +public class MenuItemTest { + + @Test + public void testToString() throws Exception { + for (final MenuItem menuItem : MenuItem.values()) { + final String toString = menuItem.toString(); + assertNotNull(toString); + assertFalse(toString.trim().isEmpty()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/app/AppTest.java new file mode 100644 index 0000000000..7e6475ee73 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.app; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java new file mode 100644 index 0000000000..b245de6ac0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/dispatcher/DispatcherTest.java @@ -0,0 +1,113 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.dispatcher; + +import com.iluwatar.flux.action.Action; +import com.iluwatar.flux.action.ActionType; +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.store.Store; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.util.List; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 8:22 PM + * + * @author Jeroen Meulemeester + */ +public class DispatcherTest { + + /** + * Dispatcher is a singleton with no way to reset it's internal state back to the beginning. + * Replace the instance with a fresh one before each test to make sure test cases have no + * influence on each other. + */ + @Before + public void setUp() throws Exception { + final Constructor constructor; + constructor = Dispatcher.class.getDeclaredConstructor(); + constructor.setAccessible(true); + + final Field field = Dispatcher.class.getDeclaredField("instance"); + field.setAccessible(true); + field.set(Dispatcher.getInstance(), constructor.newInstance()); + } + + @Test + public void testGetInstance() throws Exception { + assertNotNull(Dispatcher.getInstance()); + assertSame(Dispatcher.getInstance(), Dispatcher.getInstance()); + } + + @Test + public void testMenuItemSelected() throws Exception { + final Dispatcher dispatcher = Dispatcher.getInstance(); + + final Store store = mock(Store.class); + dispatcher.registerStore(store); + dispatcher.menuItemSelected(MenuItem.HOME); + dispatcher.menuItemSelected(MenuItem.COMPANY); + + // We expect 4 events, 2 menu selections and 2 content change actions + final ArgumentCaptor actionCaptor = ArgumentCaptor.forClass(Action.class); + verify(store, times(4)).onAction(actionCaptor.capture()); + verifyNoMoreInteractions(store); + + final List actions = actionCaptor.getAllValues(); + final List menuActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.MENU_ITEM_SELECTED)) + .map(a -> (MenuAction) a) + .collect(Collectors.toList()); + + final List contentActions = actions.stream() + .filter(a -> a.getType().equals(ActionType.CONTENT_CHANGED)) + .map(a -> (ContentAction) a) + .collect(Collectors.toList()); + + assertEquals(2, menuActions.size()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.HOME::equals).count()); + assertEquals(1, menuActions.stream().map(MenuAction::getMenuItem).filter(MenuItem.COMPANY::equals).count()); + + assertEquals(2, contentActions.size()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.PRODUCTS::equals).count()); + assertEquals(1, contentActions.stream().map(ContentAction::getContent).filter(Content.COMPANY::equals).count()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java new file mode 100644 index 0000000000..85c0e46f4f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/ContentStoreTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.store; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:18 PM + * + * @author Jeroen Meulemeester + */ +public class ContentStoreTest { + + @Test + public void testOnAction() throws Exception { + final ContentStore contentStore = new ContentStore(); + + final View view = mock(View.class); + contentStore.registerView(view); + + verifyZeroInteractions(view); + + // Content should not react on menu action ... + contentStore.onAction(new MenuAction(MenuItem.PRODUCTS)); + verifyZeroInteractions(view); + + // ... but it should react on a content action + contentStore.onAction(new ContentAction(Content.COMPANY)); + verify(view, times(1)).storeChanged(eq(contentStore)); + verifyNoMoreInteractions(view); + assertEquals(Content.COMPANY, contentStore.getContent()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java new file mode 100644 index 0000000000..63d1dfdfb9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/store/MenuStoreTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.store; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.action.ContentAction; +import com.iluwatar.flux.action.MenuAction; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.view.View; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:18 PM + * + * @author Jeroen Meulemeester + */ +public class MenuStoreTest { + + @Test + public void testOnAction() throws Exception { + final MenuStore menuStore = new MenuStore(); + + final View view = mock(View.class); + menuStore.registerView(view); + + verifyZeroInteractions(view); + + // Menu should not react on content action ... + menuStore.onAction(new ContentAction(Content.COMPANY)); + verifyZeroInteractions(view); + + // ... but it should react on a menu action + menuStore.onAction(new MenuAction(MenuItem.PRODUCTS)); + verify(view, times(1)).storeChanged(eq(menuStore)); + verifyNoMoreInteractions(view); + assertEquals(MenuItem.PRODUCTS, menuStore.getSelected()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java new file mode 100644 index 0000000000..b97d751bf7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/ContentViewTest.java @@ -0,0 +1,54 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.view; + +import com.iluwatar.flux.action.Content; +import com.iluwatar.flux.store.ContentStore; +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/12/15 - 10:31 PM + * + * @author Jeroen Meulemeester + */ +public class ContentViewTest { + + @Test + public void testStoreChanged() throws Exception { + final ContentStore store = mock(ContentStore.class); + when(store.getContent()).thenReturn(Content.PRODUCTS); + + final ContentView view = new ContentView(); + view.storeChanged(store); + + verify(store, times(1)).getContent(); + verifyNoMoreInteractions(store); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java new file mode 100644 index 0000000000..528549e9ca --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flux/src/test/java/com/iluwatar/flux/view/MenuViewTest.java @@ -0,0 +1,71 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flux.view; + +import com.iluwatar.flux.action.Action; +import com.iluwatar.flux.action.MenuItem; +import com.iluwatar.flux.dispatcher.Dispatcher; +import com.iluwatar.flux.store.MenuStore; +import com.iluwatar.flux.store.Store; +import org.junit.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/12/15 - 10:31 PM + * + * @author Jeroen Meulemeester + */ +public class MenuViewTest { + + @Test + public void testStoreChanged() throws Exception { + final MenuStore store = mock(MenuStore.class); + when(store.getSelected()).thenReturn(MenuItem.HOME); + + final MenuView view = new MenuView(); + view.storeChanged(store); + + verify(store, times(1)).getSelected(); + verifyNoMoreInteractions(store); + } + + @Test + public void testItemClicked() throws Exception { + final Store store = mock(Store.class); + Dispatcher.getInstance().registerStore(store); + + final MenuView view = new MenuView(); + view.itemClicked(MenuItem.PRODUCTS); + + // We should receive a menu click action and a content changed action + verify(store, times(2)).onAction(any(Action.class)); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java new file mode 100644 index 0000000000..96cc455a78 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AlchemistShopTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/12/15 - 10:54 PM + * + * @author Jeroen Meulemeester + */ +public class AlchemistShopTest { + + @Test + public void testShop() throws Exception { + final AlchemistShop shop = new AlchemistShop(); + + final List bottomShelf = shop.getBottomShelf(); + assertNotNull(bottomShelf); + assertEquals(5, bottomShelf.size()); + + final List topShelf = shop.getTopShelf(); + assertNotNull(topShelf); + assertEquals(8, topShelf.size()); + + final List allPotions = new ArrayList<>(); + allPotions.addAll(topShelf); + allPotions.addAll(bottomShelf); + + // There are 13 potion instances, but only 5 unique instance types + assertEquals(13, allPotions.size()); + assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java new file mode 100644 index 0000000000..5d2d6815f1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/flyweight/src/test/java/com/iluwatar/flyweight/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.flyweight; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java new file mode 100644 index 0000000000..dd15be495e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java new file mode 100644 index 0000000000..c68a4ebf6b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ApplicationExceptionTest.java @@ -0,0 +1,42 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import static org.junit.Assert.assertSame; + +import org.junit.Test; + +/** + * Date: 12/13/15 - 1:35 PM + * + * @author Jeroen Meulemeester + */ +public class ApplicationExceptionTest { + + @Test + public void testCause() throws Exception { + final Exception cause = new Exception(); + assertSame(cause, new ApplicationException(cause).getCause()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java new file mode 100644 index 0000000000..edb5032ed1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/CommandTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class CommandTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Parameters + public static List data() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{"Archer", "Displaying archers"}); + parameters.add(new Object[]{"Catapult", "Displaying catapults"}); + parameters.add(new Object[]{"NonExistentCommand", "Error 500"}); + return parameters; + } + + /** + * The view that's been tested + */ + private final String request; + + /** + * The expected display message + */ + private final String displayMessage; + + /** + * Create a new instance of the {@link CommandTest} with the given view and expected message + * + * @param request The request that's been tested + * @param displayMessage The expected display message + */ + public CommandTest(final String request, final String displayMessage) { + this.displayMessage = displayMessage; + this.request = request; + } + + @Test + public void testDisplay() { + final FrontController frontController = new FrontController(); + assertEquals(0, appender.getLogSize()); + frontController.handleRequest(request); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java new file mode 100644 index 0000000000..5367403f97 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/FrontControllerTest.java @@ -0,0 +1,96 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class FrontControllerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Parameters + public static List data() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new ArcherCommand(), "Displaying archers"}); + parameters.add(new Object[]{new CatapultCommand(), "Displaying catapults"}); + parameters.add(new Object[]{new UnknownCommand(), "Error 500"}); + return parameters; + } + + /** + * The view that's been tested + */ + private final Command command; + + /** + * The expected display message + */ + private final String displayMessage; + + /** + * Create a new instance of the {@link FrontControllerTest} with the given view and expected message + * + * @param command The command that's been tested + * @param displayMessage The expected display message + */ + public FrontControllerTest(final Command command, final String displayMessage) { + this.displayMessage = displayMessage; + this.command = command; + } + + @Test + public void testDisplay() { + assertEquals(0, appender.getLogSize()); + this.command.process(); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java new file mode 100644 index 0000000000..a5786b97eb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/front-controller/src/test/java/com/iluwatar/front/controller/ViewTest.java @@ -0,0 +1,96 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.front.controller; + +import com.iluwatar.front.controller.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/13/15 - 1:39 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class ViewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Parameters + public static List data() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new ArcherView(), "Displaying archers"}); + parameters.add(new Object[]{new CatapultView(), "Displaying catapults"}); + parameters.add(new Object[]{new ErrorView(), "Error 500"}); + return parameters; + } + + /** + * The view that's been tested + */ + private final View view; + + /** + * The expected display message + */ + private final String displayMessage; + + /** + * Create a new instance of the {@link ViewTest} with the given view and expected message + * + * @param view The view that's been tested + * @param displayMessage The expected display message + */ + public ViewTest(final View view, final String displayMessage) { + this.displayMessage = displayMessage; + this.view = view; + } + + @Test + public void testDisplay() { + assertEquals(0, appender.getLogSize()); + this.view.display(); + assertEquals(displayMessage, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java new file mode 100644 index 0000000000..5a741d399b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/guarded-suspension/src/test/java/com/iluwatar/guarded/suspension/GuardedQueueTest.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.guarded.suspension; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * Test for Guarded Queue + */ +public class GuardedQueueTest { + private volatile Integer value; + + @Test + public void testGet() { + GuardedQueue g = new GuardedQueue(); + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.submit(() -> value = g.get()); + executorService.submit(() -> g.put(Integer.valueOf(10))); + executorService.shutdown(); + try { + executorService.awaitTermination(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + Assert.assertEquals(Integer.valueOf(10), value); + } + + @Test + public void testPut() { + GuardedQueue g = new GuardedQueue(); + g.put(12); + Assert.assertEquals(Integer.valueOf(12), g.get()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java new file mode 100644 index 0000000000..2dfc2bf5cb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.halfsynchalfasync; + +import java.util.concurrent.ExecutionException; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws InterruptedException, ExecutionException { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java new file mode 100644 index 0000000000..c6d00b1ac4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/half-sync-half-async/src/test/java/com/iluwatar/halfsynchalfasync/AsynchronousServiceTest.java @@ -0,0 +1,94 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.halfsynchalfasync; + +import org.junit.Test; +import org.mockito.InOrder; + +import java.io.IOException; +import java.util.concurrent.LinkedBlockingQueue; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; + +/** + * Date: 12/12/15 - 11:15 PM + * + * @author Jeroen Meulemeester + */ +public class AsynchronousServiceTest { + + @Test + public void testPerfectExecution() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final Object result = new Object(); + when(task.call()).thenReturn(result); + service.execute(task); + + verify(task, timeout(2000)).onPostCall(eq(result)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).call(); + inOrder.verify(task, times(1)).onPostCall(eq(result)); + + verifyNoMoreInteractions(task); + } + + @Test + public void testCallException() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final IOException exception = new IOException(); + when(task.call()).thenThrow(exception); + service.execute(task); + + verify(task, timeout(2000)).onError(eq(exception)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).call(); + inOrder.verify(task, times(1)).onError(exception); + + verifyNoMoreInteractions(task); + } + + @Test + public void testPreCallException() throws Exception { + final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>()); + final AsyncTask task = mock(AsyncTask.class); + final IllegalStateException exception = new IllegalStateException(); + doThrow(exception).when(task).onPreCall(); + service.execute(task); + + verify(task, timeout(2000)).onError(eq(exception)); + + final InOrder inOrder = inOrder(task); + inOrder.verify(task, times(1)).onPreCall(); + inOrder.verify(task, times(1)).onError(exception); + + verifyNoMoreInteractions(task); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java new file mode 100644 index 0000000000..1e35847b2e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal; + +import org.junit.Test; + +/** + * Unit test for simple App. + */ +public class AppTest { + + @Test + public void testApp() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java new file mode 100644 index 0000000000..9c265a2ab5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/InMemoryBankTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.banking; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * + * Tests for banking + * + */ +public class InMemoryBankTest { + + private final WireTransfers bank = new InMemoryBank(); + + @Test + public void testInit() { + assertEquals(bank.getFunds("foo"), 0); + bank.setFunds("foo", 100); + assertEquals(bank.getFunds("foo"), 100); + bank.setFunds("bar", 150); + assertEquals(bank.getFunds("bar"), 150); + assertTrue(bank.transferFunds(50, "bar", "foo")); + assertEquals(bank.getFunds("foo"), 150); + assertEquals(bank.getFunds("bar"), 100); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java new file mode 100644 index 0000000000..61529f3e4e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/banking/MongoBankTest.java @@ -0,0 +1,69 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.banking; + +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Tests for Mongo banking adapter + */ +@Ignore +public class MongoBankTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_ACCOUNTS_COLLECTION = "testAccounts"; + + private MongoBank mongoBank; + + @Before + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + mongoBank = new MongoBank(TEST_DB, TEST_ACCOUNTS_COLLECTION); + } + + @Test + public void testSetup() { + assertEquals(0, mongoBank.getAccountsCollection().count()); + } + + @Test + public void testFundTransfers() { + assertEquals(0, mongoBank.getFunds("000-000")); + mongoBank.setFunds("000-000", 10); + assertEquals(10, mongoBank.getFunds("000-000")); + assertEquals(0, mongoBank.getFunds("111-111")); + mongoBank.transferFunds(9, "000-000", "111-111"); + assertEquals(1, mongoBank.getFunds("000-000")); + assertEquals(9, mongoBank.getFunds("111-111")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java new file mode 100644 index 0000000000..ce50383699 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/InMemoryTicketRepositoryTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.database; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Optional; + +import org.junit.Before; +import org.junit.Test; + +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.test.LotteryTestUtils; + +/** + * + * Tests for {@link LotteryTicketRepository} + * + */ +public class InMemoryTicketRepositoryTest { + + private final LotteryTicketRepository repository = new InMemoryTicketRepository(); + + @Before + public void clear() { + repository.deleteAll(); + } + + @Test + public void testCrudOperations() { + LotteryTicketRepository repository = new InMemoryTicketRepository(); + assertEquals(repository.findAll().size(), 0); + LotteryTicket ticket = LotteryTestUtils.createLotteryTicket(); + Optional id = repository.save(ticket); + assertTrue(id.isPresent()); + assertEquals(repository.findAll().size(), 1); + Optional optionalTicket = repository.findById(id.get()); + assertTrue(optionalTicket.isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java new file mode 100644 index 0000000000..8b248de8c0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/database/MongoTicketRepositoryTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.database; + +import com.iluwatar.hexagonal.domain.LotteryNumbers; +import com.iluwatar.hexagonal.domain.LotteryTicket; +import com.iluwatar.hexagonal.domain.LotteryTicketId; +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Tests for Mongo based ticket repository + */ +@Ignore +public class MongoTicketRepositoryTest { + + private static final String TEST_DB = "lotteryTestDB"; + private static final String TEST_TICKETS_COLLECTION = "lotteryTestTickets"; + private static final String TEST_COUNTERS_COLLECTION = "testCounters"; + + private MongoTicketRepository repository; + + @Before + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + repository = new MongoTicketRepository(TEST_DB, TEST_TICKETS_COLLECTION, + TEST_COUNTERS_COLLECTION); + } + + @Test + public void testSetup() { + assertTrue(repository.getCountersCollection().count() == 1); + assertTrue(repository.getTicketsCollection().count() == 0); + } + + @Test + public void testNextId() { + assertEquals(1, repository.getNextId()); + assertEquals(2, repository.getNextId()); + assertEquals(3, repository.getNextId()); + } + + @Test + public void testCrudOperations() { + // create new lottery ticket and save it + PlayerDetails details = new PlayerDetails("foo@bar.com", "123-123", "07001234"); + LotteryNumbers random = LotteryNumbers.createRandom(); + LotteryTicket original = new LotteryTicket(new LotteryTicketId(), details, random); + Optional saved = repository.save(original); + assertEquals(1, repository.getTicketsCollection().count()); + assertTrue(saved.isPresent()); + // fetch the saved lottery ticket from database and check its contents + Optional found = repository.findById(saved.get()); + assertTrue(found.isPresent()); + LotteryTicket ticket = found.get(); + assertEquals("foo@bar.com", ticket.getPlayerDetails().getEmail()); + assertEquals("123-123", ticket.getPlayerDetails().getBankAccount()); + assertEquals("07001234", ticket.getPlayerDetails().getPhoneNumber()); + assertEquals(original.getNumbers(), ticket.getNumbers()); + // clear the collection + repository.deleteAll(); + assertEquals(0, repository.getTicketsCollection().count()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java new file mode 100644 index 0000000000..8bd61db9cc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryNumbersTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; + +import org.junit.Test; + +/** + * + * Unit tests for {@link LotteryNumbers} + * + */ +public class LotteryNumbersTest { + + @Test + public void testGivenNumbers() { + LotteryNumbers numbers = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + assertEquals(numbers.getNumbers().size(), 4); + assertTrue(numbers.getNumbers().contains(1)); + assertTrue(numbers.getNumbers().contains(2)); + assertTrue(numbers.getNumbers().contains(3)); + assertTrue(numbers.getNumbers().contains(4)); + } + + @Test(expected = UnsupportedOperationException.class) + public void testNumbersCantBeModified() { + LotteryNumbers numbers = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + numbers.getNumbers().add(5); + } + + @Test + public void testRandomNumbers() { + LotteryNumbers numbers = LotteryNumbers.createRandom(); + assertEquals(numbers.getNumbers().size(), LotteryNumbers.NUM_NUMBERS); + } + + @Test + public void testEquals() { + LotteryNumbers numbers1 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + LotteryNumbers numbers2 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(1, 2, 3, 4))); + assertTrue(numbers1.equals(numbers2)); + LotteryNumbers numbers3 = LotteryNumbers.create( + new HashSet<>(Arrays.asList(11, 12, 13, 14))); + assertFalse(numbers1.equals(numbers3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java new file mode 100644 index 0000000000..4af8da3eab --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTest.java @@ -0,0 +1,114 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; + +import com.google.inject.Guice; +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.iluwatar.hexagonal.module.LotteryTestingModule; +import org.junit.Before; +import org.junit.Test; + +import com.iluwatar.hexagonal.banking.WireTransfers; +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; +import com.iluwatar.hexagonal.test.LotteryTestUtils; + +/** + * + * Test the lottery system + * + */ +public class LotteryTest { + + private Injector injector; + @Inject + private LotteryAdministration administration; + @Inject + private LotteryService service; + @Inject + private WireTransfers wireTransfers; + + public LotteryTest() { + this.injector = Guice.createInjector(new LotteryTestingModule()); + } + + @Before + public void setup() { + injector.injectMembers(this); + // add funds to the test player's bank account + wireTransfers.setFunds("123-12312", 100); + } + + @Test + public void testLottery() { + // admin resets the lottery + administration.resetLottery(); + assertEquals(administration.getAllSubmittedTickets().size(), 0); + + // players submit the lottery tickets + Optional ticket1 = service.submitTicket(LotteryTestUtils.createLotteryTicket("cvt@bbb.com", + "123-12312", "+32425255", new HashSet<>(Arrays.asList(1, 2, 3, 4)))); + assertTrue(ticket1.isPresent()); + Optional ticket2 = service.submitTicket(LotteryTestUtils.createLotteryTicket("ant@bac.com", + "123-12312", "+32423455", new HashSet<>(Arrays.asList(11, 12, 13, 14)))); + assertTrue(ticket2.isPresent()); + Optional ticket3 = service.submitTicket(LotteryTestUtils.createLotteryTicket("arg@boo.com", + "123-12312", "+32421255", new HashSet<>(Arrays.asList(6, 8, 13, 19)))); + assertTrue(ticket3.isPresent()); + assertEquals(administration.getAllSubmittedTickets().size(), 3); + + // perform lottery + LotteryNumbers winningNumbers = administration.performLottery(); + + // cheat a bit for testing sake, use winning numbers to submit another ticket + Optional ticket4 = service.submitTicket(LotteryTestUtils.createLotteryTicket("lucky@orb.com", + "123-12312", "+12421255", winningNumbers.getNumbers())); + assertTrue(ticket4.isPresent()); + assertEquals(administration.getAllSubmittedTickets().size(), 4); + + // check winners + Map tickets = administration.getAllSubmittedTickets(); + for (LotteryTicketId id: tickets.keySet()) { + LotteryTicketCheckResult checkResult = service.checkTicketForPrize(id, winningNumbers); + assertTrue(checkResult.getResult() != CheckResult.TICKET_NOT_SUBMITTED); + if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { + assertTrue(checkResult.getPrizeAmount() > 0); + } else if (checkResult.getResult().equals(CheckResult.WIN_PRIZE)) { + assertEquals(checkResult.getPrizeAmount(), 0); + } + } + + // check another ticket that has not been submitted + LotteryTicketCheckResult checkResult = service.checkTicketForPrize(new LotteryTicketId(), winningNumbers); + assertTrue(checkResult.getResult() == CheckResult.TICKET_NOT_SUBMITTED); + assertEquals(checkResult.getPrizeAmount(), 0); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java new file mode 100644 index 0000000000..454d0dd010 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResultTest.java @@ -0,0 +1,47 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult.CheckResult; + +/** + * + * Unit tests for {@link LotteryTicketCheckResult} + * + */ +public class LotteryTicketCheckResultTest { + + @Test + public void testEquals() { + LotteryTicketCheckResult result1 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + LotteryTicketCheckResult result2 = new LotteryTicketCheckResult(CheckResult.NO_PRIZE); + assertEquals(result1, result2); + LotteryTicketCheckResult result3 = new LotteryTicketCheckResult(CheckResult.WIN_PRIZE, 300000); + assertFalse(result1.equals(result3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java new file mode 100644 index 0000000000..d4f0848ba6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketIdTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Tests for lottery ticket id + */ +public class LotteryTicketIdTest { + + @Test + public void testEquals() { + LotteryTicketId ticketId1 = new LotteryTicketId(); + LotteryTicketId ticketId2 = new LotteryTicketId(); + LotteryTicketId ticketId3 = new LotteryTicketId(); + assertFalse(ticketId1.equals(ticketId2)); + assertFalse(ticketId2.equals(ticketId3)); + LotteryTicketId ticketId4 = new LotteryTicketId(ticketId1.getId()); + assertTrue(ticketId1.equals(ticketId4)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java new file mode 100644 index 0000000000..a83f9033cf --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/LotteryTicketTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.Arrays; +import java.util.HashSet; + +import org.junit.Test; + +/** + * Test Lottery Tickets for equality + */ +public class LotteryTicketTest { + + @Test + public void testEquals() { + PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + LotteryNumbers numbers1 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); + LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1); + PlayerDetails details2 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322"); + LotteryNumbers numbers2 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 4))); + LotteryTicket ticket2 = new LotteryTicket(new LotteryTicketId(), details2, numbers2); + assertEquals(ticket1, ticket2); + PlayerDetails details3 = new PlayerDetails("elsa@foo.bar", "1223-121212", "+49332322"); + LotteryNumbers numbers3 = LotteryNumbers.create(new HashSet(Arrays.asList(1, 2, 3, 8))); + LotteryTicket ticket3 = new LotteryTicket(new LotteryTicketId(), details3, numbers3); + assertFalse(ticket1.equals(ticket3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java new file mode 100644 index 0000000000..2271ebf7c3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/domain/PlayerDetailsTest.java @@ -0,0 +1,45 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +/** + * + * Unit tests for {@link PlayerDetails} + * + */ +public class PlayerDetailsTest { + + @Test + public void testEquals() { + PlayerDetails details1 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + PlayerDetails details2 = new PlayerDetails("tom@foo.bar", "11212-123434", "+12323425"); + assertEquals(details1, details2); + PlayerDetails details3 = new PlayerDetails("john@foo.bar", "16412-123439", "+34323432"); + assertFalse(details1.equals(details3)); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java new file mode 100644 index 0000000000..07c40691be --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/hexagonal/src/test/java/com/iluwatar/hexagonal/eventlog/MongoEventLogTest.java @@ -0,0 +1,84 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.hexagonal.eventlog; + +import com.iluwatar.hexagonal.domain.PlayerDetails; +import com.iluwatar.hexagonal.mongo.MongoConnectionPropertiesLoader; +import com.mongodb.MongoClient; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Tests for Mongo event log + */ +@Ignore +public class MongoEventLogTest { + + private static final String TEST_DB = "lotteryDBTest"; + private static final String TEST_EVENTS_COLLECTION = "testEvents"; + + private MongoEventLog mongoEventLog; + + @Before + public void init() { + MongoConnectionPropertiesLoader.load(); + MongoClient mongoClient = new MongoClient(System.getProperty("mongo-host"), + Integer.parseInt(System.getProperty("mongo-port"))); + mongoClient.dropDatabase(TEST_DB); + mongoClient.close(); + mongoEventLog = new MongoEventLog(TEST_DB, TEST_EVENTS_COLLECTION); + } + + @Test + public void testSetup() { + assertEquals(0, mongoEventLog.getEventsCollection().count()); + } + + @Test + public void testFundTransfers() { + PlayerDetails playerDetails = new PlayerDetails("john@wayne.com", "000-000", "03432534543"); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(1, mongoEventLog.getEventsCollection().count()); + mongoEventLog.prizeError(playerDetails, 1000); + assertEquals(2, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(3, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketDidNotWin(playerDetails); + assertEquals(4, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(5, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitError(playerDetails); + assertEquals(6, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(7, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketSubmitted(playerDetails); + assertEquals(8, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(9, mongoEventLog.getEventsCollection().count()); + mongoEventLog.ticketWon(playerDetails, 1000); + assertEquals(10, mongoEventLog.getEventsCollection().count()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java new file mode 100644 index 0000000000..eb347dce75 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.Test; + +/** + * + * Application test. + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java new file mode 100644 index 0000000000..9b77ea19c6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterManagerTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/13/15 - 3:01 PM + * + * @author Jeroen Meulemeester + */ +public class FilterManagerTest { + + @Test + public void testFilterRequest() throws Exception { + final Target target = mock(Target.class); + final FilterManager filterManager = new FilterManager(); + assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); + verifyZeroInteractions(target); + } + + @Test + public void testAddFilter() throws Exception { + final Target target = mock(Target.class); + final FilterManager filterManager = new FilterManager(); + + verifyZeroInteractions(target); + + final Filter filter = mock(Filter.class); + when(filter.execute(any(Order.class))).thenReturn("filter"); + + filterManager.addFilter(filter); + + final Order order = mock(Order.class); + assertEquals("filter", filterManager.filterRequest(order)); + + verify(filter, times(1)).execute(any(Order.class)); + verifyZeroInteractions(target, filter, order); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java new file mode 100644 index 0000000000..877340355d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/FilterTest.java @@ -0,0 +1,120 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.ArrayList; +import java.util.List; + +import static junit.framework.TestCase.assertSame; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Date: 12/13/15 - 2:17 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class FilterTest { + + private static final Order PERFECT_ORDER = new Order("name", "12345678901", "addr", "dep", "order"); + private static final Order WRONG_ORDER = new Order("name", "12345678901", "addr", "dep", ""); + private static final Order WRONG_DEPOSIT = new Order("name", "12345678901", "addr", "", "order"); + private static final Order WRONG_ADDRESS = new Order("name", "12345678901", "", "dep", "order"); + private static final Order WRONG_CONTACT = new Order("name", "", "addr", "dep", "order"); + private static final Order WRONG_NAME = new Order("", "12345678901", "addr", "dep", "order"); + + @Parameters + public static List getTestData() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{new NameFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_NAME, "Invalid name!"}); + testData.add(new Object[]{new NameFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new NameFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new ContactFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_CONTACT, "Invalid contact number!"}); + testData.add(new Object[]{new ContactFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new ContactFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new AddressFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_ADDRESS, "Invalid address!"}); + testData.add(new Object[]{new AddressFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new AddressFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new DepositFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new DepositFilter(), WRONG_DEPOSIT, "Invalid deposit number!"}); + testData.add(new Object[]{new DepositFilter(), WRONG_ORDER, ""}); + + testData.add(new Object[]{new OrderFilter(), PERFECT_ORDER, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_NAME, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_CONTACT, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_ADDRESS, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_DEPOSIT, ""}); + testData.add(new Object[]{new OrderFilter(), WRONG_ORDER, "Invalid order!"}); + + return testData; + } + + private final Filter filter; + private final Order order; + private final String result; + + /** + * Constructor + */ + public FilterTest(Filter filter, Order order, String result) { + this.filter = filter; + this.order = order; + this.result = result; + } + + @Test + public void testExecute() throws Exception { + final String result = this.filter.execute(this.order); + assertNotNull(result); + assertEquals(this.result, result.trim()); + } + + @Test + public void testNext() throws Exception { + assertNull(this.filter.getNext()); + assertSame(this.filter, this.filter.getLast()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java new file mode 100644 index 0000000000..f52f6deece --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/intercepting-filter/src/test/java/com/iluwatar/intercepting/filter/OrderTest.java @@ -0,0 +1,73 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.intercepting.filter; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/13/15 - 2:57 PM + * + * @author Jeroen Meulemeester + */ +public class OrderTest { + + private static final String EXPECTED_VALUE = "test"; + + @Test + public void testSetName() throws Exception { + final Order order = new Order(); + order.setName(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getName()); + } + + @Test + public void testSetContactNumber() throws Exception { + final Order order = new Order(); + order.setContactNumber(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getContactNumber()); + } + + @Test + public void testSetAddress() throws Exception { + final Order order = new Order(); + order.setAddress(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getAddress()); + } + + @Test + public void testSetDepositNumber() throws Exception { + final Order order = new Order(); + order.setDepositNumber(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getDepositNumber()); + } + + @Test + public void testSetOrder() throws Exception { + final Order order = new Order(); + order.setOrderItem(EXPECTED_VALUE); + assertEquals(EXPECTED_VALUE, order.getOrderItem()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java new file mode 100644 index 0000000000..b2d6db1575 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java new file mode 100644 index 0000000000..2241b882b0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/ExpressionTest.java @@ -0,0 +1,136 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.IntBinaryOperator; + +import org.junit.Test; + +/** + * Date: 12/14/15 - 11:48 AM + * + * Test Case for Expressions + * @param Type of Expression + * @author Jeroen Meulemeester + */ +public abstract class ExpressionTest { + + /** + * Generate inputs ranging from -10 to 10 for both input params and calculate the expected result + * + * @param resultCalc The function used to calculate the expected result + * @return A data set with test entries + */ + static List prepareParameters(final IntBinaryOperator resultCalc) { + final List testData = new ArrayList<>(); + for (int i = -10; i < 10; i++) { + for (int j = -10; j < 10; j++) { + testData.add(new Object[]{ + new NumberExpression(i), + new NumberExpression(j), + resultCalc.applyAsInt(i, j) + }); + } + } + return testData; + } + + /** + * The input used as first parameter during the test + */ + private final NumberExpression first; + + /** + * The input used as second parameter during the test + */ + private final NumberExpression second; + + /** + * The expected result of the calculation, taking the first and second parameter in account + */ + private final int result; + + /** + * The expected {@link E#toString()} response + */ + private final String expectedToString; + + /** + * Factory, used to create a new test object instance with the correct first and second parameter + */ + private final BiFunction factory; + + /** + * Create a new test instance with the given parameters and expected results + * + * @param first The input used as first parameter during the test + * @param second The input used as second parameter during the test + * @param result The expected result of the tested expression + * @param expectedToString The expected {@link E#toString()} response + * @param factory Factory, used to create a new test object instance + */ + ExpressionTest(final NumberExpression first, final NumberExpression second, final int result, + final String expectedToString, final BiFunction factory) { + + this.first = first; + this.second = second; + this.result = result; + this.expectedToString = expectedToString; + this.factory = factory; + } + + /** + * Get the first parameter + * + * @return The first parameter + */ + final NumberExpression getFirst() { + return this.first; + } + + /** + * Verify if the expression calculates the correct result when calling {@link E#interpret()} + */ + @Test + public void testInterpret() { + final E expression = this.factory.apply(this.first, this.second); + assertNotNull(expression); + assertEquals(this.result, expression.interpret()); + } + + /** + * Verify if the expression has the expected {@link E#toString()} value + */ + @Test + public void testToString() { + final E expression = this.factory.apply(this.first, this.second); + assertNotNull(expression); + assertEquals(expectedToString, expression.toString()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java new file mode 100644 index 0000000000..65e7e4515e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MinusExpressionTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.List; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class MinusExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + @Parameters + public static List data() { + return prepareParameters((f, s) -> f - s); + } + + /** + * Create a new test instance using the given test parameters and expected result + * + * @param first The first expression parameter + * @param second The second expression parameter + * @param result The expected result + */ + public MinusExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { + super(first, second, result, "-", MinusExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java new file mode 100644 index 0000000000..12ea358634 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/MultiplyExpressionTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.List; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class MultiplyExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + @Parameters + public static List data() { + return prepareParameters((f, s) -> f * s); + } + + /** + * Create a new test instance using the given test parameters and expected result + * + * @param first The first expression parameter + * @param second The second expression parameter + * @param result The expected result + */ + public MultiplyExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { + super(first, second, result, "*", MultiplyExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java new file mode 100644 index 0000000000..9f18355ef5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/NumberExpressionTest.java @@ -0,0 +1,74 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class NumberExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + @Parameters + public static List data() { + return prepareParameters((f, s) -> f); + } + + /** + * Create a new test instance using the given test parameters and expected result + * + * @param first The first expression parameter + * @param second The second expression parameter + * @param result The expected result + */ + public NumberExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { + super(first, second, result, "number", (f, s) -> f); + } + + /** + * Verify if the {@link NumberExpression#NumberExpression(String)} constructor works as expected + */ + @Test + public void testFromString() throws Exception { + final int expectedValue = getFirst().interpret(); + final String testStingValue = String.valueOf(expectedValue); + final NumberExpression numberExpression = new NumberExpression(testStingValue); + assertEquals(expectedValue, numberExpression.interpret()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java new file mode 100644 index 0000000000..d11ba8a8d4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/interpreter/src/test/java/com/iluwatar/interpreter/PlusExpressionTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.interpreter; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.List; + +/** + * Date: 12/14/15 - 12:08 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class PlusExpressionTest extends ExpressionTest { + + /** + * Create a new set of test entries with the expected result + * + * @return The list of parameters used during this test + */ + @Parameters + public static List data() { + return prepareParameters((f, s) -> f + s); + } + + /** + * Create a new test instance using the given test parameters and expected result + * + * @param first The first expression parameter + * @param second The second expression parameter + * @param result The expected result + */ + public PlusExpressionTest(final NumberExpression first, final NumberExpression second, final int result) { + super(first, second, result, "+", PlusExpression::new); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/AppTest.java new file mode 100644 index 0000000000..75cad3ced7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.iterator; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java new file mode 100644 index 0000000000..196e082162 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/iterator/src/test/java/com/iluwatar/iterator/TreasureChestTest.java @@ -0,0 +1,130 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.iterator; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +/** + * Date: 12/14/15 - 2:58 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class TreasureChestTest { + + /** + * Create a list of all expected items in the chest. + * + * @return The set of all expected items in the chest + */ + @Parameterized.Parameters + public static List data() { + final List parameters = new ArrayList<>(); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of courage")}); + parameters.add(new Object[]{new Item(ItemType.RING, "Ring of shadows")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of wisdom")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of blood")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Sword of silver +1")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of rust")}); + parameters.add(new Object[]{new Item(ItemType.POTION, "Potion of healing")}); + parameters.add(new Object[]{new Item(ItemType.RING, "Ring of armor")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Steel halberd")}); + parameters.add(new Object[]{new Item(ItemType.WEAPON, "Dagger of poison")}); + return parameters; + } + + /** + * One of the expected items in the chest + */ + private final Item expectedItem; + + /** + * Create a new test instance, test if the given expected item can be retrieved from the chest + * + * @param expectedItem One of the items that should be in the chest + */ + public TreasureChestTest(final Item expectedItem) { + this.expectedItem = expectedItem; + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link ItemIterator} + */ + @Test + public void testIterator() { + final TreasureChest chest = new TreasureChest(); + final ItemIterator iterator = chest.iterator(expectedItem.getType()); + assertNotNull(iterator); + + while (iterator.hasNext()) { + final Item item = iterator.next(); + assertNotNull(item); + assertEquals(this.expectedItem.getType(), item.getType()); + + final String name = item.toString(); + assertNotNull(name); + if (this.expectedItem.toString().equals(name)) { + return; + } + } + + fail("Expected to find item [" + this.expectedItem + "] using iterator, but we didn't."); + + } + + /** + * Test if the expected item can be retrieved from the chest using the {@link + * TreasureChest#getItems()} method + */ + @Test + public void testGetItems() throws Exception { + final TreasureChest chest = new TreasureChest(); + final List items = chest.getItems(); + assertNotNull(items); + + for (final Item item : items) { + assertNotNull(item); + assertNotNull(item.getType()); + assertNotNull(item.toString()); + + final boolean sameType = this.expectedItem.getType() == item.getType(); + final boolean sameName = this.expectedItem.toString().equals(item.toString()); + if (sameType && sameName) { + return; + } + } + + fail("Expected to find item [" + this.expectedItem + "] in the item list, but we didn't."); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/AppTest.java new file mode 100644 index 0000000000..841d0ecb53 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java new file mode 100644 index 0000000000..abefc9f2cb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingExceptionTest.java @@ -0,0 +1,52 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * Date: 12/15/15 - 7:57 PM + * + * @author Jeroen Meulemeester + */ +public class CakeBakingExceptionTest { + + @Test + public void testConstructor() throws Exception { + final CakeBakingException exception = new CakeBakingException(); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testConstructorWithMessage() throws Exception { + final String expectedMessage = "message"; + final CakeBakingException exception = new CakeBakingException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java new file mode 100644 index 0000000000..1c6eb15173 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeBakingServiceImplTest.java @@ -0,0 +1,181 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/15/15 - 9:55 PM + * + * @author Jeroen Meulemeester + */ +public class CakeBakingServiceImplTest { + + @Test + public void testLayers() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialLayers = service.getAvailableLayers(); + assertNotNull(initialLayers); + assertTrue(initialLayers.isEmpty()); + + service.saveNewLayer(new CakeLayerInfo("Layer1", 1000)); + service.saveNewLayer(new CakeLayerInfo("Layer2", 2000)); + + final List availableLayers = service.getAvailableLayers(); + assertNotNull(availableLayers); + assertEquals(2, availableLayers.size()); + for (final CakeLayerInfo layer : availableLayers) { + assertNotNull(layer.id); + assertNotNull(layer.name); + assertNotNull(layer.toString()); + assertTrue(layer.calories > 0); + } + + } + + @Test + public void testToppings() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialToppings = service.getAvailableToppings(); + assertNotNull(initialToppings); + assertTrue(initialToppings.isEmpty()); + + service.saveNewTopping(new CakeToppingInfo("Topping1", 1000)); + service.saveNewTopping(new CakeToppingInfo("Topping2", 2000)); + + final List availableToppings = service.getAvailableToppings(); + assertNotNull(availableToppings); + assertEquals(2, availableToppings.size()); + for (final CakeToppingInfo topping : availableToppings) { + assertNotNull(topping.id); + assertNotNull(topping.name); + assertNotNull(topping.toString()); + assertTrue(topping.calories > 0); + } + + } + + @Test + public void testBakeCakes() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); + service.saveNewTopping(topping1); + service.saveNewTopping(topping2); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + final CakeLayerInfo layer3 = new CakeLayerInfo("Layer3", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + service.saveNewLayer(layer3); + + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3))); + + final List allCakes = service.getAllCakes(); + assertNotNull(allCakes); + assertEquals(2, allCakes.size()); + for (final CakeInfo cakeInfo : allCakes) { + assertNotNull(cakeInfo.id); + assertNotNull(cakeInfo.cakeToppingInfo); + assertNotNull(cakeInfo.cakeLayerInfos); + assertNotNull(cakeInfo.toString()); + assertFalse(cakeInfo.cakeLayerInfos.isEmpty()); + assertTrue(cakeInfo.calculateTotalCalories() > 0); + } + + } + + @Test(expected = CakeBakingException.class) + public void testBakeCakeMissingTopping() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + + final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000); + service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2))); + } + + @Test(expected = CakeBakingException.class) + public void testBakeCakeMissingLayer() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + service.saveNewTopping(topping1); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + service.saveNewLayer(layer1); + + final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000); + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer))); + + } + + @Test(expected = CakeBakingException.class) + public void testBakeCakesUsedLayer() throws CakeBakingException { + final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); + + final List initialCakes = service.getAllCakes(); + assertNotNull(initialCakes); + assertTrue(initialCakes.isEmpty()); + + final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000); + final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000); + service.saveNewTopping(topping1); + service.saveNewTopping(topping2); + + final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); + final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000); + service.saveNewLayer(layer1); + service.saveNewLayer(layer2); + + service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2))); + service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2))); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeTest.java new file mode 100644 index 0000000000..f43f5508fc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeTest.java @@ -0,0 +1,119 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/15/15 - 8:02 PM + * + * @author Jeroen Meulemeester + */ +public class CakeTest { + + @Test + public void testSetId() { + final Cake cake = new Cake(); + assertNull(cake.getId()); + + final Long expectedId = Long.valueOf(1234L); + cake.setId(expectedId); + assertEquals(expectedId, cake.getId()); + } + + @Test + public void testSetTopping() { + final Cake cake = new Cake(); + assertNull(cake.getTopping()); + + final CakeTopping expectedTopping = new CakeTopping("DummyTopping", 1000); + cake.setTopping(expectedTopping); + assertEquals(expectedTopping, cake.getTopping()); + } + + @Test + public void testSetLayers() { + final Cake cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final Set expectedLayers = new HashSet<>(); + expectedLayers.add(new CakeLayer("layer1", 1000)); + expectedLayers.add(new CakeLayer("layer2", 2000)); + expectedLayers.add(new CakeLayer("layer3", 3000)); + + cake.setLayers(expectedLayers); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + public void testAddLayer() { + final Cake cake = new Cake(); + assertNotNull(cake.getLayers()); + assertTrue(cake.getLayers().isEmpty()); + + final Set initialLayers = new HashSet<>(); + initialLayers.add(new CakeLayer("layer1", 1000)); + initialLayers.add(new CakeLayer("layer2", 2000)); + + cake.setLayers(initialLayers); + assertEquals(initialLayers, cake.getLayers()); + + final CakeLayer newLayer = new CakeLayer("layer3", 3000); + cake.addLayer(newLayer); + + final Set expectedLayers = new HashSet<>(); + expectedLayers.addAll(initialLayers); + expectedLayers.addAll(initialLayers); + expectedLayers.add(newLayer); + assertEquals(expectedLayers, cake.getLayers()); + } + + @Test + public void testToString() { + final CakeTopping topping = new CakeTopping("topping", 20); + topping.setId(2345L); + + final CakeLayer layer = new CakeLayer("layer", 100); + layer.setId(3456L); + + final Cake cake = new Cake(); + cake.setId(1234L); + cake.setTopping(topping); + cake.addLayer(layer); + + final String expected = "id=1234 topping=id=2345 name=topping calories=20 " + + "layers=[id=3456 name=layer calories=100]"; + assertEquals(expected, cake.toString()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java new file mode 100644 index 0000000000..8a62e074ba --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/layers/src/test/java/com/iluwatar/layers/CakeViewImplTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.layers; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +/** + * Date: 12/15/15 - 10:04 PM + * + * @author Jeroen Meulemeester + */ +public class CakeViewImplTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(CakeViewImpl.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Verify if the cake view renders the expected result + */ + @Test + public void testRender() { + + final List layers = new ArrayList<>(); + layers.add(new CakeLayerInfo("layer1", 1000)); + layers.add(new CakeLayerInfo("layer2", 2000)); + layers.add(new CakeLayerInfo("layer3", 3000)); + + final List cakes = new ArrayList<>(); + final CakeInfo cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers); + cakes.add(cake); + + final CakeBakingService bakingService = mock(CakeBakingService.class); + when(bakingService.getAllCakes()).thenReturn(cakes); + + final CakeViewImpl cakeView = new CakeViewImpl(bakingService); + + assertEquals(0, appender.getLogSize()); + + cakeView.render(); + assertEquals(cake.toString(), appender.getLastMessage()); + + } + + private class InMemoryAppender extends AppenderBase { + + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java new file mode 100644 index 0000000000..917ccb8d3a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AbstractHolderTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.lazy.loading; + +import org.junit.Test; + +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertSame; +import static junit.framework.TestCase.assertNull; + +/** + * Date: 12/19/15 - 11:58 AM + * + * @author Jeroen Meulemeester + */ +public abstract class AbstractHolderTest { + + /** + * Get the internal state of the holder value + * + * @return The internal value + */ + abstract Heavy getInternalHeavyValue() throws Exception; + + /** + * Request a lazy loaded {@link Heavy} object from the holder. + * + * @return The lazy loaded {@link Heavy} object + */ + abstract Heavy getHeavy() throws Exception; + + /** + * This test shows that the heavy field is not instantiated until the method getHeavy is called + */ + @Test(timeout = 3000) + public void testGetHeavy() throws Exception { + assertNull(getInternalHeavyValue()); + assertNotNull(getHeavy()); + assertNotNull(getInternalHeavyValue()); + assertSame(getHeavy(), getInternalHeavyValue()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java new file mode 100644 index 0000000000..cefa9918ac --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/lazy-loading/src/test/java/com/iluwatar/lazy/loading/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.lazy.loading; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/AppTest.java new file mode 100644 index 0000000000..85fb61b16d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/AppTest.java @@ -0,0 +1,35 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/GuardTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/GuardTest.java new file mode 100644 index 0000000000..eb3a4b7571 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/GuardTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertThat; + +/** + * Guard test + */ +public class GuardTest { + + @Test + public void testGuard() { + Guard guard = new Guard(); + assertThat(guard, instanceOf(Permission.class)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/ThiefTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/ThiefTest.java new file mode 100644 index 0000000000..f950809cc3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/marker/src/test/java/ThiefTest.java @@ -0,0 +1,36 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +import org.junit.Test; + +import static org.junit.Assert.assertFalse; + +/** + * Thief test + */ +public class ThiefTest { + @Test + public void testThief() { + Thief thief = new Thief(); + assertFalse(thief instanceof Permission); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/AppTest.java new file mode 100644 index 0000000000..d92b8969bd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java new file mode 100644 index 0000000000..bb3c51474e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyImplTest.java @@ -0,0 +1,63 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/19/15 - 10:00 PM + * + * @author Jeroen Meulemeester + */ +public class PartyImplTest { + + /** + * Verify if a member is notified when it's joining a party. Generate an action and see if the + * other member gets it. Also check members don't get their own actions. + */ + @Test + public void testPartyAction() { + final PartyMember partyMember1 = mock(PartyMember.class); + final PartyMember partyMember2 = mock(PartyMember.class); + + final PartyImpl party = new PartyImpl(); + party.addMember(partyMember1); + party.addMember(partyMember2); + + verify(partyMember1).joinedParty(party); + verify(partyMember2).joinedParty(party); + + party.act(partyMember1, Action.GOLD); + verifyZeroInteractions(partyMember1); + verify(partyMember2).partyAction(Action.GOLD); + + verifyNoMoreInteractions(partyMember1, partyMember2); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java new file mode 100644 index 0000000000..4d578c3333 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mediator/src/test/java/com/iluwatar/mediator/PartyMemberTest.java @@ -0,0 +1,160 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mediator; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Supplier; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +/** + * Date: 12/19/15 - 10:13 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class PartyMemberTest { + + @Parameterized.Parameters + public static Collection[]> data() { + return Arrays.asList( + new Supplier[]{Hobbit::new}, + new Supplier[]{Hunter::new}, + new Supplier[]{Rogue::new}, + new Supplier[]{Wizard::new} + ); + } + + /** + * The factory, used to create a new instance of the tested party member + */ + private final Supplier memberSupplier; + + /** + * Create a new test instance, using the given {@link PartyMember} factory + * + * @param memberSupplier The party member factory + */ + public PartyMemberTest(final Supplier memberSupplier) { + this.memberSupplier = memberSupplier; + } + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(PartyMemberBase.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Verify if a party action triggers the correct output to the std-Out + */ + @Test + public void testPartyAction() { + final PartyMember member = this.memberSupplier.get(); + + for (final Action action : Action.values()) { + member.partyAction(action); + assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage()); + } + + assertEquals(Action.values().length, appender.getLogSize()); + } + + /** + * Verify if a member action triggers the expected interactions with the party class + */ + @Test + public void testAct() { + final PartyMember member = this.memberSupplier.get(); + + member.act(Action.GOLD); + assertEquals(0, appender.getLogSize()); + + final Party party = mock(Party.class); + member.joinedParty(party); + assertEquals(member.toString() + " joins the party", appender.getLastMessage()); + + for (final Action action : Action.values()) { + member.act(action); + assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage()); + verify(party).act(member, action); + } + + assertEquals(Action.values().length + 1, appender.getLogSize()); + } + + /** + * Verify if {@link PartyMember#toString()} generate the expected output + */ + @Test + public void testToString() throws Exception { + final PartyMember member = this.memberSupplier.get(); + final Class memberClass = member.getClass(); + assertEquals(memberClass.getSimpleName(), member.toString()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/AppTest.java new file mode 100644 index 0000000000..b987571229 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.memento; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/StarTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/StarTest.java new file mode 100644 index 0000000000..2a7efc70f5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/memento/src/test/java/com/iluwatar/memento/StarTest.java @@ -0,0 +1,97 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.memento; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/20/15 - 10:08 AM + * + * @author Jeroen Meulemeester + */ +public class StarTest { + + /** + * Verify the stages of a dying sun, without going back in time + */ + @Test + public void testTimePasses() { + final Star star = new Star(StarType.SUN, 1, 2); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + star.timePasses(); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.timePasses(); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 16 years mass: 8192 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 64 years mass: 0 tons", star.toString()); + + star.timePasses(); + assertEquals("dead star age: 256 years mass: 0 tons", star.toString()); + } + + /** + * Verify some stage of a dying sun, but go back in time to test the memento + */ + @Test + public void testSetMemento() { + final Star star = new Star(StarType.SUN, 1, 2); + final StarMemento firstMemento = star.getMemento(); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + star.timePasses(); + final StarMemento secondMemento = star.getMemento(); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.timePasses(); + final StarMemento thirdMemento = star.getMemento(); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.setMemento(thirdMemento); + assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString()); + + star.timePasses(); + assertEquals("supernova age: 8 years mass: 1024 tons", star.toString()); + + star.setMemento(secondMemento); + assertEquals("red giant age: 2 years mass: 16 tons", star.toString()); + + star.setMemento(firstMemento); + assertEquals("sun age: 1 years mass: 2 tons", star.toString()); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java new file mode 100644 index 0000000000..e41977a000 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/message-channel/src/test/java/com/iluwatar/message/channel/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.message.channel; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java new file mode 100644 index 0000000000..66062faf52 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java new file mode 100644 index 0000000000..ab9b3e0a4d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantControllerTest.java @@ -0,0 +1,122 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/20/15 - 2:19 PM + * + * @author Jeroen Meulemeester + */ +public class GiantControllerTest { + + /** + * Verify if the controller passes the health level through to the model and vice versa + */ + @Test + public void testSetHealth() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Health health : Health.values()) { + controller.setHealth(health); + verify(model).setHealth(health); + verifyZeroInteractions(view); + } + + controller.getHealth(); + verify(model).getHealth(); + + verifyNoMoreInteractions(model, view); + } + + /** + * Verify if the controller passes the fatigue level through to the model and vice versa + */ + @Test + public void testSetFatigue() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Fatigue fatigue : Fatigue.values()) { + controller.setFatigue(fatigue); + verify(model).setFatigue(fatigue); + verifyZeroInteractions(view); + } + + controller.getFatigue(); + verify(model).getFatigue(); + + verifyNoMoreInteractions(model, view); + } + + /** + * Verify if the controller passes the nourishment level through to the model and vice versa + */ + @Test + public void testSetNourishment() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + for (final Nourishment nourishment : Nourishment.values()) { + controller.setNourishment(nourishment); + verify(model).setNourishment(nourishment); + verifyZeroInteractions(view); + } + + controller.getNourishment(); + verify(model).getNourishment(); + + verifyNoMoreInteractions(model, view); + } + + @Test + public void testUpdateView() { + final GiantModel model = mock(GiantModel.class); + final GiantView view = mock(GiantView.class); + final GiantController controller = new GiantController(model, view); + + verifyZeroInteractions(model, view); + + controller.updateView(); + verify(view).displayGiant(model); + + verifyNoMoreInteractions(model, view); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java new file mode 100644 index 0000000000..ecf713a611 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantModelTest.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/20/15 - 2:10 PM + * + * @author Jeroen Meulemeester + */ +public class GiantModelTest { + + /** + * Verify if the health value is set properly though the constructor and setter + */ + @Test + public void testSetHealth() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Health.HEALTHY, model.getHealth()); + for (final Health health : Health.values()) { + model.setHealth(health); + assertEquals(health, model.getHealth()); + assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString()); + } + } + + /** + * Verify if the fatigue level is set properly though the constructor and setter + */ + @Test + public void testSetFatigue() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Fatigue.ALERT, model.getFatigue()); + for (final Fatigue fatigue : Fatigue.values()) { + model.setFatigue(fatigue); + assertEquals(fatigue, model.getFatigue()); + assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString()); + } + } + + /** + * Verify if the nourishment level is set properly though the constructor and setter + */ + @Test + public void testSetNourishment() { + final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED); + assertEquals(Nourishment.SATURATED, model.getNourishment()); + for (final Nourishment nourishment : Nourishment.values()) { + model.setNourishment(nourishment); + assertEquals(nourishment, model.getNourishment()); + assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java new file mode 100644 index 0000000000..ec0aabd152 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-controller/src/test/java/com/iluwatar/model/view/controller/GiantViewTest.java @@ -0,0 +1,96 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.controller; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/20/15 - 2:04 PM + * + * @author Jeroen Meulemeester + */ +public class GiantViewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(GiantView.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Verify if the {@link GiantView} does what it has to do: Print the {@link GiantModel} to the + * standard out stream, nothing more, nothing less. + */ + @Test + public void testDisplayGiant() { + final GiantView view = new GiantView(); + + final GiantModel model = mock(GiantModel.class); + view.displayGiant(model); + + assertEquals(model.toString(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getMessage(); + } + + public int getLogSize() { + return log.size(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java new file mode 100644 index 0000000000..83639c0b20 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java new file mode 100644 index 0000000000..8e9a558a75 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileLoaderTest.java @@ -0,0 +1,43 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import org.junit.Test; + +import static org.junit.Assert.assertNull; + +/** + * Date: 12/21/15 - 12:12 PM + * + * @author Jeroen Meulemeester + */ +public class FileLoaderTest { + + @Test + public void testLoadData() throws Exception { + final FileLoader fileLoader = new FileLoader(); + fileLoader.setFileName("non-existing-file"); + assertNull(fileLoader.loadData()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java new file mode 100644 index 0000000000..057d4dcdc4 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/model-view-presenter/src/test/java/com/iluwatar/model/view/presenter/FileSelectorPresenterTest.java @@ -0,0 +1,145 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.model.view.presenter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +/** + * This test case is responsible for testing our application by taking advantage of the + * Model-View-Controller architectural pattern. + */ +public class FileSelectorPresenterTest { + + /** + * The Presenter component. + */ + private FileSelectorPresenter presenter; + + /** + * The View component, implemented this time as a Stub!!! + */ + private FileSelectorStub stub; + + /** + * The Model component. + */ + private FileLoader loader; + + /** + * Initializes the components of the test case. + */ + @Before + public void setUp() { + this.stub = new FileSelectorStub(); + this.loader = new FileLoader(); + presenter = new FileSelectorPresenter(this.stub); + presenter.setLoader(loader); + } + + /** + * Tests if the Presenter was successfully connected with the View. + */ + @Test + public void wiring() { + presenter.start(); + + assertNotNull(stub.getPresenter()); + assertTrue(stub.isOpened()); + } + + /** + * Tests if the name of the file changes. + */ + @Test + public void updateFileNameToLoader() { + String expectedFile = "Stamatis"; + stub.setFileName(expectedFile); + + presenter.start(); + presenter.fileNameChanged(); + + assertEquals(expectedFile, loader.getFileName()); + } + + /** + * Tests if we receive a confirmation when we attempt to open a file that it's name is null or an + * empty string. + */ + @Test + public void fileConfirmationWhenNameIsNull() { + stub.setFileName(null); + + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertFalse(loader.isLoaded()); + assertEquals(1, stub.getMessagesSent()); + } + + /** + * Tests if we receive a confirmation when we attempt to open a file that it doesn't exist. + */ + @Test + public void fileConfirmationWhenFileDoesNotExist() { + stub.setFileName("RandomName.txt"); + + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertFalse(loader.isLoaded()); + assertEquals(1, stub.getMessagesSent()); + } + + /** + * Tests if we can open the file, when it exists. + */ + @Test + public void fileConfirmationWhenFileExists() { + stub.setFileName("etc/data/test.txt"); + presenter.start(); + presenter.fileNameChanged(); + presenter.confirmed(); + + assertTrue(loader.isLoaded()); + assertTrue(stub.dataDisplayed()); + } + + /** + * Tests if the view closes after cancellation. + */ + @Test + public void cancellation() { + presenter.start(); + presenter.cancelled(); + + assertFalse(stub.isOpened()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/AppTest.java new file mode 100644 index 0000000000..5df6ab0f38 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.module; + +import java.io.FileNotFoundException; + +import com.iluwatar.module.App; + +import org.junit.Test; + +/** + * Tests that Module example runs without errors. + */ +public final class AppTest { + + @Test + public void test() throws FileNotFoundException { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java new file mode 100644 index 0000000000..7274aab14e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/module/src/test/java/com/iluwatar/module/FileLoggerModuleTest.java @@ -0,0 +1,182 @@ +/** + * The MIT License Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + * associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT + * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.iluwatar.module; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import org.apache.log4j.Logger; +import org.junit.Test; + +/** + * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages + * the creation and organization of other elements, and groups them as the structural pattern does. + * An object that applies this pattern can provide the equivalent of a namespace, providing the + * initialization and finalization process of a static class or a class with static members with + * cleaner, more concise syntax and semantics. + *

+ * The below example demonstrates a JUnit test for testing two different modules: File Logger and + * Console Logger + */ +public final class FileLoggerModuleTest { + + private static final Logger LOGGER = Logger.getLogger(FileLoggerModuleTest.class); + + private static final String OUTPUT_FILE = "output.txt"; + private static final String ERROR_FILE = "error.txt"; + + private static final String MESSAGE = "MESSAGE"; + private static final String ERROR = "ERROR"; + + + /** + * This test verify that 'MESSAGE' is perfectly printed in output file + * + * @throws IOException if program is not able to find log files (output.txt and error.txt) + */ + @Test + public void testFileMessage() throws IOException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Print 'Message' in file */ + fileLoggerModule.printString(MESSAGE); + + /* Test if 'Message' is printed in file */ + assertEquals(readFirstLine(OUTPUT_FILE), MESSAGE); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that nothing is printed in output file + * + * @throws IOException if program is not able to find log files (output.txt and error.txt) + */ + @Test + public void testNoFileMessage() throws IOException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Test if nothing is printed in file */ + assertEquals(readFirstLine(OUTPUT_FILE), null); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that 'ERROR' is perfectly printed in error file + * + * @throws FileNotFoundException if program is not able to find log files (output.txt and + * error.txt) + */ + @Test + public void testFileErrorMessage() throws FileNotFoundException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Print 'Error' in file */ + fileLoggerModule.printErrorString(ERROR); + + /* Test if 'Message' is printed in file */ + assertEquals(readFirstLine(ERROR_FILE), ERROR); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * This test verify that nothing is printed in error file + * + * @throws FileNotFoundException if program is not able to find log files (output.txt and + * error.txt) + */ + @Test + public void testNoFileErrorMessage() throws FileNotFoundException { + + /* Get singletong instance of File Logger Module */ + final FileLoggerModule fileLoggerModule = FileLoggerModule.getSingleton(); + + /* Prepare the essential sub modules, to perform the sequence of jobs */ + fileLoggerModule.prepare(); + + /* Test if nothing is printed in file */ + assertEquals(readFirstLine(ERROR_FILE), null); + + /* Unprepare to cleanup the modules */ + fileLoggerModule.unprepare(); + } + + /** + * Utility method to read first line of a file + * + * @param file as file name to be read + * @return a string value as first line in file + */ + private static final String readFirstLine(final String file) { + + String firstLine = null; + BufferedReader bufferedReader = null; + try { + + /* Create a buffered reader */ + bufferedReader = new BufferedReader(new FileReader(file)); + + while (bufferedReader.ready()) { + + /* Read the line */ + firstLine = bufferedReader.readLine(); + } + + LOGGER.info("ModuleTest::readFirstLine() : firstLine : " + firstLine); + + } catch (final IOException e) { + LOGGER.error("ModuleTest::readFirstLine()", e); + } finally { + + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (final IOException e) { + LOGGER.error("ModuleTest::readFirstLine()", e); + } + } + } + + return firstLine; + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/AppTest.java new file mode 100644 index 0000000000..69464ff87d --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + +import org.junit.Test; + +/** + * Application Test + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/MonadTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/MonadTest.java new file mode 100644 index 0000000000..a342439788 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monad/src/test/java/com/iluwatar/monad/MonadTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monad; + + +import junit.framework.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Objects; + +/** + * Test for Monad Pattern + */ +public class MonadTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void testForInvalidName() { + thrown.expect(IllegalStateException.class); + User tom = new User(null, 21, Sex.MALE, "tom@foo.bar"); + Validator.of(tom).validate(User::getName, Objects::nonNull, "name cannot be null").get(); + } + + @Test + public void testForInvalidAge() { + thrown.expect(IllegalStateException.class); + User john = new User("John", 17, Sex.MALE, "john@qwe.bar"); + Validator.of(john).validate(User::getName, Objects::nonNull, "name cannot be null") + .validate(User::getAge, age -> age > 21, "user is underaged") + .get(); + } + + @Test + public void testForValid() { + User sarah = new User("Sarah", 42, Sex.FEMALE, "sarah@det.org"); + User validated = Validator.of(sarah).validate(User::getName, Objects::nonNull, "name cannot be null") + .validate(User::getAge, age -> age > 21, "user is underaged") + .validate(User::getSex, sex -> sex == Sex.FEMALE, "user is not female") + .validate(User::getEmail, email -> email.contains("@"), "email does not contain @ sign") + .get(); + Assert.assertSame(validated, sarah); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/AppTest.java new file mode 100644 index 0000000000..3e88b3bf28 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monostate; + +import org.junit.Test; + +/** + * Application Test Entry + */ +public class AppTest { + + @Test + public void testMain() { + String[] args = {}; + App.main(args); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java new file mode 100644 index 0000000000..96b4830c78 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/monostate/src/test/java/com/iluwatar/monostate/LoadBalancerTest.java @@ -0,0 +1,71 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.monostate; + +import org.junit.Assert; +import org.junit.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +/** + * Date: 12/21/15 - 12:26 PM + * + * @author Jeroen Meulemeester + */ +public class LoadBalancerTest { + + @Test + public void testSameStateAmongstAllInstances() { + final LoadBalancer firstBalancer = new LoadBalancer(); + final LoadBalancer secondBalancer = new LoadBalancer(); + firstBalancer.addServer(new Server("localhost", 8085, 6)); + // Both should have the same number of servers. + Assert.assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers()); + // Both Should have the same LastServedId + Assert.assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId()); + } + + @Test + public void testServe() { + final Server server = mock(Server.class); + when(server.getHost()).thenReturn("testhost"); + when(server.getPort()).thenReturn(1234); + doNothing().when(server).serve(any(Request.class)); + + final LoadBalancer loadBalancer = new LoadBalancer(); + loadBalancer.addServer(server); + + verifyZeroInteractions(server); + + final Request request = new Request("test"); + for (int i = 0; i < loadBalancer.getNoOfServers() * 2; i++) { + loadBalancer.serverRequest(request); + } + + verify(server, times(2)).serve(request); + verifyNoMoreInteractions(server); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/AppTest.java new file mode 100644 index 0000000000..370a2665b3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.multiton; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java new file mode 100644 index 0000000000..ad10a9eb0e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/multiton/src/test/java/com/iluwatar/multiton/NazgulTest.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.multiton; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +/** + * Date: 12/22/15 - 22:28 AM + * + * @author Jeroen Meulemeester + */ +public class NazgulTest { + + /** + * Verify if {@link Nazgul#getInstance(NazgulName)} returns the correct Nazgul multiton instance + */ + @Test + public void testGetInstance() { + for (final NazgulName name : NazgulName.values()) { + final Nazgul nazgul = Nazgul.getInstance(name); + assertNotNull(nazgul); + assertSame(nazgul, Nazgul.getInstance(name)); + assertEquals(name, nazgul.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java new file mode 100644 index 0000000000..8534ff2ad1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.mute; + +import org.junit.Test; + +/** + * Tests that Mute idiom example runs without errors. + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java new file mode 100644 index 0000000000..7e1d2e1afb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mute-idiom/src/test/java/com/iluwatar/mute/MuteTest.java @@ -0,0 +1,85 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.mute; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test for the mute-idiom pattern + */ +public class MuteTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(MuteTest.class); + + private static final String MESSAGE = "should not occur"; + + @Rule public ExpectedException exception = ExpectedException.none(); + + @Test + public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + Mute.mute(() -> methodNotThrowingAnyException()); + } + + @Test + public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception { + exception.expect(AssertionError.class); + exception.expectMessage(MESSAGE); + + Mute.mute(() -> methodThrowingException()); + } + + @Test + public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { + Mute.loggedMute(() -> methodNotThrowingAnyException()); + } + + @Test + public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(stream)); + + Mute.loggedMute(() -> methodThrowingException()); + + assertTrue(new String(stream.toByteArray()).contains(MESSAGE)); + } + + + private void methodNotThrowingAnyException() { + LOGGER.info("Executed successfully"); + } + + private void methodThrowingException() throws Exception { + throw new Exception(MESSAGE); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/AppTest.java new file mode 100644 index 0000000000..530db835d9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.Test; +import java.io.IOException; + +/** + * Application Test Entrypoint + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/JarTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/JarTest.java new file mode 100644 index 0000000000..b9e0c52cab --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/JarTest.java @@ -0,0 +1,43 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Test case for taking beans from a Jar + */ +public class JarTest { + + @Test + public void testTakeBeans() { + Mutex mutex = new Mutex(); + Jar jar = new Jar(10, mutex); + for (int i = 0; i < 10; i++) { + assertTrue(jar.takeBean()); + } + assertFalse(jar.takeBean()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java new file mode 100644 index 0000000000..93649002f7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/mutex/src/test/java/com/iluwatar/mutex/MutexTest.java @@ -0,0 +1,47 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.mutex; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Test case for acquiring and releasing a Mutex + */ +public class MutexTest { + + @Test + public void acquireReleaseTest() { + Mutex mutex = new Mutex(); + assertNull(mutex.getOwner()); + try { + mutex.acquire(); + assertEquals(mutex.getOwner(), Thread.currentThread()); + } catch (InterruptedException e) { + fail(e.toString()); + } + mutex.release(); + assertNull(mutex.getOwner()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java new file mode 100644 index 0000000000..13e92034a2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java new file mode 100644 index 0000000000..778344e067 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/NullNodeTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Date: 12/26/15 - 11:47 PM + * + * @author Jeroen Meulemeester + */ +public class NullNodeTest { + + /** + * Verify if {@link NullNode#getInstance()} actually returns the same object instance + */ + @Test + public void testGetInstance() { + final NullNode instance = NullNode.getInstance(); + assertNotNull(instance); + assertSame(instance, NullNode.getInstance()); + } + + @Test + public void testFields() { + final NullNode node = NullNode.getInstance(); + assertEquals(0, node.getTreeSize()); + assertNull(node.getName()); + assertNull(node.getLeft()); + assertNull(node.getRight()); + } + + @Test + public void testWalk() throws Exception { + NullNode.getInstance().walk(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java new file mode 100644 index 0000000000..6a683a60e5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/null-object/src/test/java/com/iluwatar/nullobject/TreeTest.java @@ -0,0 +1,161 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.nullobject; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.*; + +/** + * Date: 12/26/15 - 11:44 PM + * + * @author Jeroen Meulemeester + */ +public class TreeTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * During the tests, the same tree structure will be used, shown below. End points will be + * terminated with the {@link NullNode} instance. + * + *

+   * root
+   * ├── level1_a
+   * │   ├── level2_a
+   * │   │   ├── level3_a
+   * │   │   └── level3_b
+   * │   └── level2_b
+   * └── level1_b
+   * 
+ */ + private static final Node TREE_ROOT; + + static { + final NodeImpl level1B = new NodeImpl("level1_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level2B = new NodeImpl("level2_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level3A = new NodeImpl("level3_a", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level3B = new NodeImpl("level3_b", NullNode.getInstance(), NullNode.getInstance()); + final NodeImpl level2A = new NodeImpl("level2_a", level3A, level3B); + final NodeImpl level1A = new NodeImpl("level1_a", level2A, level2B); + TREE_ROOT = new NodeImpl("root", level1A, level1B); + } + + /** + * Verify the number of items in the tree. The root has 6 children so we expect a {@link + * Node#getTreeSize()} of 7 {@link Node}s in total. + */ + @Test + public void testTreeSize() { + assertEquals(7, TREE_ROOT.getTreeSize()); + } + + /** + * Walk through the tree and verify if every item is handled + */ + @Test + public void testWalk() { + TREE_ROOT.walk(); + + assertTrue(appender.logContains("root")); + assertTrue(appender.logContains("level1_a")); + assertTrue(appender.logContains("level2_a")); + assertTrue(appender.logContains("level3_a")); + assertTrue(appender.logContains("level3_b")); + assertTrue(appender.logContains("level2_b")); + assertTrue(appender.logContains("level1_b")); + assertEquals(7, appender.getLogSize()); + } + + @Test + public void testGetLeft() throws Exception { + final Node level1 = TREE_ROOT.getLeft(); + assertNotNull(level1); + assertEquals("level1_a", level1.getName()); + assertEquals(5, level1.getTreeSize()); + + final Node level2 = level1.getLeft(); + assertNotNull(level2); + assertEquals("level2_a", level2.getName()); + assertEquals(3, level2.getTreeSize()); + + final Node level3 = level2.getLeft(); + assertNotNull(level3); + assertEquals("level3_a", level3.getName()); + assertEquals(1, level3.getTreeSize()); + assertSame(NullNode.getInstance(), level3.getRight()); + assertSame(NullNode.getInstance(), level3.getLeft()); + } + + @Test + public void testGetRight() throws Exception { + final Node level1 = TREE_ROOT.getRight(); + assertNotNull(level1); + assertEquals("level1_b", level1.getName()); + assertEquals(1, level1.getTreeSize()); + assertSame(NullNode.getInstance(), level1.getRight()); + assertSame(NullNode.getInstance(), level1.getLeft()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java new file mode 100644 index 0000000000..cc5af45aab --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-mother/src/test/java/com/iluwatar/objectmother/test/RoyaltyObjectMotherTest.java @@ -0,0 +1,92 @@ +/** + * The MIT License + * Copyright (c) 2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.objectmother.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.iluwatar.objectmother.King; +import com.iluwatar.objectmother.Queen; +import com.iluwatar.objectmother.Royalty; +import com.iluwatar.objectmother.RoyaltyObjectMother; + +/** + * Test Generation of Royalty Types using the object-mother + */ +public class RoyaltyObjectMotherTest { + + @Test + public void unsuccessfulKingFlirt() { + King soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing(); + Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + soberUnhappyKing.flirt(flirtyQueen); + assertFalse(soberUnhappyKing.isHappy()); + } + + @Test + public void queenIsBlockingFlirtCauseDrunkKing() { + King drunkUnhappyKing = RoyaltyObjectMother.createDrunkKing(); + Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + drunkUnhappyKing.flirt(notFlirtyQueen); + assertFalse(drunkUnhappyKing.isHappy()); + } + + @Test + public void queenIsBlockingFlirt() { + King soberHappyKing = RoyaltyObjectMother.createHappyKing(); + Queen notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + soberHappyKing.flirt(notFlirtyQueen); + assertFalse(soberHappyKing.isHappy()); + } + + @Test + public void successfullKingFlirt() { + King soberHappyKing = RoyaltyObjectMother.createHappyKing(); + Queen flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + soberHappyKing.flirt(flirtyQueen); + assertTrue(soberHappyKing.isHappy()); + } + + @Test + public void testQueenType() { + Royalty flirtyQueen = RoyaltyObjectMother.createFlirtyQueen(); + Royalty notFlirtyQueen = RoyaltyObjectMother.createNotFlirtyQueen(); + assertEquals(flirtyQueen.getClass(), Queen.class); + assertEquals(notFlirtyQueen.getClass(), Queen.class); + } + + @Test + public void testKingType() { + Royalty drunkKing = RoyaltyObjectMother.createDrunkKing(); + Royalty happyDrunkKing = RoyaltyObjectMother.createHappyDrunkKing(); + Royalty happyKing = RoyaltyObjectMother.createHappyKing(); + Royalty soberUnhappyKing = RoyaltyObjectMother.createSoberUnhappyKing(); + assertEquals(drunkKing.getClass(), King.class); + assertEquals(happyDrunkKing.getClass(), King.class); + assertEquals(happyKing.getClass(), King.class); + assertEquals(soberUnhappyKing.getClass(), King.class); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java new file mode 100644 index 0000000000..c92399c32e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.object.pool; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java new file mode 100644 index 0000000000..46ed22b364 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/object-pool/src/test/java/com/iluwatar/object/pool/OliphauntPoolTest.java @@ -0,0 +1,121 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.object.pool; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/27/15 - 1:05 AM + * + * @author Jeroen Meulemeester + */ +public class OliphauntPoolTest { + + /** + * Use the same object 100 times subsequently. This should not take much time since the heavy + * object instantiation is done only once. Verify if we get the same object each time. + */ + @Test(timeout = 5000) + public void testSubsequentCheckinCheckout() { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); + + final Oliphaunt expectedOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + + pool.checkIn(expectedOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=0"); + + for (int i = 0; i < 100; i++) { + final Oliphaunt oliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + assertSame(expectedOliphaunt, oliphaunt); + assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); + assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); + + pool.checkIn(oliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=0"); + } + + } + + /** + * Use the same object 100 times subsequently. This should not take much time since the heavy + * object instantiation is done only once. Verify if we get the same object each time. + */ + @Test(timeout = 5000) + public void testConcurrentCheckinCheckout() { + final OliphauntPool pool = new OliphauntPool(); + assertEquals(pool.toString(), "Pool available=0 inUse=0"); + + final Oliphaunt firstOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=1"); + + final Oliphaunt secondOliphaunt = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + + assertNotSame(firstOliphaunt, secondOliphaunt); + assertEquals(firstOliphaunt.getId() + 1, secondOliphaunt.getId()); + + // After checking in the second, we should get the same when checking out a new oliphaunt ... + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + final Oliphaunt oliphaunt3 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(secondOliphaunt, oliphaunt3); + + // ... and the same applies for the first one + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + final Oliphaunt oliphaunt4 = pool.checkOut(); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertSame(firstOliphaunt, oliphaunt4); + + // When both oliphaunt return to the pool, we should still get the same instances + pool.checkIn(firstOliphaunt); + assertEquals(pool.toString(), "Pool available=1 inUse=1"); + + pool.checkIn(secondOliphaunt); + assertEquals(pool.toString(), "Pool available=2 inUse=0"); + + // The order of the returned instances is not determined, so just put them in a list + // and verify if both expected instances are in there. + final List oliphaunts = Arrays.asList(pool.checkOut(), pool.checkOut()); + assertEquals(pool.toString(), "Pool available=0 inUse=2"); + assertTrue(oliphaunts.contains(firstOliphaunt)); + assertTrue(oliphaunts.contains(secondOliphaunt)); + + } + + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/AppTest.java new file mode 100644 index 0000000000..11bbb5496f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java new file mode 100644 index 0000000000..31a4fd6670 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/HobbitsTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class HobbitsTest extends WeatherObserverTest { + + @Parameterized.Parameters + public static Collection data() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); + testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); + testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); + testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + * + * @param weather The weather that should be unleashed on the observer + * @param response The expected response from the observer + */ + public HobbitsTest(final WeatherType weather, final String response) { + super(weather, response, Hobbits::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/OrcsTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/OrcsTest.java new file mode 100644 index 0000000000..b1f0b82d75 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/OrcsTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class OrcsTest extends WeatherObserverTest { + + @Parameterized.Parameters + public static Collection data() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); + testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); + testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); + testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + * + * @param weather The weather that should be unleashed on the observer + * @param response The expected response from the observer + */ + public OrcsTest(final WeatherType weather, final String response) { + super(weather, response, Orcs::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java new file mode 100644 index 0000000000..70a7922c56 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherObserverTest.java @@ -0,0 +1,94 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import static org.junit.Assert.assertEquals; + +import com.iluwatar.observer.utils.InMemoryAppender; +import java.util.function.Supplier; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Date: 12/27/15 - 11:44 AM + * Weather Observer Tests + * @param Type of WeatherObserver + * @author Jeroen Meulemeester + */ +public abstract class WeatherObserverTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * The observer instance factory + */ + private final Supplier factory; + + /** + * The weather type currently tested + */ + private final WeatherType weather; + + /** + * The expected response from the observer + */ + private final String response; + + /** + * Create a new test instance using the given parameters + * + * @param weather The weather currently being tested + * @param response The expected response from the observer + * @param factory The factory, used to create an instance of the tested observer + */ + WeatherObserverTest(final WeatherType weather, final String response, final Supplier factory) { + this.weather = weather; + this.response = response; + this.factory = factory; + } + + /** + * Verify if the weather has the expected influence on the observer + */ + @Test + public void testObserver() { + final O observer = this.factory.get(); + assertEquals(0, appender.getLogSize()); + + observer.update(this.weather); + assertEquals(response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherTest.java new file mode 100644 index 0000000000..88bf1c4c35 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/WeatherTest.java @@ -0,0 +1,100 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer; + +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/27/15 - 11:08 AM + * + * @author Jeroen Meulemeester + */ +public class WeatherTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Weather.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the + * observer again and verify that there are no more notifications. + */ + @Test + public void testAddRemoveObserver() { + final WeatherObserver observer = mock(WeatherObserver.class); + + final Weather weather = new Weather(); + weather.addObserver(observer); + verifyZeroInteractions(observer); + + weather.timePasses(); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); + verify(observer).update(WeatherType.RAINY); + + weather.removeObserver(observer); + weather.timePasses(); + assertEquals("The weather changed to windy.", appender.getLastMessage()); + + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); + } + + /** + * Verify if the weather passes in the order of the {@link WeatherType}s + */ + @Test + public void testTimePasses() { + final WeatherObserver observer = mock(WeatherObserver.class); + final Weather weather = new Weather(); + weather.addObserver(observer); + + final InOrder inOrder = inOrder(observer); + final WeatherType[] weatherTypes = WeatherType.values(); + for (int i = 1; i < 20; i++) { + weather.timePasses(); + inOrder.verify(observer).update(weatherTypes[i % weatherTypes.length]); + } + + verifyNoMoreInteractions(observer); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java new file mode 100644 index 0000000000..a54f15689e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GHobbitsTest.java @@ -0,0 +1,64 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.Hobbits; +import com.iluwatar.observer.WeatherObserverTest; +import com.iluwatar.observer.WeatherType; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class GHobbitsTest extends ObserverTest { + + @Parameterized.Parameters + public static Collection data() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The happy hobbits bade in the warm sun."}); + testData.add(new Object[]{WeatherType.RAINY, "The hobbits look for cover from the rain."}); + testData.add(new Object[]{WeatherType.WINDY, "The hobbits hold their hats tightly in the windy weather."}); + testData.add(new Object[]{WeatherType.COLD, "The hobbits are shivering in the cold weather."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + * + * @param weather The weather that should be unleashed on the observer + * @param response The expected response from the observer + */ + public GHobbitsTest(final WeatherType weather, final String response) { + super(weather, response, GHobbits::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java new file mode 100644 index 0000000000..ab15ca884b --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/GWeatherTest.java @@ -0,0 +1,98 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherObserver; +import com.iluwatar.observer.WeatherType; +import com.iluwatar.observer.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +/** + * Date: 12/27/15 - 11:08 AM + * + * @author Jeroen Meulemeester + */ +public class GWeatherTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(GWeather.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the + * observer again and verify that there are no more notifications. + */ + @Test + public void testAddRemoveObserver() { + final Race observer = mock(Race.class); + + final GWeather weather = new GWeather(); + weather.addObserver(observer); + verifyZeroInteractions(observer); + + weather.timePasses(); + assertEquals("The weather changed to rainy.", appender.getLastMessage()); + verify(observer).update(weather, WeatherType.RAINY); + + weather.removeObserver(observer); + weather.timePasses(); + assertEquals("The weather changed to windy.", appender.getLastMessage()); + + verifyNoMoreInteractions(observer); + assertEquals(2, appender.getLogSize()); + } + + /** + * Verify if the weather passes in the order of the {@link WeatherType}s + */ + @Test + public void testTimePasses() { + final Race observer = mock(Race.class); + final GWeather weather = new GWeather(); + weather.addObserver(observer); + + final InOrder inOrder = inOrder(observer); + final WeatherType[] weatherTypes = WeatherType.values(); + for (int i = 1; i < 20; i++) { + weather.timePasses(); + inOrder.verify(observer).update(weather, weatherTypes[i % weatherTypes.length]); + } + + verifyNoMoreInteractions(observer); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java new file mode 100644 index 0000000000..930f7533f1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/ObserverTest.java @@ -0,0 +1,95 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import static org.junit.Assert.assertEquals; + +import com.iluwatar.observer.WeatherType; +import com.iluwatar.observer.utils.InMemoryAppender; +import java.util.function.Supplier; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Date: 12/27/15 - 11:44 AM + * Test for Observers + * @param Type of Observer + * @author Jeroen Meulemeester + */ +public abstract class ObserverTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * The observer instance factory + */ + private final Supplier factory; + + /** + * The weather type currently tested + */ + private final WeatherType weather; + + /** + * The expected response from the observer + */ + private final String response; + + /** + * Create a new test instance using the given parameters + * + * @param weather The weather currently being tested + * @param response The expected response from the observer + * @param factory The factory, used to create an instance of the tested observer + */ + ObserverTest(final WeatherType weather, final String response, final Supplier factory) { + this.weather = weather; + this.response = response; + this.factory = factory; + } + + /** + * Verify if the weather has the expected influence on the observer + */ + @Test + public void testObserver() { + final O observer = this.factory.get(); + assertEquals(0, appender.getLogSize()); + + observer.update(null, this.weather); + assertEquals(this.response, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java new file mode 100644 index 0000000000..a61a91afe0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/observer/src/test/java/com/iluwatar/observer/generic/OrcsTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.observer.generic; + +import com.iluwatar.observer.WeatherType; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Date: 12/27/15 - 12:07 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class OrcsTest extends ObserverTest { + + @Parameterized.Parameters + public static Collection data() { + final List testData = new ArrayList<>(); + testData.add(new Object[]{WeatherType.SUNNY, "The sun hurts the orcs' eyes."}); + testData.add(new Object[]{WeatherType.RAINY, "The orcs are dripping wet."}); + testData.add(new Object[]{WeatherType.WINDY, "The orc smell almost vanishes in the wind."}); + testData.add(new Object[]{WeatherType.COLD, "The orcs are freezing cold."}); + return testData; + } + + /** + * Create a new test with the given weather and expected response + * + * @param weather The weather that should be unleashed on the observer + * @param response The expected response from the observer + */ + public OrcsTest(final WeatherType weather, final String response) { + super(weather, response, GOrcs::new); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java new file mode 100644 index 0000000000..79101f3d36 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumListPageTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + + +import static org.junit.Assert.assertTrue; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.AlbumPage; +import org.junit.Before; +import org.junit.Test; + +/** + * Test Album Selection and Album Listing + */ +public class AlbumListPageTest { + + private AlbumListPage albumListPage = new AlbumListPage(new WebClient()); + + @Before + public void setUp() { + albumListPage.navigateToPage(); + } + + @Test + public void testSelectAlbum() { + AlbumPage albumPage = albumListPage.selectAlbum("21"); + albumPage.navigateToPage(); + assertTrue(albumPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java new file mode 100644 index 0000000000..cb07a8293e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java @@ -0,0 +1,67 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + +import static org.junit.Assert.assertTrue; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.AlbumPage; +import org.junit.Before; +import org.junit.Test; + +/** + * Test Album Page Operations + */ +public class AlbumPageTest { + + private AlbumPage albumPage = new AlbumPage(new WebClient()); + + @Before + public void setUp() { + albumPage.navigateToPage(); + } + + @Test + public void testSaveAlbum() { + + AlbumPage albumPageAfterChanges = albumPage + .changeAlbumTitle("25") + .changeArtist("Adele Laurie Blue Adkins") + .changeAlbumYear(2015) + .changeAlbumRating("B") + .changeNumberOfSongs(20) + .saveChanges(); + + assertTrue(albumPageAfterChanges.isAt()); + + } + + @Test + public void testCancelChanges() { + AlbumListPage albumListPage = albumPage.cancelChanges(); + albumListPage.navigateToPage(); + assertTrue(albumListPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java new file mode 100644 index 0000000000..ad10a19278 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/page-object/src/test/java/com/iluwatar/pageobject/LoginPageTest.java @@ -0,0 +1,55 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + *

+ * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + *

+ * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.pageobject; + +import static org.junit.Assert.assertTrue; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.iluwatar.pageobject.pages.AlbumListPage; +import com.iluwatar.pageobject.pages.LoginPage; +import org.junit.Before; +import org.junit.Test; + +/** + * Test Login Page Object + */ +public class LoginPageTest { + + private LoginPage loginPage = new LoginPage(new WebClient()); + + @Before + public void setUp() { + loginPage.navigateToPage(); + } + + @Test + public void testLogin() { + AlbumListPage albumListPage = loginPage + .enterUsername("admin") + .enterPassword("password") + .login(); + albumListPage.navigateToPage(); + assertTrue(albumListPage.isAt()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java new file mode 100644 index 0000000000..8c15bcf0fc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java new file mode 100644 index 0000000000..17bd4f89e8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ConsumerTest.java @@ -0,0 +1,112 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.time.LocalDateTime; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/27/15 - 9:45 PM + * + * @author Jeroen Meulemeester + */ +public class ConsumerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Consumer.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testConsume() throws Exception { + final Message[] messages = new Message[]{ + createMessage("you", "Hello!"), + createMessage("me", "Hi!"), + Message.POISON_PILL, + createMessage("late_for_the_party", "Hello? Anyone here?"), + }; + + final MessageQueue queue = new SimpleMessageQueue(messages.length); + for (final Message message : messages) { + queue.put(message); + } + + new Consumer("NSA", queue).consume(); + + assertTrue(appender.logContains("Message [Hello!] from [you] received by [NSA]")); + assertTrue(appender.logContains("Message [Hi!] from [me] received by [NSA]")); + assertTrue(appender.logContains("Consumer NSA receive request to terminate.")); + } + + /** + * Create a new message from the given sender with the given message body + * + * @param sender The sender's name + * @param message The message body + * @return The message instance + */ + private static Message createMessage(final String sender, final String message) { + final SimpleMessage msg = new SimpleMessage(); + msg.addHeader(Message.Headers.SENDER, sender); + msg.addHeader(Message.Headers.DATE, LocalDateTime.now().toString()); + msg.setBody(message); + return msg; + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender(Class clazz) { + ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java new file mode 100644 index 0000000000..b150056956 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/PoisonMessageTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.Test; + +import static com.iluwatar.poison.pill.Message.Headers; +import static com.iluwatar.poison.pill.Message.POISON_PILL; + +/** + * Date: 12/27/15 - 10:30 PM + * + * @author Jeroen Meulemeester + */ +public class PoisonMessageTest { + + @Test(expected = UnsupportedOperationException.class) + public void testAddHeader() throws Exception { + POISON_PILL.addHeader(Headers.SENDER, "sender"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testGetHeader() throws Exception { + POISON_PILL.getHeader(Headers.SENDER); + } + + @Test(expected = UnsupportedOperationException.class) + public void testGetHeaders() throws Exception { + POISON_PILL.getHeaders(); + } + + @Test(expected = UnsupportedOperationException.class) + public void testSetBody() throws Exception { + POISON_PILL.setBody("Test message."); + } + + @Test(expected = UnsupportedOperationException.class) + public void testGetBody() throws Exception { + POISON_PILL.getBody(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java new file mode 100644 index 0000000000..7b5982a3d8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/ProducerTest.java @@ -0,0 +1,86 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/27/15 - 10:32 PM + * + * @author Jeroen Meulemeester + */ +public class ProducerTest { + + @Test + public void testSend() throws Exception { + final MqPublishPoint publishPoint = mock(MqPublishPoint.class); + final Producer producer = new Producer("producer", publishPoint); + verifyZeroInteractions(publishPoint); + + producer.send("Hello!"); + + final ArgumentCaptor messageCaptor = ArgumentCaptor.forClass(Message.class); + verify(publishPoint).put(messageCaptor.capture()); + + final Message message = messageCaptor.getValue(); + assertNotNull(message); + assertEquals("producer", message.getHeader(Message.Headers.SENDER)); + assertNotNull(message.getHeader(Message.Headers.DATE)); + assertEquals("Hello!", message.getBody()); + + verifyNoMoreInteractions(publishPoint); + } + + @Test + public void testStop() throws Exception { + final MqPublishPoint publishPoint = mock(MqPublishPoint.class); + final Producer producer = new Producer("producer", publishPoint); + verifyZeroInteractions(publishPoint); + + producer.stop(); + verify(publishPoint).put(eq(Message.POISON_PILL)); + + try { + producer.send("Hello!"); + fail("Expected 'IllegalStateException' at this point, since the producer has stopped!"); + } catch (IllegalStateException e) { + assertNotNull(e); + assertNotNull(e.getMessage()); + assertEquals("Producer Hello! was stopped and fail to deliver requested message [producer].", + e.getMessage()); + } + + verifyNoMoreInteractions(publishPoint); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java new file mode 100644 index 0000000000..2b0b3bd172 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/poison-pill/src/test/java/com/iluwatar/poison/pill/SimpleMessageTest.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.poison.pill; + +import org.junit.Test; + +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/27/15 - 10:25 PM + * + * @author Jeroen Meulemeester + */ +public class SimpleMessageTest { + + @Test + public void testGetHeaders() { + final SimpleMessage message = new SimpleMessage(); + assertNotNull(message.getHeaders()); + assertTrue(message.getHeaders().isEmpty()); + + final String senderName = "test"; + message.addHeader(Message.Headers.SENDER, senderName); + assertNotNull(message.getHeaders()); + assertFalse(message.getHeaders().isEmpty()); + assertEquals(senderName, message.getHeaders().get(Message.Headers.SENDER)); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUnModifiableHeaders() { + final SimpleMessage message = new SimpleMessage(); + final Map headers = message.getHeaders(); + headers.put(Message.Headers.SENDER, "test"); + } + + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java new file mode 100644 index 0000000000..ef80e87cb6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java new file mode 100644 index 0000000000..6e337e5840 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/ImmutableStewTest.java @@ -0,0 +1,83 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/27/15 - 10:46 PM + * + * @author Jeroen Meulemeester + */ +public class ImmutableStewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Verify if mixing the stew doesn't change the internal state + */ + @Test + public void testMix() { + final Stew stew = new Stew(1, 2, 3, 4); + final String expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers"; + + for (int i = 0; i < 20; i++) { + stew.mix(); + assertEquals(expectedMessage, appender.getLastMessage()); + } + + assertEquals(20, appender.getLogSize()); + } + + /** + * Verify if tasting the stew actually removes one of each ingredient + */ + @Test + public void testDrink() { + final Stew stew = new Stew(1, 2, 3, 4); + stew.mix(); + + assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender.getLastMessage()); + + stew.taste(); + assertEquals("Tasting the stew", appender.getLastMessage()); + + stew.mix(); + assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender.getLastMessage()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java new file mode 100644 index 0000000000..6ac5b834f7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/private-class-data/src/test/java/com/iluwatar/privateclassdata/StewTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.privateclassdata; + +import com.iluwatar.privateclassdata.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/27/15 - 10:46 PM + * + * @author Jeroen Meulemeester + */ +public class StewTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Verify if mixing the stew doesn't change the internal state + */ + @Test + public void testMix() { + final ImmutableStew stew = new ImmutableStew(1, 2, 3, 4); + final String expectedMessage = "Mixing the immutable stew we find: 1 potatoes, " + + "2 carrots, 3 meat and 4 peppers"; + + for (int i = 0; i < 20; i++) { + stew.mix(); + assertEquals(expectedMessage, appender.getLastMessage()); + } + + assertEquals(20, appender.getLogSize()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java new file mode 100644 index 0000000000..e7f7870f79 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java new file mode 100644 index 0000000000..4c110cad2a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ConsumerTest.java @@ -0,0 +1,55 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.Test; + +import static org.mockito.Mockito.*; + +/** + * Date: 12/27/15 - 11:01 PM + * + * @author Jeroen Meulemeester + */ +public class ConsumerTest { + + private static final int ITEM_COUNT = 5; + + @Test + public void testConsume() throws Exception { + final ItemQueue queue = spy(new ItemQueue()); + for (int id = 0; id < ITEM_COUNT; id++) { + queue.put(new Item("producer", id)); + } + + reset(queue); // Don't count the preparation above as interactions with the queue + final Consumer consumer = new Consumer("consumer", queue); + + for (int id = 0; id < ITEM_COUNT; id++) { + consumer.consume(); + } + + verify(queue, times(ITEM_COUNT)).take(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java new file mode 100644 index 0000000000..5f756c9386 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/producer-consumer/src/test/java/com/iluwatar/producer/consumer/ProducerTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.producer.consumer; + +import org.junit.Test; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/28/15 - 12:12 AM + * + * @author Jeroen Meulemeester + */ +public class ProducerTest { + + @Test(timeout = 6000) + public void testProduce() throws Exception { + final ItemQueue queue = mock(ItemQueue.class); + final Producer producer = new Producer("producer", queue); + + producer.produce(); + verify(queue).put(any(Item.class)); + + verifyNoMoreInteractions(queue); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/AppTest.java new file mode 100644 index 0000000000..f7df415e85 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.promise; + +import java.util.concurrent.ExecutionException; + +import org.junit.Test; + +/** + * + * Application test. + */ +public class AppTest { + + @Test + public void testApp() throws InterruptedException, ExecutionException { + App.main(null); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/PromiseTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/PromiseTest.java new file mode 100644 index 0000000000..6e17b97947 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/promise/src/test/java/com/iluwatar/promise/PromiseTest.java @@ -0,0 +1,263 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.promise; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Consumer; +import java.util.function.Function; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +/** + * Tests Promise class. + */ +public class PromiseTest { + + private Executor executor; + private Promise promise; + @Rule public ExpectedException exception = ExpectedException.none(); + + @Before + public void setUp() { + executor = Executors.newSingleThreadExecutor(); + promise = new Promise<>(); + } + + @Test + public void promiseIsFulfilledWithTheResultantValueOfExecutingTheTask() + throws InterruptedException, ExecutionException { + promise.fulfillInAsync(new NumberCrunchingTask(), executor); + + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, promise.get()); + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + @Test + public void promiseIsFulfilledWithAnExceptionIfTaskThrowsAnException() + throws InterruptedException, ExecutionException, TimeoutException { + testWaitingForeverForPromiseToBeFulfilled(); + testWaitingSomeTimeForPromiseToBeFulfilled(); + } + + private void testWaitingForeverForPromiseToBeFulfilled() + throws InterruptedException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfillInAsync(new Callable() { + + @Override + public Integer call() throws Exception { + throw new RuntimeException("Barf!"); + } + }, executor); + + try { + promise.get(); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + promise.get(1000, TimeUnit.SECONDS); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + private void testWaitingSomeTimeForPromiseToBeFulfilled() + throws InterruptedException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfillInAsync(new Callable() { + + @Override + public Integer call() throws Exception { + throw new RuntimeException("Barf!"); + } + }, executor); + + try { + promise.get(1000, TimeUnit.SECONDS); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + promise.get(); + fail("Fetching promise should result in exception if the task threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + } + + @Test + public void dependentPromiseIsFulfilledAfterTheConsumerConsumesTheResultOfThisPromise() + throws InterruptedException, ExecutionException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept(value -> { + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + }); + + + dependentPromise.get(); + assertTrue(dependentPromise.isDone()); + assertFalse(dependentPromise.isCancelled()); + } + + @Test + public void dependentPromiseIsFulfilledWithAnExceptionIfConsumerThrowsAnException() + throws InterruptedException, ExecutionException, TimeoutException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenAccept(new Consumer() { + + @Override + public void accept(Integer value) { + throw new RuntimeException("Barf!"); + } + }); + + try { + dependentPromise.get(); + fail("Fetching dependent promise should result in exception " + + "if the action threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + dependentPromise.get(1000, TimeUnit.SECONDS); + fail("Fetching dependent promise should result in exception " + + "if the action threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + @Test + public void dependentPromiseIsFulfilledAfterTheFunctionTransformsTheResultOfThisPromise() + throws InterruptedException, ExecutionException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply(value -> { + assertEquals(NumberCrunchingTask.CRUNCHED_NUMBER, value); + return String.valueOf(value); + }); + + + assertEquals(String.valueOf(NumberCrunchingTask.CRUNCHED_NUMBER), dependentPromise.get()); + assertTrue(dependentPromise.isDone()); + assertFalse(dependentPromise.isCancelled()); + } + + @Test + public void dependentPromiseIsFulfilledWithAnExceptionIfTheFunctionThrowsException() + throws InterruptedException, ExecutionException, TimeoutException { + Promise dependentPromise = promise + .fulfillInAsync(new NumberCrunchingTask(), executor) + .thenApply(new Function() { + + @Override + public String apply(Integer value) { + throw new RuntimeException("Barf!"); + } + }); + + try { + dependentPromise.get(); + fail("Fetching dependent promise should result in exception " + + "if the function threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + + try { + dependentPromise.get(1000, TimeUnit.SECONDS); + fail("Fetching dependent promise should result in exception " + + "if the function threw an exception"); + } catch (ExecutionException ex) { + assertTrue(promise.isDone()); + assertFalse(promise.isCancelled()); + } + } + + @Test + public void fetchingAnAlreadyFulfilledPromiseReturnsTheFulfilledValueImmediately() + throws InterruptedException, ExecutionException, TimeoutException { + Promise promise = new Promise<>(); + promise.fulfill(NumberCrunchingTask.CRUNCHED_NUMBER); + + promise.get(1000, TimeUnit.SECONDS); + } + + @SuppressWarnings("unchecked") + @Test + public void exceptionHandlerIsCalledWhenPromiseIsFulfilledExceptionally() { + Promise promise = new Promise<>(); + Consumer exceptionHandler = mock(Consumer.class); + promise.onError(exceptionHandler); + + Exception exception = new Exception("barf!"); + promise.fulfillExceptionally(exception); + + verify(exceptionHandler).accept(eq(exception)); + } + + private static class NumberCrunchingTask implements Callable { + + private static final Integer CRUNCHED_NUMBER = Integer.MAX_VALUE; + + @Override + public Integer call() throws Exception { + // Do number crunching + Thread.sleep(100); + return CRUNCHED_NUMBER; + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/AppTest.java new file mode 100644 index 0000000000..08e0dbba13 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.property; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/CharacterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/CharacterTest.java new file mode 100644 index 0000000000..5dc996f4de --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/property/src/test/java/com/iluwatar/property/CharacterTest.java @@ -0,0 +1,125 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.property; + +import org.junit.Test; + +import static com.iluwatar.property.Character.Type; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/28/15 - 7:46 PM + * + * @author Jeroen Meulemeester + */ +public class CharacterTest { + + @Test + public void testPrototypeStats() throws Exception { + final Character prototype = new Character(); + + for (final Stats stat : Stats.values()) { + assertFalse(prototype.has(stat)); + assertNull(prototype.get(stat)); + + final Integer expectedValue = stat.ordinal(); + prototype.set(stat, expectedValue); + assertTrue(prototype.has(stat)); + assertEquals(expectedValue, prototype.get(stat)); + + prototype.remove(stat); + assertFalse(prototype.has(stat)); + assertNull(prototype.get(stat)); + } + + } + + @Test + public void testCharacterStats() throws Exception { + final Character prototype = new Character(); + for (final Stats stat : Stats.values()) { + prototype.set(stat, stat.ordinal()); + } + + final Character mage = new Character(Type.MAGE, prototype); + for (final Stats stat : Stats.values()) { + final Integer expectedValue = stat.ordinal(); + assertTrue(mage.has(stat)); + assertEquals(expectedValue, mage.get(stat)); + } + } + + @Test + public void testToString() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.AGILITY, 2); + prototype.set(Stats.INTELLECT, 3); + assertEquals("Stats:\n - AGILITY:2\n - ARMOR:1\n - INTELLECT:3\n", prototype.toString()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertEquals("Character type: ROGUE\nStats:\n - AGILITY:2\n - ARMOR:1\n", stupid.toString()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertEquals("Player: weak\nStats:\n - AGILITY:2\n - INTELLECT:3\n", weak.toString()); + + } + + @Test + public void testName() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.INTELLECT, 2); + assertNull(prototype.name()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertNull(stupid.name()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertEquals("weak", weak.name()); + } + + @Test + public void testType() throws Exception { + final Character prototype = new Character(); + prototype.set(Stats.ARMOR, 1); + prototype.set(Stats.INTELLECT, 2); + assertNull(prototype.type()); + + final Character stupid = new Character(Type.ROGUE, prototype); + stupid.remove(Stats.INTELLECT); + assertEquals(Type.ROGUE, stupid.type()); + + final Character weak = new Character("weak", prototype); + weak.remove(Stats.ARMOR); + assertNull(weak.type()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/AppTest.java new file mode 100644 index 0000000000..48c70429a9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java new file mode 100644 index 0000000000..bee05bc5e2 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/HeroFactoryImplTest.java @@ -0,0 +1,61 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import org.junit.Test; + +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/28/15 - 8:34 PM + * + * @author Jeroen Meulemeester + */ +public class HeroFactoryImplTest { + + @Test + public void testFactory() throws Exception { + final Mage mage = mock(Mage.class); + final Warlord warlord = mock(Warlord.class); + final Beast beast = mock(Beast.class); + + when(mage.clone()).thenThrow(CloneNotSupportedException.class); + when(warlord.clone()).thenThrow(CloneNotSupportedException.class); + when(beast.clone()).thenThrow(CloneNotSupportedException.class); + + final HeroFactoryImpl factory = new HeroFactoryImpl(mage, warlord, beast); + assertNull(factory.createMage()); + assertNull(factory.createWarlord()); + assertNull(factory.createBeast()); + + verify(mage).clone(); + verify(warlord).clone(); + verify(beast).clone(); + verifyNoMoreInteractions(mage, warlord, beast); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java new file mode 100644 index 0000000000..839f27bc71 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/prototype/src/test/java/com/iluwatar/prototype/PrototypeTest.java @@ -0,0 +1,87 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.prototype; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +/** + * Date: 12/28/15 - 8:45 PM + * @param

Prototype + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class PrototypeTest

{ + + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList( + new Object[]{new OrcBeast(), "Orcish wolf"}, + new Object[]{new OrcMage(), "Orcish mage"}, + new Object[]{new OrcWarlord(), "Orcish warlord"}, + new Object[]{new ElfBeast(), "Elven eagle"}, + new Object[]{new ElfMage(), "Elven mage"}, + new Object[]{new ElfWarlord(), "Elven warlord"} + ); + } + + /** + * The tested prototype instance + */ + private final P testedPrototype; + + /** + * The expected {@link Prototype#toString()} value + */ + private final String expectedToString; + + /** + * Create a new test instance, using the given test object and expected value + * + * @param testedPrototype The tested prototype instance + * @param expectedToString The expected {@link Prototype#toString()} value + */ + public PrototypeTest(final P testedPrototype, final String expectedToString) { + this.expectedToString = expectedToString; + this.testedPrototype = testedPrototype; + } + + @Test + public void testPrototype() throws Exception { + assertEquals(this.expectedToString, this.testedPrototype.toString()); + + final Object clone = this.testedPrototype.clone(); + assertNotNull(clone); + assertNotSame(clone, this.testedPrototype); + assertSame(this.testedPrototype.getClass(), clone.getClass()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/AppTest.java new file mode 100644 index 0000000000..d22d9c4bdd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java new file mode 100644 index 0000000000..944193a0ab --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/IvoryTowerTest.java @@ -0,0 +1,72 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Tests for {@link IvoryTower} + */ +public class IvoryTowerTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(IvoryTower.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testEnter() throws Exception { + final Wizard[] wizards = new Wizard[]{ + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin") + }; + + IvoryTower tower = new IvoryTower(); + for (Wizard wizard : wizards) { + tower.enter(wizard); + } + + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin enters the tower.")); + assertEquals(4, appender.getLogSize()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java new file mode 100644 index 0000000000..ce5637214a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTest.java @@ -0,0 +1,41 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Tests for {@link Wizard} + */ +public class WizardTest { + + @Test + public void testToString() throws Exception { + final String[] wizardNames = {"Gandalf", "Dumbledore", "Oz", "Merlin"}; + for (String name : wizardNames) { + assertEquals(name, new Wizard(name).toString()); + } + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java new file mode 100644 index 0000000000..2958376d67 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/proxy/src/test/java/com/iluwatar/proxy/WizardTowerProxyTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.proxy; + +import com.iluwatar.proxy.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Tests for {@link WizardTowerProxy} + */ +public class WizardTowerProxyTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testEnter() throws Exception { + final Wizard[] wizards = new Wizard[]{ + new Wizard("Gandalf"), + new Wizard("Dumbledore"), + new Wizard("Oz"), + new Wizard("Merlin") + }; + + final WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower()); + for (Wizard wizard : wizards) { + proxy.enter(wizard); + } + + assertTrue(appender.logContains("Gandalf enters the tower.")); + assertTrue(appender.logContains("Dumbledore enters the tower.")); + assertTrue(appender.logContains("Oz enters the tower.")); + assertTrue(appender.logContains("Merlin is not allowed to enter!")); + assertEquals(4, appender.getLogSize()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java new file mode 100644 index 0000000000..216ba49f08 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/publish-subscribe/src/test/java/com/iluwatar/publish/subscribe/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.publish.subscribe; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java new file mode 100644 index 0000000000..d1cf75ca8f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import java.io.IOException; + +import org.junit.Test; + +/** + * Application Test + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java new file mode 100644 index 0000000000..30b5d7ce09 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageQueueTest.java @@ -0,0 +1,48 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * + * Test case for submitting and retrieving messages from Blocking Queue. + * + */ +public class MessageQueueTest { + + @Test + public void messageQueueTest() { + + MessageQueue msgQueue = new MessageQueue(); + + // submit message + msgQueue.submitMsg(new Message("MessageQueue Test")); + + // retrieve message + assertEquals(msgQueue.retrieveMsg().getMsg(), "MessageQueue Test"); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java new file mode 100644 index 0000000000..93ef723ea7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/MessageTest.java @@ -0,0 +1,43 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +/** + * + * Test case for creating and checking the Message. + * + */ +public class MessageTest { + + @Test + public void messageTest() { + + // Parameterized constructor test. + String testMsg = "Message Test"; + Message msg = new Message(testMsg); + assertEquals(msg.getMsg(), testMsg); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java new file mode 100644 index 0000000000..a773c377e9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/queue-load-leveling/src/test/java/com/iluwatar/queue/load/leveling/TaskGenSrvExeTest.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.queue.load.leveling; + +import org.junit.Test; + +/** + * + * Test case for submitting Message to Blocking Queue by TaskGenerator + * and retrieve the message by ServiceExecutor. + * + */ +public class TaskGenSrvExeTest { + + @Test + public void taskGeneratorTest() { + MessageQueue msgQueue = new MessageQueue(); + + // Create a task generator thread with 1 job to submit. + Runnable taskRunnable = new TaskGenerator(msgQueue, 1); + Thread taskGenThr = new Thread(taskRunnable); + taskGenThr.start(); + + // Create a service executor thread. + Runnable srvRunnable = new ServiceExecutor(msgQueue); + Thread srvExeThr = new Thread(srvRunnable); + srvExeThr.start(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java new file mode 100644 index 0000000000..7aa80f8cca --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -0,0 +1,99 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reactor.app; + +import java.io.IOException; + +import com.iluwatar.reactor.framework.NioReactor; +import org.junit.Test; + +import com.iluwatar.reactor.framework.SameThreadDispatcher; +import com.iluwatar.reactor.framework.ThreadPoolDispatcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * This class tests the Distributed Logging service by starting a Reactor and then sending it + * concurrent logging requests using multiple clients. + */ +public class ReactorTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReactorTest.class); + + /** + * Test the application using pooled thread dispatcher. + * + * @throws IOException if any I/O error occurs. + * @throws InterruptedException if interrupted while stopping the application. + */ + @Test + public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingThreadPoolDispatcher start"); + App app = new App(new ThreadPoolDispatcher(2)); + app.start(); + + AppClient client = new AppClient(); + client.start(); + + // allow clients to send requests. Artificial delay. + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("sleep interrupted", e); + } + + client.stop(); + + app.stop(); + LOGGER.info("testAppUsingThreadPoolDispatcher stop"); + } + + /** + * Test the application using same thread dispatcher. + * + * @throws IOException if any I/O error occurs. + * @throws InterruptedException if interrupted while stopping the application. + */ + @Test + public void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingSameThreadDispatcher start"); + App app = new App(new SameThreadDispatcher()); + app.start(); + + AppClient client = new AppClient(); + client.start(); + + // allow clients to send requests. Artificial delay. + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + LOGGER.error("sleep interrupted", e); + } + + client.stop(); + + app.stop(); + LOGGER.info("testAppUsingSameThreadDispatcher stop"); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java new file mode 100644 index 0000000000..fd0cd4b270 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java new file mode 100644 index 0000000000..adc2adae20 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderAndWriterTest.java @@ -0,0 +1,118 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; + +/** + * @author hongshuwei@gmail.com + */ +public class ReaderAndWriterTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderAndWriterTest.class); + + /** + * Verify reader and writer can only get the lock to read and write orderly + */ + @Test + public void testReadAndWrite() throws Exception { + + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = new Reader("Reader 1", lock.readLock()); + Writer writer1 = new Writer("Writer 1", lock.writeLock()); + + ExecutorService executeService = Executors.newFixedThreadPool(2); + executeService.submit(reader1); + // Let reader1 execute first + Thread.sleep(150); + executeService.submit(writer1); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + } + + /** + * Verify reader and writer can only get the lock to read and write orderly + */ + @Test + public void testWriteAndRead() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = new Reader("Reader 1", lock.readLock()); + Writer writer1 = new Writer("Writer 1", lock.writeLock()); + + executeService.submit(writer1); + // Let writer1 execute first + Thread.sleep(150); + executeService.submit(reader1); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + } +} + diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java new file mode 100644 index 0000000000..c9b3eb72cd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/ReaderTest.java @@ -0,0 +1,88 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static junit.framework.TestCase.assertTrue; +import static org.mockito.Mockito.spy; + +/** + * @author hongshuwei@gmail.com + */ +public class ReaderTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Reader.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderTest.class); + + /** + * Verify that multiple readers can get the read lock concurrently + */ + @Test + public void testRead() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Reader reader1 = spy(new Reader("Reader 1", lock.readLock())); + Reader reader2 = spy(new Reader("Reader 2", lock.readLock())); + + executeService.submit(reader1); + Thread.sleep(150); + executeService.submit(reader2); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + + // Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads + // can be performed in the same time. + assertTrue(appender.logContains("Reader 1 begin")); + assertTrue(appender.logContains("Reader 2 begin")); + assertTrue(appender.logContains("Reader 1 finish")); + assertTrue(appender.logContains("Reader 2 finish")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java new file mode 100644 index 0000000000..7c4b4148dc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/WriterTest.java @@ -0,0 +1,89 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.reader.writer.lock; + +import com.iluwatar.reader.writer.lock.utils.InMemoryAppender; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.spy; + +/** + * @author hongshuwei@gmail.com + */ +public class WriterTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(Writer.class); + } + + @After + public void tearDown() { + appender.stop(); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(WriterTest.class); + + /** + * Verify that multiple writers will get the lock in order. + */ + @Test + public void testWrite() throws Exception { + + ExecutorService executeService = Executors.newFixedThreadPool(2); + ReaderWriterLock lock = new ReaderWriterLock(); + + Writer writer1 = spy(new Writer("Writer 1", lock.writeLock())); + Writer writer2 = spy(new Writer("Writer 2", lock.writeLock())); + + executeService.submit(writer1); + // Let write1 execute first + Thread.sleep(150); + executeService.submit(writer2); + + executeService.shutdown(); + try { + executeService.awaitTermination(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + LOGGER.error("Error waiting for ExecutorService shutdown", e); + } + // Write operation will hold the write lock 250 milliseconds, so here we verify that when two + // writer execute concurrently, the second writer can only writes only when the first one is + // finished. + assertTrue(appender.logContains("Writer 1 begin")); + assertTrue(appender.logContains("Writer 1 finish")); + assertTrue(appender.logContains("Writer 2 begin")); + assertTrue(appender.logContains("Writer 2 finish")); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java new file mode 100644 index 0000000000..cb84b1ae83 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AnnotationBasedRepositoryTest.java @@ -0,0 +1,132 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Resource; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.google.common.collect.Lists; + +/** + * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query + * by {@link org.springframework.data.jpa.domain.Specification} are also test. + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +public class AnnotationBasedRepositoryTest { + + @Resource + private PersonRepository repository; + + Person peter = new Person("Peter", "Sagan", 17); + Person nasta = new Person("Nasta", "Kuzminova", 25); + Person john = new Person("John", "lawrence", 35); + Person terry = new Person("Terry", "Law", 36); + + List persons = Arrays.asList(peter, nasta, john, terry); + + /** + * Prepare data for test + */ + @Before + public void setup() { + + repository.save(persons); + } + + @Test + public void testFindAll() { + + List actuals = Lists.newArrayList(repository.findAll()); + assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); + } + + @Test + public void testSave() { + + Person terry = repository.findByName("Terry"); + terry.setSurname("Lee"); + terry.setAge(47); + repository.save(terry); + + terry = repository.findByName("Terry"); + assertEquals(terry.getSurname(), "Lee"); + assertEquals(47, terry.getAge()); + } + + @Test + public void testDelete() { + + Person terry = repository.findByName("Terry"); + repository.delete(terry); + + assertEquals(3, repository.count()); + assertNull(repository.findByName("Terry")); + } + + @Test + public void testCount() { + + assertEquals(4, repository.count()); + } + + @Test + public void testFindAllByAgeBetweenSpec() { + + List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + + assertEquals(3, persons.size()); + assertTrue(persons.stream().allMatch((item) -> { + return item.getAge() > 20 && item.getAge() < 40; + })); + } + + @Test + public void testFindOneByNameEqualSpec() { + + Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual); + } + + @After + public void cleanup() { + + repository.deleteAll(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java new file mode 100644 index 0000000000..6d6a58e8dd --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppConfigTest.java @@ -0,0 +1,76 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.ResultSet; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.annotation.Transactional; + +/** + * This case is Just for test the Annotation Based configuration + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { AppConfig.class }, loader = AnnotationConfigContextLoader.class) +public class AppConfigTest { + + @Autowired + DataSource dataSource; + + /** + * Test for bean instance + */ + @Test + public void testDataSource() { + assertNotNull(dataSource); + } + + /** + * Test for correct query execution + */ + @Test + @Transactional + public void testQuery() throws SQLException { + ResultSet resultSet = dataSource.getConnection().createStatement().executeQuery("SELECT 1"); + String result = null; + String expected = "1"; + while (resultSet.next()) { + result = resultSet.getString(1); + + } + assertTrue(result.equals(expected)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppTest.java new file mode 100644 index 0000000000..d3f05caaa5 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/AppTest.java @@ -0,0 +1,38 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import org.junit.Test; + +import java.io.IOException; + +/** + * Tests that Repository example runs without errors. + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java new file mode 100644 index 0000000000..3201c024ca --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/repository/src/test/java/com/iluwatar/repository/RepositoryTest.java @@ -0,0 +1,130 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.repository; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Resource; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.google.common.collect.Lists; + +/** + * Test case to test the functions of {@link PersonRepository}, beside the CRUD functions, the query + * by {@link org.springframework.data.jpa.domain.Specification} are also test. + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:applicationContext.xml" }) +public class RepositoryTest { + + @Resource + private PersonRepository repository; + + Person peter = new Person("Peter", "Sagan", 17); + Person nasta = new Person("Nasta", "Kuzminova", 25); + Person john = new Person("John", "lawrence", 35); + Person terry = new Person("Terry", "Law", 36); + + List persons = Arrays.asList(peter, nasta, john, terry); + + /** + * Prepare data for test + */ + @Before + public void setup() { + + repository.save(persons); + } + + @Test + public void testFindAll() { + + List actuals = Lists.newArrayList(repository.findAll()); + assertTrue(actuals.containsAll(persons) && persons.containsAll(actuals)); + } + + @Test + public void testSave() { + + Person terry = repository.findByName("Terry"); + terry.setSurname("Lee"); + terry.setAge(47); + repository.save(terry); + + terry = repository.findByName("Terry"); + assertEquals(terry.getSurname(), "Lee"); + assertEquals(47, terry.getAge()); + } + + @Test + public void testDelete() { + + Person terry = repository.findByName("Terry"); + repository.delete(terry); + + assertEquals(3, repository.count()); + assertNull(repository.findByName("Terry")); + } + + @Test + public void testCount() { + + assertEquals(4, repository.count()); + } + + @Test + public void testFindAllByAgeBetweenSpec() { + + List persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); + + assertEquals(3, persons.size()); + assertTrue(persons.stream().allMatch((item) -> { + return item.getAge() > 20 && item.getAge() < 40; + })); + } + + @Test + public void testFindOneByNameEqualSpec() { + + Person actual = repository.findOne(new PersonSpecifications.NameEqualSpec("Terry")); + assertEquals(terry, actual); + } + + @After + public void cleanup() { + + repository.deleteAll(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java new file mode 100644 index 0000000000..1d7b4137ad --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.resource.acquisition.is.initialization; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java new file mode 100644 index 0000000000..6786416fa8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/resource-acquisition-is-initialization/src/test/java/com/iluwatar/resource/acquisition/is/initialization/ClosableTest.java @@ -0,0 +1,87 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.resource.acquisition.is.initialization; + +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/28/15 - 9:31 PM + * + * @author Jeroen Meulemeester + */ +public class ClosableTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testOpenClose() throws Exception { + try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) { + assertTrue(appender.logContains("Sliding door opens.")); + assertTrue(appender.logContains("Treasure chest opens.")); + } + assertTrue(appender.logContains("Treasure chest closes.")); + assertTrue(appender.logContains("Sliding door closes.")); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java new file mode 100644 index 0000000000..634443fef9 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/FindCustomerTest.java @@ -0,0 +1,86 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.retry; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import org.junit.Test; + +/** + * Unit tests for {@link FindCustomer}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class FindCustomerTest { + /** + * Returns the given result with no exceptions. + */ + @Test + public void noExceptions() throws Exception { + assertThat( + new FindCustomer("123").perform(), + is("123") + ); + } + + /** + * Throws the given exception. + * + * @throws Exception the expected exception + */ + @Test(expected = BusinessException.class) + public void oneException() throws Exception { + new FindCustomer("123", new BusinessException("test")).perform(); + } + + /** + * Should first throw the given exceptions, then return the given result. + * + * @throws Exception not an expected exception + */ + @Test + public void resultAfterExceptions() throws Exception { + final BusinessOperation op = new FindCustomer( + "123", + new CustomerNotFoundException("not found"), + new DatabaseNotAvailableException("not available") + ); + try { + op.perform(); + } catch (CustomerNotFoundException e) { + //ignore + } + try { + op.perform(); + } catch (DatabaseNotAvailableException e) { + //ignore + } + + assertThat( + op.perform(), + is("123") + ); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/RetryTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/RetryTest.java new file mode 100644 index 0000000000..c66c413548 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/retry/src/test/java/com/iluwatar/retry/RetryTest.java @@ -0,0 +1,110 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.iluwatar.retry; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Unit tests for {@link Retry}. + * + * @author George Aristy (george.aristy@gmail.com) + */ +public class RetryTest { + /** + * Should contain all errors thrown. + */ + @Test + public void errors() throws Exception { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.errors(), + hasItem(e) + ); + } + + /** + * No exceptions will be ignored, hence final number of attempts should be 1 even if we're asking + * it to attempt twice. + */ + @Test + public void attempts() { + final BusinessException e = new BusinessException("unhandled"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0 + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(1) + ); + } + + /** + * Final number of attempts should be equal to the number of attempts asked because we are + * asking it to ignore the exception that will be thrown. + */ + @Test + public void ignore() throws Exception { + final BusinessException e = new CustomerNotFoundException("customer not found"); + final Retry retry = new Retry<>( + () -> { throw e; }, + 2, + 0, + ex -> CustomerNotFoundException.class.isAssignableFrom(ex.getClass()) + ); + try { + retry.perform(); + } catch (BusinessException ex) { + //ignore + } + + assertThat( + retry.attempts(), + is(2) + ); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java new file mode 100644 index 0000000000..5eaed3b2ed --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.Test; +import java.io.IOException; + +/** + * Application Test Entrypoint + */ +public class AppTest { + @Test + public void test() throws IOException { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java new file mode 100644 index 0000000000..30a7dce44f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/FruitBowlTest.java @@ -0,0 +1,51 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Test taking from and putting Fruit into a FruitBowl + */ +public class FruitBowlTest { + + @Test + public void fruitBowlTest() { + FruitBowl fbowl = new FruitBowl(); + + assertEquals(fbowl.countFruit(), 0); + + for (int i = 1; i <= 10; i++) { + fbowl.put(new Fruit(Fruit.FruitType.LEMON)); + assertEquals(fbowl.countFruit(), i); + } + + for (int i = 9; i >= 0; i--) { + assertNotNull(fbowl.take()); + assertEquals(fbowl.countFruit(), i); + } + + assertNull(fbowl.take()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java new file mode 100644 index 0000000000..b787a33014 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/semaphore/src/test/java/com/iluwatar/semaphore/SemaphoreTest.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.semaphore; + +import org.junit.Test; +import static org.junit.Assert.*; + +/** + * Test case for acquiring and releasing a Semaphore + */ +public class SemaphoreTest { + + @Test + public void acquireReleaseTest() { + Semaphore sphore = new Semaphore(3); + + assertEquals(sphore.getAvailableLicenses(), 3); + + for (int i = 2; i >= 0; i--) { + try { + sphore.acquire(); + assertEquals(sphore.getAvailableLicenses(), i); + } catch (InterruptedException e) { + fail(e.toString()); + } + } + + for (int i = 1; i <= 3; i++) { + sphore.release(); + assertEquals(sphore.getAvailableLicenses(), i); + } + + sphore.release(); + assertEquals(sphore.getAvailableLicenses(), 3); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/AppTest.java new file mode 100644 index 0000000000..5b8908d80c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/KingTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/KingTest.java new file mode 100644 index 0000000000..3ebbaf28bb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/KingTest.java @@ -0,0 +1,104 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Date: 12/28/15 - 9:40 PM + * + * @author Jeroen Meulemeester + */ +public class KingTest { + + @Test + public void testHungrySoberUncomplimentedKing() { + final King king = new King(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedSoberUncomplimentedKing() { + final King king = new King(); + king.getFed(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungryDrunkUncomplimentedKing() { + final King king = new King(); + king.getDrink(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungrySoberComplimentedKing() { + final King king = new King(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedDrunkUncomplimentedKing() { + final King king = new King(); + king.getFed(); + king.getDrink(); + king.changeMood(); + assertTrue(king.getMood()); + } + + @Test + public void testFedSoberComplimentedKing() { + final King king = new King(); + king.getFed(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testFedDrunkComplimentedKing() { + final King king = new King(); + king.getFed(); + king.getDrink(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + + @Test + public void testHungryDrunkComplimentedKing() { + final King king = new King(); + king.getDrink(); + king.receiveCompliments(); + king.changeMood(); + assertFalse(king.getMood()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/QueenTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/QueenTest.java new file mode 100644 index 0000000000..d425886ba1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/QueenTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Date: 12/28/15 - 9:52 PM + * + * @author Jeroen Meulemeester + */ +public class QueenTest { + + @Test + public void testNotFlirtyUncomplemented() throws Exception { + final Queen queen = new Queen(); + queen.setFlirtiness(false); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testNotFlirtyComplemented() throws Exception { + final Queen queen = new Queen(); + queen.setFlirtiness(false); + queen.receiveCompliments(); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testFlirtyUncomplemented() throws Exception { + final Queen queen = new Queen(); + queen.changeMood(); + assertFalse(queen.getMood()); + } + + @Test + public void testFlirtyComplemented() throws Exception { + final Queen queen = new Queen(); + queen.receiveCompliments(); + queen.changeMood(); + assertTrue(queen.getMood()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/ServantTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/ServantTest.java new file mode 100644 index 0000000000..900ccc4189 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/servant/src/test/java/com/iluwatar/servant/ServantTest.java @@ -0,0 +1,93 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servant; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/28/15 - 10:02 PM + * + * @author Jeroen Meulemeester + */ +public class ServantTest { + + @Test + public void testFeed() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.feed(royalty); + verify(royalty).getFed(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testGiveWine() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.giveWine(royalty); + verify(royalty).getDrink(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testGiveCompliments() throws Exception { + final Royalty royalty = mock(Royalty.class); + final Servant servant = new Servant("test"); + servant.giveCompliments(royalty); + verify(royalty).receiveCompliments(); + verifyNoMoreInteractions(royalty); + } + + @Test + public void testCheckIfYouWillBeHanged() throws Exception { + final Royalty goodMoodRoyalty = mock(Royalty.class); + when(goodMoodRoyalty.getMood()).thenReturn(true); + + final Royalty badMoodRoyalty = mock(Royalty.class); + when(badMoodRoyalty.getMood()).thenReturn(true); + + final List goodCompany = new ArrayList<>(); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + + final List badCompany = new ArrayList<>(); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(goodMoodRoyalty); + goodCompany.add(badMoodRoyalty); + + assertTrue(new Servant("test").checkIfYouWillBeHanged(goodCompany)); + assertTrue(new Servant("test").checkIfYouWillBeHanged(badCompany)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java new file mode 100644 index 0000000000..a667252a16 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/app/AppTest.java @@ -0,0 +1,48 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.app; + +import com.iluwatar.servicelayer.hibernate.HibernateUtil; + +import org.junit.After; +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } + + @After + public void tearDown() throws Exception { + HibernateUtil.dropSession(); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java new file mode 100644 index 0000000000..694fc746db --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/common/BaseDaoTest.java @@ -0,0 +1,145 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import com.iluwatar.servicelayer.hibernate.HibernateUtil; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +/** + * Date: 12/28/15 - 10:53 PM + * Test for Base Data Access Objects + * @param Type of Base Entity + * @param Type of Dao Base Implementation + * @author Jeroen Meulemeester + */ +public abstract class BaseDaoTest> { + + /** + * The number of entities stored before each test + */ + private static final int INITIAL_COUNT = 5; + + /** + * The unique id generator, shared between all entities + */ + private static final AtomicInteger ID_GENERATOR = new AtomicInteger(); + + /** + * Factory, used to create new entity instances with the given name + */ + private final Function factory; + + /** + * The tested data access object + */ + private final D dao; + + /** + * Create a new test using the given factory and dao + * + * @param factory The factory, used to create new entity instances with the given name + * @param dao The tested data access object + */ + public BaseDaoTest(final Function factory, final D dao) { + this.factory = factory; + this.dao = dao; + } + + @Before + public void setUp() throws Exception { + for (int i = 0; i < INITIAL_COUNT; i++) { + final String className = dao.persistentClass.getSimpleName(); + final String entityName = String.format("%s%d", className, ID_GENERATOR.incrementAndGet()); + this.dao.persist(this.factory.apply(entityName)); + } + } + + @After + public void tearDown() throws Exception { + HibernateUtil.dropSession(); + } + + protected final D getDao() { + return this.dao; + } + + @Test + public void testFind() throws Exception { + final List all = this.dao.findAll(); + for (final E entity : all) { + final E byId = this.dao.find(entity.getId()); + assertNotNull(byId); + assertEquals(byId.getId(), byId.getId()); + } + } + + @Test + public void testDelete() throws Exception { + final List originalEntities = this.dao.findAll(); + this.dao.delete(originalEntities.get(1)); + this.dao.delete(originalEntities.get(2)); + + final List entitiesLeft = this.dao.findAll(); + assertNotNull(entitiesLeft); + assertEquals(INITIAL_COUNT - 2, entitiesLeft.size()); + } + + @Test + public void testFindAll() throws Exception { + final List all = this.dao.findAll(); + assertNotNull(all); + assertEquals(INITIAL_COUNT, all.size()); + } + + @Test + public void testSetId() throws Exception { + final E entity = this.factory.apply("name"); + assertNull(entity.getId()); + + final Long expectedId = Long.valueOf(1); + entity.setId(expectedId); + assertEquals(expectedId, entity.getId()); + } + + @Test + public void testSetName() throws Exception { + final E entity = this.factory.apply("name"); + assertEquals("name", entity.getName()); + assertEquals("name", entity.toString()); + + final String expectedName = "new name"; + entity.setName(expectedName); + assertEquals(expectedName, entity.getName()); + assertEquals(expectedName, entity.toString()); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java new file mode 100644 index 0000000000..05ad6f8879 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/magic/MagicServiceImplTest.java @@ -0,0 +1,160 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.magic; + +import com.iluwatar.servicelayer.spell.Spell; +import com.iluwatar.servicelayer.spell.SpellDao; +import com.iluwatar.servicelayer.spellbook.Spellbook; +import com.iluwatar.servicelayer.spellbook.SpellbookDao; +import com.iluwatar.servicelayer.wizard.Wizard; +import com.iluwatar.servicelayer.wizard.WizardDao; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 12:06 AM + * + * @author Jeroen Meulemeester + */ +public class MagicServiceImplTest { + + @Test + public void testFindAllWizards() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllWizards(); + verify(wizardDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindAllSpellbooks() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllSpellbooks(); + verify(spellbookDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindAllSpells() throws Exception { + final WizardDao wizardDao = mock(WizardDao.class); + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao); + + service.findAllSpells(); + verify(spellDao).findAll(); + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindWizardsWithSpellbook() throws Exception { + final String bookname = "bookname"; + final Spellbook spellbook = mock(Spellbook.class); + final Set wizards = new HashSet<>(); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + + when(spellbook.getWizards()).thenReturn(wizards); + + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + when(spellbookDao.findByName(eq(bookname))).thenReturn(spellbook); + + final WizardDao wizardDao = mock(WizardDao.class); + final SpellDao spellDao = mock(SpellDao.class); + + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); + + final List result = service.findWizardsWithSpellbook(bookname); + verify(spellbookDao).findByName(eq(bookname)); + verify(spellbook).getWizards(); + + assertNotNull(result); + assertEquals(3, result.size()); + + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + + @Test + public void testFindWizardsWithSpell() throws Exception { + final Set wizards = new HashSet<>(); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + wizards.add(mock(Wizard.class)); + + final Spellbook spellbook = mock(Spellbook.class); + when(spellbook.getWizards()).thenReturn(wizards); + + final SpellbookDao spellbookDao = mock(SpellbookDao.class); + final WizardDao wizardDao = mock(WizardDao.class); + + final Spell spell = mock(Spell.class); + when(spell.getSpellbook()).thenReturn(spellbook); + + final String spellName = "spellname"; + final SpellDao spellDao = mock(SpellDao.class); + when(spellDao.findByName(eq(spellName))).thenReturn(spell); + + final MagicServiceImpl service = new MagicServiceImpl(wizardDao, spellbookDao, spellDao); + verifyZeroInteractions(wizardDao, spellbookDao, spellDao, spellbook); + + final List result = service.findWizardsWithSpell(spellName); + verify(spellDao).findByName(eq(spellName)); + verify(spellbook).getWizards(); + + assertNotNull(result); + assertEquals(3, result.size()); + + verifyNoMoreInteractions(wizardDao, spellbookDao, spellDao); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java new file mode 100644 index 0000000000..b6b4917c8f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spell/SpellDaoImplTest.java @@ -0,0 +1,57 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.spell; + +import com.iluwatar.servicelayer.common.BaseDaoTest; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/28/15 - 11:02 PM + * + * @author Jeroen Meulemeester + */ +public class SpellDaoImplTest extends BaseDaoTest { + + public SpellDaoImplTest() { + super(Spell::new, new SpellDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final SpellDaoImpl dao = getDao(); + final List allSpells = dao.findAll(); + for (final Spell spell : allSpells) { + final Spell spellByName = dao.findByName(spell.getName()); + assertNotNull(spellByName); + assertEquals(spell.getId(), spellByName.getId()); + assertEquals(spell.getName(), spellByName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java new file mode 100644 index 0000000000..fb7eca15a7 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/spellbook/SpellbookDaoImplTest.java @@ -0,0 +1,57 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.spellbook; + +import com.iluwatar.servicelayer.common.BaseDaoTest; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/28/15 - 11:44 PM + * + * @author Jeroen Meulemeester + */ +public class SpellbookDaoImplTest extends BaseDaoTest { + + public SpellbookDaoImplTest() { + super(Spellbook::new, new SpellbookDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final SpellbookDaoImpl dao = getDao(); + final List allBooks = dao.findAll(); + for (final Spellbook book : allBooks) { + final Spellbook spellByName = dao.findByName(book.getName()); + assertNotNull(spellByName); + assertEquals(book.getId(), spellByName.getId()); + assertEquals(book.getName(), spellByName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java new file mode 100644 index 0000000000..64bd72c7aa --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-layer/src/test/java/com/iluwatar/servicelayer/wizard/WizardDaoImplTest.java @@ -0,0 +1,57 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelayer.wizard; + +import com.iluwatar.servicelayer.common.BaseDaoTest; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/28/15 - 11:46 PM + * + * @author Jeroen Meulemeester + */ +public class WizardDaoImplTest extends BaseDaoTest { + + public WizardDaoImplTest() { + super(Wizard::new, new WizardDaoImpl()); + } + + @Test + public void testFindByName() throws Exception { + final WizardDaoImpl dao = getDao(); + final List allWizards = dao.findAll(); + for (final Wizard spell : allWizards) { + final Wizard byName = dao.findByName(spell.getName()); + assertNotNull(byName); + assertEquals(spell.getId(), byName.getId()); + assertEquals(spell.getName(), byName.getName()); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java new file mode 100644 index 0000000000..1228898f29 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelocator; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java new file mode 100644 index 0000000000..5dbbcdaf7f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/service-locator/src/test/java/com/iluwatar/servicelocator/ServiceLocatorTest.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.servicelocator; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/29/15 - 19:07 PM + * + * @author Jeroen Meulemeester + */ +public class ServiceLocatorTest { + + /** + * Verify if we just receive 'null' when requesting a non-existing service + */ + @Test + public void testGetNonExistentService() { + assertNull(ServiceLocator.getService("fantastic/unicorn/service")); + assertNull(ServiceLocator.getService("another/fantastic/unicorn/service")); + } + + /** + * Verify if we get the same cached instance when requesting the same service twice + */ + @Test + public void testServiceCache() { + final String[] serviceNames = new String[]{ + "jndi/serviceA", "jndi/serviceB" + }; + + for (final String serviceName : serviceNames) { + final Service service = ServiceLocator.getService(serviceName); + assertNotNull(service); + assertEquals(serviceName, service.getName()); + assertTrue(service.getId() > 0); // The id is generated randomly, but the minimum value is '1' + assertSame(service, ServiceLocator.getService(serviceName)); + } + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/AppTest.java new file mode 100644 index 0000000000..951c5c4fd3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.singleton; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java new file mode 100644 index 0000000000..f468ad0b8e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/singleton/src/test/java/com/iluwatar/singleton/SingletonTest.java @@ -0,0 +1,109 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.singleton; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Supplier; +import org.junit.Test; + +/** + * This class provides several test case that test singleton construction. + * + * The first proves that multiple calls to the singleton getInstance object are the same when called + * in the SAME thread. The second proves that multiple calls to the singleton getInstance object are + * the same when called in the DIFFERENT thread. + * + * Date: 12/29/15 - 19:25 PM + * @param Supplier method generating singletons + * @author Jeroen Meulemeester + * @author Richard Jones + */ +public abstract class SingletonTest { + + /** + * The singleton's getInstance method + */ + private final Supplier singletonInstanceMethod; + + /** + * Create a new singleton test instance using the given 'getInstance' method + * + * @param singletonInstanceMethod The singleton's getInstance method + */ + public SingletonTest(final Supplier singletonInstanceMethod) { + this.singletonInstanceMethod = singletonInstanceMethod; + } + + /** + * Test the singleton in a non-concurrent setting + */ + @Test + public void testMultipleCallsReturnTheSameObjectInSameThread() { + // Create several instances in the same calling thread + S instance1 = this.singletonInstanceMethod.get(); + S instance2 = this.singletonInstanceMethod.get(); + S instance3 = this.singletonInstanceMethod.get(); + // now check they are equal + assertSame(instance1, instance2); + assertSame(instance1, instance3); + assertSame(instance2, instance3); + } + + /** + * Test singleton instance in a concurrent setting + */ + @Test(timeout = 10000) + public void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception { + + // Create 10000 tasks and inside each callable instantiate the singleton class + final List> tasks = new ArrayList<>(); + for (int i = 0; i < 10000; i++) { + tasks.add(this.singletonInstanceMethod::get); + } + + // Use up to 8 concurrent threads to handle the tasks + final ExecutorService executorService = Executors.newFixedThreadPool(8); + final List> results = executorService.invokeAll(tasks); + + // wait for all of the threads to complete + final S expectedInstance = this.singletonInstanceMethod.get(); + for (Future res : results) { + final S instance = res.get(); + assertNotNull(instance); + assertSame(expectedInstance, instance); + } + + // tidy up the executor + executorService.shutdown(); + + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/app/AppTest.java new file mode 100644 index 0000000000..a111016706 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/app/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.app; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java new file mode 100644 index 0000000000..1c969891b1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/creature/CreatureTest.java @@ -0,0 +1,133 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.creature; + +import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Movement; +import com.iluwatar.specification.property.Size; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/29/15 - 7:47 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class CreatureTest { + + /** + * @return The tested {@link Creature} instance and its expected specs + */ + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList( + new Object[]{new Dragon(), "Dragon", Size.LARGE, Movement.FLYING, Color.RED}, + new Object[]{new Goblin(), "Goblin", Size.SMALL, Movement.WALKING, Color.GREEN}, + new Object[]{new KillerBee(), "KillerBee", Size.SMALL, Movement.FLYING, Color.LIGHT}, + new Object[]{new Octopus(), "Octopus", Size.NORMAL, Movement.SWIMMING, Color.DARK}, + new Object[]{new Shark(), "Shark", Size.NORMAL, Movement.SWIMMING, Color.LIGHT}, + new Object[]{new Troll(), "Troll", Size.LARGE, Movement.WALKING, Color.DARK} + ); + } + + /** + * The tested creature + */ + private final Creature testedCreature; + + /** + * The expected name of the tested creature + */ + private final String name; + + /** + * The expected size of the tested creature + */ + private final Size size; + + /** + * The expected movement type of the tested creature + */ + private final Movement movement; + + /** + * The expected color of the tested creature + */ + private final Color color; + + /** + * @param testedCreature The tested creature + * @param name The expected name of the creature + * @param size The expected size of the creature + * @param movement The expected movement type of the creature + * @param color The expected color of the creature + */ + public CreatureTest(final Creature testedCreature, final String name, final Size size, + final Movement movement, final Color color) { + this.testedCreature = testedCreature; + this.name = name; + this.size = size; + this.movement = movement; + this.color = color; + } + + + @Test + public void testGetName() throws Exception { + assertEquals(this.name, this.testedCreature.getName()); + } + + @Test + public void testGetSize() throws Exception { + assertEquals(this.size, this.testedCreature.getSize()); + } + + @Test + public void testGetMovement() throws Exception { + assertEquals(this.movement, this.testedCreature.getMovement()); + } + + @Test + public void testGetColor() throws Exception { + assertEquals(this.color, this.testedCreature.getColor()); + } + + @Test + public void testToString() throws Exception { + final String toString = this.testedCreature.toString(); + assertNotNull(toString); + assertEquals( + String.format("%s [size=%s, movement=%s, color=%s]", name, size, movement, color), + toString + ); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java new file mode 100644 index 0000000000..52b176915a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/ColorSelectorTest.java @@ -0,0 +1,59 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Color; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:35 PM + * + * @author Jeroen Meulemeester + */ +public class ColorSelectorTest { + + /** + * Verify if the color selector gives the correct results + */ + @Test + public void testColor() { + final Creature greenCreature = mock(Creature.class); + when(greenCreature.getColor()).thenReturn(Color.GREEN); + + final Creature redCreature = mock(Creature.class); + when(redCreature.getColor()).thenReturn(Color.RED); + + final ColorSelector greenSelector = new ColorSelector(Color.GREEN); + assertTrue(greenSelector.test(greenCreature)); + assertFalse(greenSelector.test(redCreature)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java new file mode 100644 index 0000000000..b9e86193eb --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/MovementSelectorTest.java @@ -0,0 +1,60 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Color; +import com.iluwatar.specification.property.Movement; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:37 PM + * + * @author Jeroen Meulemeester + */ +public class MovementSelectorTest { + + /** + * Verify if the movement selector gives the correct results + */ + @Test + public void testMovement() { + final Creature swimmingCreature = mock(Creature.class); + when(swimmingCreature.getMovement()).thenReturn(Movement.SWIMMING); + + final Creature flyingCreature = mock(Creature.class); + when(flyingCreature.getMovement()).thenReturn(Movement.FLYING); + + final MovementSelector swimmingSelector = new MovementSelector(Movement.SWIMMING); + assertTrue(swimmingSelector.test(swimmingCreature)); + assertFalse(swimmingSelector.test(flyingCreature)); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java new file mode 100644 index 0000000000..f2b6b80b7e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/specification/src/test/java/com/iluwatar/specification/selector/SizeSelectorTest.java @@ -0,0 +1,58 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.specification.selector; + +import com.iluwatar.specification.creature.Creature; +import com.iluwatar.specification.property.Size; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Date: 12/29/15 - 7:43 PM + * + * @author Jeroen Meulemeester + */ +public class SizeSelectorTest { + + /** + * Verify if the size selector gives the correct results + */ + @Test + public void testMovement() { + final Creature normalCreature = mock(Creature.class); + when(normalCreature.getSize()).thenReturn(Size.NORMAL); + + final Creature smallCreature = mock(Creature.class); + when(smallCreature.getSize()).thenReturn(Size.SMALL); + + final SizeSelector normalSelector = new SizeSelector(Size.NORMAL); + assertTrue(normalSelector.test(normalCreature)); + assertFalse(normalSelector.test(smallCreature)); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/AppTest.java new file mode 100644 index 0000000000..cb40d04813 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/MammothTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/MammothTest.java new file mode 100644 index 0000000000..60f4b18f47 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/state/src/test/java/com/iluwatar/state/MammothTest.java @@ -0,0 +1,120 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.state; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Date: 12/29/15 - 8:27 PM + * + * @author Jeroen Meulemeester + */ +public class MammothTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * Switch to a complete mammoth 'mood'-cycle and verify if the observed mood matches the expected + * value. + */ + @Test + public void testTimePasses() { + final Mammoth mammoth = new Mammoth(); + + mammoth.observe(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(1 , appender.getLogSize()); + + mammoth.timePasses(); + assertEquals("The mammoth gets angry!", appender.getLastMessage()); + assertEquals(2 , appender.getLogSize()); + + mammoth.observe(); + assertEquals("The mammoth is furious!", appender.getLastMessage()); + assertEquals(3 , appender.getLogSize()); + + mammoth.timePasses(); + assertEquals("The mammoth calms down.", appender.getLastMessage()); + assertEquals(4 , appender.getLogSize()); + + mammoth.observe(); + assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage()); + assertEquals(5 , appender.getLogSize()); + + } + + /** + * Verify if {@link Mammoth#toString()} gives the expected value + */ + @Test + public void testToString() { + final String toString = new Mammoth().toString(); + assertNotNull(toString); + assertEquals("The mammoth", toString); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java new file mode 100644 index 0000000000..af1ddfb58f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.stepbuilder; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java new file mode 100644 index 0000000000..962feeabb6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/step-builder/src/test/java/com/iluwatar/stepbuilder/CharacterStepBuilderTest.java @@ -0,0 +1,177 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.stepbuilder; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Date: 12/29/15 - 9:21 PM + * + * @author Jeroen Meulemeester + */ +public class CharacterStepBuilderTest { + + /** + * Build a new wizard {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .withAbility("invisibility") + .withAbility("wisdom") + .noMoreAbilities() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertEquals("poison", character.getSpell()); + assertNotNull(character.toString()); + + final List abilities = character.getAbilities(); + assertNotNull(abilities); + assertEquals(2, abilities.size()); + assertTrue(abilities.contains("invisibility")); + assertTrue(abilities.contains("wisdom")); + + } + + /** + * Build a new wizard {@link Character} without spell or abilities and verify if it has the + * expected attributes + */ + @Test + public void testBuildPoorWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .noSpell() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertNull(character.getSpell()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + /** + * Build a new wizard {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWeakWizard() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Merlin") + .wizardClass("alchemist") + .withSpell("poison") + .noAbilities() + .build(); + + assertEquals("Merlin", character.getName()); + assertEquals("alchemist", character.getWizardClass()); + assertEquals("poison", character.getSpell()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + + /** + * Build a new warrior {@link Character} and verify if it has the expected attributes + */ + @Test + public void testBuildWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Cuauhtemoc") + .fighterClass("aztec") + .withWeapon("spear") + .withAbility("speed") + .withAbility("strength") + .noMoreAbilities() + .build(); + + assertEquals("Cuauhtemoc", character.getName()); + assertEquals("aztec", character.getFighterClass()); + assertEquals("spear", character.getWeapon()); + assertNotNull(character.toString()); + + final List abilities = character.getAbilities(); + assertNotNull(abilities); + assertEquals(2, abilities.size()); + assertTrue(abilities.contains("speed")); + assertTrue(abilities.contains("strength")); + + } + + /** + * Build a new wizard {@link Character} without weapon and abilities and verify if it has the + * expected attributes + */ + @Test + public void testBuildPoorWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Poor warrior") + .fighterClass("none") + .noWeapon() + .build(); + + assertEquals("Poor warrior", character.getName()); + assertEquals("none", character.getFighterClass()); + assertNull(character.getWeapon()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + + /** + * Build a new warrior {@link Character} without any abilities, but with a weapon and verify if it + * has the expected attributes + */ + @Test + public void testBuildWeakWarrior() { + final Character character = CharacterStepBuilder.newBuilder() + .name("Weak warrior") + .fighterClass("none") + .withWeapon("Slingshot") + .noAbilities() + .build(); + + assertEquals("Weak warrior", character.getName()); + assertEquals("none", character.getFighterClass()); + assertEquals("Slingshot", character.getWeapon()); + assertNull(character.getAbilities()); + assertNotNull(character.toString()); + + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/AppTest.java new file mode 100644 index 0000000000..59b3a22a95 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java new file mode 100644 index 0000000000..ad8b9784fe --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayerTest.java @@ -0,0 +1,70 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/29/15 - 10:50 PM + * + * @author Jeroen Meulemeester + */ +public class DragonSlayerTest { + + /** + * Verify if the dragon slayer uses the strategy during battle + */ + @Test + public void testGoToBattle() { + final DragonSlayingStrategy strategy = mock(DragonSlayingStrategy.class); + final DragonSlayer dragonSlayer = new DragonSlayer(strategy); + + dragonSlayer.goToBattle(); + verify(strategy).execute(); + verifyNoMoreInteractions(strategy); + } + + /** + * Verify if the dragon slayer uses the new strategy during battle after a change of strategy + */ + @Test + public void testChangeStrategy() throws Exception { + final DragonSlayingStrategy initialStrategy = mock(DragonSlayingStrategy.class); + final DragonSlayer dragonSlayer = new DragonSlayer(initialStrategy); + + dragonSlayer.goToBattle(); + verify(initialStrategy).execute(); + + final DragonSlayingStrategy newStrategy = mock(DragonSlayingStrategy.class); + dragonSlayer.changeStrategy(newStrategy); + + dragonSlayer.goToBattle(); + verify(newStrategy).execute(); + + verifyNoMoreInteractions(initialStrategy, newStrategy); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java new file mode 100644 index 0000000000..52e596e5c1 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/strategy/src/test/java/com/iluwatar/strategy/DragonSlayingStrategyTest.java @@ -0,0 +1,136 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.strategy; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * Date: 12/29/15 - 10:58 PM + * + * @author Jeroen Meulemeester + */ +@RunWith(Parameterized.class) +public class DragonSlayingStrategyTest { + + /** + * @return The test parameters for each cycle + */ + @Parameterized.Parameters + public static Collection data() { + return Arrays.asList( + new Object[]{ + new MeleeStrategy(), + "With your Excalibur you sever the dragon's head!" + }, + new Object[]{ + new ProjectileStrategy(), + "You shoot the dragon with the magical crossbow and it falls dead on the ground!" + }, + new Object[]{ + new SpellStrategy(), + "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!" + } + ); + } + + /** + * The tested strategy + */ + private final DragonSlayingStrategy strategy; + + /** + * The expected action in the log + */ + private final String expectedResult; + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + + /** + * Create a new test instance for the given strategy + * + * @param strategy The tested strategy + * @param expectedResult The expected result + */ + public DragonSlayingStrategyTest(final DragonSlayingStrategy strategy, final String expectedResult) { + this.strategy = strategy; + this.expectedResult = expectedResult; + } + + /** + * Test if executing the strategy gives the correct response + */ + @Test + public void testExecute() { + this.strategy.execute(); + assertEquals(this.expectedResult, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java new file mode 100644 index 0000000000..da85062f56 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java new file mode 100644 index 0000000000..6cc80446c0 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/HalflingThiefTest.java @@ -0,0 +1,72 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * Date: 12/29/15 - 18:15 PM + * + * @author Jeroen Meulemeester + */ +public class HalflingThiefTest { + + /** + * Verify if the thief uses the provided stealing method + */ + @Test + public void testSteal() { + final StealingMethod method = mock(StealingMethod.class); + final HalflingThief thief = new HalflingThief(method); + + thief.steal(); + verify(method).steal(); + + verifyNoMoreInteractions(method); + } + + /** + * Verify if the thief uses the provided stealing method, and the new method after changing it + */ + @Test + public void testChangeMethod() { + final StealingMethod initialMethod = mock(StealingMethod.class); + final HalflingThief thief = new HalflingThief(initialMethod); + + thief.steal(); + verify(initialMethod).steal(); + + final StealingMethod newMethod = mock(StealingMethod.class); + thief.changeMethod(newMethod); + + thief.steal(); + verify(newMethod).steal(); + + verifyNoMoreInteractions(initialMethod, newMethod); + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java new file mode 100644 index 0000000000..98ac62613e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/template-method/src/test/java/com/iluwatar/templatemethod/StealingMethodTest.java @@ -0,0 +1,171 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.templatemethod; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/30/15 - 18:12 PM + * @param Type of StealingMethod + * @author Jeroen Meulemeester + */ +public abstract class StealingMethodTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * The tested stealing method + */ + private final M method; + + /** + * The expected target + */ + private final String expectedTarget; + + /** + * The expected target picking result + */ + private final String expectedTargetResult; + + /** + * The expected confusion method + */ + private final String expectedConfuseMethod; + + /** + * The expected stealing method + */ + private final String expectedStealMethod; + + /** + * Create a new test for the given stealing method, together with the expected results + * + * @param method The tested stealing method + * @param expectedTarget The expected target name + * @param expectedTargetResult The expected target picking result + * @param expectedConfuseMethod The expected confusion method + * @param expectedStealMethod The expected stealing method + */ + public StealingMethodTest(final M method, String expectedTarget, final String expectedTargetResult, + final String expectedConfuseMethod, final String expectedStealMethod) { + + this.method = method; + this.expectedTarget = expectedTarget; + this.expectedTargetResult = expectedTargetResult; + this.expectedConfuseMethod = expectedConfuseMethod; + this.expectedStealMethod = expectedStealMethod; + } + + /** + * Verify if the thief picks the correct target + */ + @Test + public void testPickTarget() { + assertEquals(expectedTarget, this.method.pickTarget()); + } + + /** + * Verify if the target confusing step goes as planned + */ + @Test + public void testConfuseTarget() { + assertEquals(0, appender.getLogSize()); + + this.method.confuseTarget(this.expectedTarget); + assertEquals(this.expectedConfuseMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Verify if the stealing step goes as planned + */ + @Test + public void testStealTheItem() { + assertEquals(0, appender.getLogSize()); + + this.method.stealTheItem(this.expectedTarget); + assertEquals(this.expectedStealMethod, appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + + /** + * Verify if the complete steal process goes as planned + */ + @Test + public void testSteal() { + this.method.steal(); + + assertTrue(appender.logContains(this.expectedTargetResult)); + assertTrue(appender.logContains(this.expectedConfuseMethod)); + assertTrue(appender.logContains(this.expectedStealMethod)); + assertEquals(3, appender.getLogSize()); + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java new file mode 100644 index 0000000000..2d21eec12e --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import org.junit.Test; + +/** + * Application test + * + * @author ilkka + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java new file mode 100644 index 0000000000..4a2a06de8c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java @@ -0,0 +1,145 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.function.ToIntFunction; +import java.util.stream.Collectors; +import org.junit.Test; + +/** + * Date: 12/30/15 - 18:22 PM + * Test for Tasks using a Thread Pool + * @param Type of Task + * @author Jeroen Meulemeester + */ +public abstract class TaskTest { + + /** + * The number of tasks used during the concurrency test + */ + private static final int TASK_COUNT = 128 * 1024; + + /** + * The number of threads used during the concurrency test + */ + private static final int THREAD_COUNT = 8; + + /** + * The task factory, used to create new test items + */ + private final IntFunction factory; + + /** + * The expected time needed to run the task 1 single time, in milli seconds + */ + private final int expectedExecutionTime; + + /** + * Create a new test instance + * + * @param factory The task factory, used to create new test items + * @param expectedExecutionTime The expected time needed to run the task 1 time, in milli seconds + */ + public TaskTest(final IntFunction factory, final int expectedExecutionTime) { + this.factory = factory; + this.expectedExecutionTime = expectedExecutionTime; + } + + /** + * Verify if the generated id is unique for each task, even if the tasks are created in separate + * threads + */ + @Test(timeout = 10000) + public void testIdGeneration() throws Exception { + final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT); + + final List> tasks = new ArrayList<>(); + for (int i = 0; i < TASK_COUNT; i++) { + tasks.add(() -> factory.apply(1).getId()); + } + + final List ids = service.invokeAll(tasks) + .stream() + .map(TaskTest::get) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + + service.shutdownNow(); + + final long uniqueIdCount = ids.stream() + .distinct() + .count(); + + assertEquals(TASK_COUNT, ids.size()); + assertEquals(TASK_COUNT, uniqueIdCount); + + } + + /** + * Verify if the time per execution of a task matches the actual time required to execute the task + * a given number of times + */ + @Test + public void testTimeMs() { + for (int i = 0; i < 10; i++) { + assertEquals(this.expectedExecutionTime * i, this.factory.apply(i).getTimeMs()); + } + } + + /** + * Verify if the task has some sort of {@link T#toString()}, different from 'null' + */ + @Test + public void testToString() { + assertNotNull(this.factory.apply(0).toString()); + } + + /** + * Extract the result from a future or returns 'null' when an exception occurred + * + * @param future The future we want the result from + * @param The result type + * @return The result or 'null' when a checked exception occurred + */ + private static O get(Future future) { + try { + return future.get(); + } catch (InterruptedException | ExecutionException e) { + return null; + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java new file mode 100644 index 0000000000..81962ab2aa --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/thread-pool/src/test/java/com/iluwatar/threadpool/WorkerTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.threadpool; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/30/15 - 18:21 PM + * + * @author Jeroen Meulemeester + */ +public class WorkerTest { + + /** + * Verify if a worker does the actual job + */ + @Test + public void testRun() { + final Task task = mock(Task.class); + final Worker worker = new Worker(task); + verifyZeroInteractions(task); + + worker.run(); + verify(task).getTimeMs(); + verifyNoMoreInteractions(task); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/AppTest.java new file mode 100644 index 0000000000..37c8e75ece --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + final String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java new file mode 100644 index 0000000000..aaab62b3a6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/B2BServiceTest.java @@ -0,0 +1,48 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import org.junit.Assert; +import org.junit.Test; + +import com.iluwatar.throttling.timer.ThrottleTimerImpl; +import com.iluwatar.throttling.timer.Throttler; + +/** + * B2BServiceTest class to test the B2BService + */ +public class B2BServiceTest { + + @Test + public void dummyCustomerApiTest() { + Tenant tenant = new Tenant("testTenant", 2); + Throttler timer = new ThrottleTimerImpl(100); + B2BService service = new B2BService(timer); + + for (int i = 0; i < 5; i++) { + service.dummyCustomerApi(tenant); + } + long counter = CallsCount.getCount(tenant.getName()); + Assert.assertTrue("Counter limit must be reached", counter == 2); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java new file mode 100644 index 0000000000..2f0b5cf12a --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/throttling/src/test/java/com/iluwatar/throttling/TenantTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2014 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.throttling; + +import org.junit.Test; + +import com.iluwatar.throttling.Tenant; + +import java.security.InvalidParameterException; + +/** + * TenantTest to test the creation of Tenant with valid parameters. + */ +public class TenantTest { + + @Test(expected = InvalidParameterException.class) + public void constructorTest() { + Tenant tenant = new Tenant("FailTenant", -1); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/AppTest.java new file mode 100644 index 0000000000..073c0988a8 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/AppTest.java @@ -0,0 +1,40 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import org.junit.Test; + +/** + * Tests that thread local storage example runs without errors. + * + * @author Thomas Bauer, January 2017 + * + */ +public class AppTest { + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java new file mode 100644 index 0000000000..b4f24be9bc --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTest.java @@ -0,0 +1,144 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * After a successful run 5 date values should be in the result object. All dates should have + * the same value (15.11.2015). To avoid problems with time zone not the date instances themselves + * are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTest { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdDateValues = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by the run of DateFormatRunnalbe + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + createdDateValues = convertDatesToString(result); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new ArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + */ + @Test + public void testDateValues() { + assertEquals(expectedDateValues, createdDateValues); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver 5 date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should deliver + * no exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java new file mode 100644 index 0000000000..e0a1507e91 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestIncorrectDateFormat.java @@ -0,0 +1,127 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is tested with only one thread (i.e. without concurrency situation) + *

+ * An incorrect formatted date is passed to the Callable + * After a successful run 0 date values and 5 exceptions should be in the result object. + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestIncorrectDateFormat { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result result; + + /** + * The date values created by the run of DateFormatRunnalbe. List will be filled in the setup() method + */ + static List createdExceptions = new ArrayList(); + + /** + * Expected number of date values in the date value list created by the run of DateFormatRunnalbe + */ + int expectedCounterDateValues = 0; + + /** + * Expected number of exceptions in the exception list created by the run of DateFormatRunnalbe. + */ + int expectedCounterExceptions = 5; + + /** + * Expected content of the list containing the exceptions created by the run of DateFormatRunnalbe + */ + List expectedExceptions = Arrays.asList("class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\"", + "class java.text.ParseException: Unparseable date: \"15.12.2015\""); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + public static void setup() { + // Create a callable. Pass a string date value not matching the format string + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15.12.2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult = executor.submit(callableDf); + try { + result = futureResult.get(); + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + /** + * Test Exceptions after the run of DateFormatRunnalbe. A correct run should deliver 5 times the + * same exception + */ + @Test + public void testExecptions() { + assertEquals(expectedExceptions, result.getExceptionList()); + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should deliver no date values + */ + @Test + public void testCounterDateValues() { + assertEquals(expectedCounterDateValues, result.getDateList().size()); + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 exceptions + */ + @Test + public void testCounterExceptions() { + assertEquals(expectedCounterExceptions, result.getExceptionList().size()); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java new file mode 100644 index 0000000000..635d6f25ad --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tls/src/test/java/com/iluwatar/tls/DateFormatCallableTestMultiThread.java @@ -0,0 +1,164 @@ +/** + * The MIT License + * Copyright (c) 2016 Thomas Bauer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +package com.iluwatar.tls; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +/** + * + * Test of the Callable + * + * In this test {@link DateFormatCallable} is used by 4 threads in parallel + *

+ * After a successful run 5 date values should be in the result object of each thread. All dates + * should have the same value (15.11.2015). To avoid problems with time zone not the date instances + * themselves are compared by the test. For the test the dates are converted into string format DD.MM.YYY + *

+ * Additionally the number of list entries are tested for both the list with the date values + * and the list with the exceptions + * + * @author Thomas Bauer, January 2017 + * + */ +public class DateFormatCallableTestMultiThread { + + // Class variables used in setup() have to be static because setup() has to be static + /** + * Result object given back by DateFormatCallable, one for each thread + * -- Array with converted date values + * -- Array with thrown exceptions + */ + static Result[] result = new Result[4]; + + /** + * The date values created by the run of of DateFormatRunnalbe. List will be filled in the setup() method + */ + @SuppressWarnings("serial") + static class StringArrayList extends ArrayList { + /* nothing needed here */ + } + static List[] createdDateValues = new StringArrayList[4]; + + /** + * Expected number of date values in the date value list created by each thread + */ + int expectedCounterDateValues = 5; + + /** + * Expected number of exceptions in the exception list created by each thread + */ + int expectedCounterExceptions = 0; + + /** + * Expected content of the list containing the date values created by each thread + */ + List expectedDateValues = Arrays.asList("15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015", "15.11.2015"); + + /** + * Run Callable and prepare results for usage in the test methods + */ + @BeforeClass + public static void setup() { + // Create a callable + DateFormatCallable callableDf = new DateFormatCallable("dd/MM/yyyy", "15/12/2015"); + // start thread using the Callable instance + ExecutorService executor = Executors.newCachedThreadPool(); + Future futureResult1 = executor.submit(callableDf); + Future futureResult2 = executor.submit(callableDf); + Future futureResult3 = executor.submit(callableDf); + Future futureResult4 = executor.submit(callableDf); + try { + result[0] = futureResult1.get(); + result[1] = futureResult2.get(); + result[2] = futureResult3.get(); + result[3] = futureResult4.get(); + for (int i = 0; i < result.length; i++) { + createdDateValues[i] = convertDatesToString(result[i]); + } + } catch (Exception e) { + fail("Setup failed: " + e); + } + executor.shutdown(); + } + + private static List convertDatesToString(Result res) { + // Format date value as DD.MM.YYYY + if (res == null || res.getDateList() == null || res.getDateList().size() == 0) { + return null; + } + List returnList = new StringArrayList(); + + for (Date dt : res.getDateList()) { + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + returnList.add(cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + cal.get(Calendar.YEAR)); + } + return returnList; + } + + /** + * Test date values after the run of DateFormatRunnalbe. A correct run should deliver 5 times 15.12.2015 + * by each thread + */ + @Test + public void testDateValues() { + for (int i = 0; i < createdDateValues.length; i++) { + assertEquals(expectedDateValues, createdDateValues[i]); + } + } + + /** + * Test number of dates in the list after the run of DateFormatRunnalbe. A correct run should + * deliver 5 date values by each thread + */ + @Test + public void testCounterDateValues() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterDateValues, result[i].getDateList().size()); + } + } + + /** + * Test number of Exceptions in the list after the run of DateFormatRunnalbe. A correct run should + * deliver no exceptions + */ + @Test + public void testCounterExceptions() { + for (int i = 0; i < result.length; i++) { + assertEquals(expectedCounterExceptions, result[i].getExceptionList().size()); + } + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java new file mode 100644 index 0000000000..f24393779c --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/AppTest.java @@ -0,0 +1,53 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.tolerantreader; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws ClassNotFoundException, IOException { + String[] args = {}; + App.main(args); + } + + @Before + @After + public void cleanup() { + File file1 = new File("fish1.out"); + file1.delete(); + File file2 = new File("fish2.out"); + file2.delete(); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java new file mode 100644 index 0000000000..a6c7fc641f --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/tolerant-reader/src/test/java/com/iluwatar/tolerantreader/RainbowFishSerializerTest.java @@ -0,0 +1,90 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.tolerantreader; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; + +/** + * Date: 12/30/15 - 18:39 PM + * + * @author Jeroen Meulemeester + */ +public class RainbowFishSerializerTest { + + /** + * Create a temporary folder, used to generate files in during this test + */ + @Rule + public final TemporaryFolder testFolder = new TemporaryFolder(); + + /** + * Rainbow fish version 1 used during the tests + */ + private static final RainbowFish V1 = new RainbowFish("version1", 1, 2, 3); + + /** + * Rainbow fish version 2 used during the tests + */ + private static final RainbowFishV2 V2 = new RainbowFishV2("version2", 4, 5, 6, true, false, true); + + /** + * Verify if a fish, written as version 1 can be read back as version 1 + */ + @Test + public void testWriteV1ReadV1() throws Exception { + final File outputFile = this.testFolder.newFile(); + RainbowFishSerializer.writeV1(V1, outputFile.getPath()); + + final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + assertNotSame(V1, fish); + assertEquals(V1.getName(), fish.getName()); + assertEquals(V1.getAge(), fish.getAge()); + assertEquals(V1.getLengthMeters(), fish.getLengthMeters()); + assertEquals(V1.getWeightTons(), fish.getWeightTons()); + + } + + /** + * Verify if a fish, written as version 2 can be read back as version 1 + */ + @Test + public void testWriteV2ReadV1() throws Exception { + final File outputFile = this.testFolder.newFile(); + RainbowFishSerializer.writeV2(V2, outputFile.getPath()); + + final RainbowFish fish = RainbowFishSerializer.readV1(outputFile.getPath()); + assertNotSame(V2, fish); + assertEquals(V2.getName(), fish.getName()); + assertEquals(V2.getAge(), fish.getAge()); + assertEquals(V2.getLengthMeters(), fish.getLengthMeters()); + assertEquals(V2.getWeightTons(), fish.getWeightTons()); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/AppTest.java new file mode 100644 index 0000000000..60e02e4c41 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() throws Exception { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallItemTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallItemTest.java new file mode 100644 index 0000000000..5dad024814 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallItemTest.java @@ -0,0 +1,132 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/30/15 - 18:44 PM + * + * @author Jeroen Meulemeester + */ +public class BallItemTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + @Test + public void testClick() { + final BallThread ballThread = mock(BallThread.class); + final BallItem ballItem = new BallItem(); + ballItem.setTwin(ballThread); + + final InOrder inOrder = inOrder(ballThread); + + for (int i = 0; i < 10; i++) { + ballItem.click(); + inOrder.verify(ballThread).suspendMe(); + + ballItem.click(); + inOrder.verify(ballThread).resumeMe(); + } + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testDoDraw() { + final BallItem ballItem = new BallItem(); + final BallThread ballThread = mock(BallThread.class); + ballItem.setTwin(ballThread); + + ballItem.draw(); + assertTrue(appender.logContains("draw")); + assertTrue(appender.logContains("doDraw")); + + verifyNoMoreInteractions(ballThread); + assertEquals(2, appender.getLogSize()); + } + + @Test + public void testMove() { + final BallItem ballItem = new BallItem(); + final BallThread ballThread = mock(BallThread.class); + ballItem.setTwin(ballThread); + + ballItem.move(); + assertTrue(appender.logContains("move")); + + verifyNoMoreInteractions(ballThread); + assertEquals(1, appender.getLogSize()); + } + + /** + * Logging Appender Implementation + */ + public class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public boolean logContains(String message) { + return log.stream().anyMatch(event -> event.getMessage().equals(message)); + } + + public int getLogSize() { + return log.size(); + } + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java new file mode 100644 index 0000000000..f531a24931 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/twin/src/test/java/com/iluwatar/twin/BallThreadTest.java @@ -0,0 +1,111 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.twin; + +import org.junit.Test; + +import static java.lang.Thread.UncaughtExceptionHandler; +import static java.lang.Thread.sleep; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; + +/** + * Date: 12/30/15 - 18:55 PM + * + * @author Jeroen Meulemeester + */ +public class BallThreadTest { + + /** + * Verify if the {@link BallThread} can be resumed + */ + @Test(timeout = 5000) + public void testSuspend() throws Exception { + final BallThread ballThread = new BallThread(); + + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); + + ballThread.start(); + + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); + ballThread.suspendMe(); + + sleep(1000); + + ballThread.stopMe(); + ballThread.join(); + + verifyNoMoreInteractions(ballItem); + } + + /** + * Verify if the {@link BallThread} can be resumed + */ + @Test(timeout = 5000) + public void testResume() throws Exception { + final BallThread ballThread = new BallThread(); + + final BallItem ballItem = mock(BallItem.class); + ballThread.setTwin(ballItem); + + ballThread.suspendMe(); + ballThread.start(); + + sleep(1000); + + verifyZeroInteractions(ballItem); + + ballThread.resumeMe(); + verify(ballItem, timeout(2000).atLeastOnce()).draw(); + verify(ballItem, timeout(2000).atLeastOnce()).move(); + + ballThread.stopMe(); + ballThread.join(); + + verifyNoMoreInteractions(ballItem); + } + + /** + * Verify if the {@link BallThread} is interruptible + */ + @Test(timeout = 5000) + public void testInterrupt() throws Exception { + final BallThread ballThread = new BallThread(); + final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class); + ballThread.setUncaughtExceptionHandler(exceptionHandler); + ballThread.setTwin(mock(BallItem.class)); + ballThread.start(); + ballThread.interrupt(); + ballThread.join(); + + verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class)); + verifyNoMoreInteractions(exceptionHandler); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/AppTest.java new file mode 100644 index 0000000000..cd0b1354f3 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/AppTest.java @@ -0,0 +1,37 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.value.object; + +import org.junit.Test; + +/** + * Application test + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java new file mode 100644 index 0000000000..b7b65b6c69 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/value-object/src/test/java/com/iluwatar/value/object/HeroStatTest.java @@ -0,0 +1,66 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.value.object; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; + +import static org.junit.Assert.assertThat; + +import com.google.common.testing.EqualsTester; + +import org.junit.Test; + +/** + * Unit test for HeroStat. + */ +public class HeroStatTest { + + /** + * Tester for equals() and hashCode() methods of a class. Using guava's EqualsTester. + * + * @see http://static.javadoc.io/com.google.guava/guava-testlib/19.0/com/google/common/testing/ + * EqualsTester.html + */ + @Test + public void testEquals() { + HeroStat heroStatA = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatB = HeroStat.valueOf(3, 9, 2); + new EqualsTester().addEqualityGroup(heroStatA, heroStatB).testEquals(); + } + + /** + * The toString() for two equal values must be the same. For two non-equal values it must be + * different. + */ + @Test + public void testToString() { + HeroStat heroStatA = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatB = HeroStat.valueOf(3, 9, 2); + HeroStat heroStatC = HeroStat.valueOf(3, 9, 8); + + assertThat(heroStatA.toString(), is(heroStatB.toString())); + assertThat(heroStatA.toString(), is(not(heroStatC.toString()))); + } + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/AppTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/AppTest.java new file mode 100644 index 0000000000..23c9bb48f6 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/AppTest.java @@ -0,0 +1,39 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import org.junit.Test; + +/** + * + * Application test + * + */ +public class AppTest { + + @Test + public void test() { + String[] args = {}; + App.main(args); + } +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java new file mode 100644 index 0000000000..ab84705122 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/UnitTest.java @@ -0,0 +1,82 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import java.util.Arrays; +import java.util.function.Function; +import org.junit.Test; + +/** + * Date: 12/30/15 - 18:59 PM + * Test related to Units + * @param Type of Unit + * @author Jeroen Meulemeester + */ +public abstract class UnitTest { + + /** + * Factory to create new instances of the tested unit + */ + private final Function factory; + + /** + * Create a new test instance for the given unit type {@link U} + * + * @param factory Factory to create new instances of the tested unit + */ + public UnitTest(final Function factory) { + this.factory = factory; + } + + @Test + public void testAccept() throws Exception { + final Unit[] children = new Unit[5]; + Arrays.setAll(children, (i) -> mock(Unit.class)); + + final U unit = this.factory.apply(children); + final UnitVisitor visitor = mock(UnitVisitor.class); + unit.accept(visitor); + verifyVisit(unit, visitor); + + for (final Unit child : children) { + verify(child).accept(eq(visitor)); + } + + verifyNoMoreInteractions(children); + verifyNoMoreInteractions(visitor); + } + + /** + * Verify if the correct visit method is called on the mock, depending on the tested instance + * + * @param unit The tested unit instance + * @param mockedVisitor The mocked {@link UnitVisitor} who should have gotten a visit by the unit + */ + abstract void verifyVisit(final U unit, final UnitVisitor mockedVisitor); + +} diff --git a/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java new file mode 100644 index 0000000000..ba6705b230 --- /dev/null +++ b/src/test/resources/oracle/commits/java-design-patterns-a20e54d0a7aceeffee5a96523ac7f3b8140b0def/visitor/src/test/java/com/iluwatar/visitor/VisitorTest.java @@ -0,0 +1,142 @@ +/** + * The MIT License + * Copyright (c) 2014-2016 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package com.iluwatar.visitor; + +import static org.junit.Assert.assertEquals; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; + +/** + * Date: 12/30/15 - 18:59 PM + * Test case for Visitor Pattern + * @param Type of UnitVisitor + * @author Jeroen Meulemeester + */ +public abstract class VisitorTest { + + private InMemoryAppender appender; + + @Before + public void setUp() { + appender = new InMemoryAppender(); + } + + @After + public void tearDown() { + appender.stop(); + } + + /** + * The tested visitor instance + */ + private final V visitor; + + /** + * The optional expected response when being visited by a commander + */ + private final Optional commanderResponse; + + /** + * The optional expected response when being visited by a sergeant + */ + private final Optional sergeantResponse; + + /** + * The optional expected response when being visited by a soldier + */ + private final Optional soldierResponse; + + /** + * Create a new test instance for the given visitor + * + * @param commanderResponse The optional expected response when being visited by a commander + * @param sergeantResponse The optional expected response when being visited by a sergeant + * @param soldierResponse The optional expected response when being visited by a soldier + */ + public VisitorTest(final V visitor, final Optional commanderResponse, + final Optional sergeantResponse, final Optional soldierResponse) { + + this.visitor = visitor; + this.commanderResponse = commanderResponse; + this.sergeantResponse = sergeantResponse; + this.soldierResponse = soldierResponse; + } + + @Test + public void testVisitCommander() { + this.visitor.visitCommander(new Commander()); + if (this.commanderResponse.isPresent()) { + assertEquals(this.commanderResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + @Test + public void testVisitSergeant() { + this.visitor.visitSergeant(new Sergeant()); + if (this.sergeantResponse.isPresent()) { + assertEquals(this.sergeantResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + @Test + public void testVisitSoldier() { + this.visitor.visitSoldier(new Soldier()); + if (this.soldierResponse.isPresent()) { + assertEquals(this.soldierResponse.get(), appender.getLastMessage()); + assertEquals(1, appender.getLogSize()); + } + } + + private class InMemoryAppender extends AppenderBase { + private List log = new LinkedList<>(); + + public InMemoryAppender() { + ((Logger) LoggerFactory.getLogger("root")).addAppender(this); + start(); + } + + @Override + protected void append(ILoggingEvent eventObject) { + log.add(eventObject); + } + + public int getLogSize() { + return log.size(); + } + + public String getLastMessage() { + return log.get(log.size() - 1).getFormattedMessage(); + } + } +} diff --git a/src/test/resources/oracle/commits/jmeter-c7279348335b820c35ee570462cb2e0b4eb1c370/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java b/src/test/resources/oracle/commits/jmeter-c7279348335b820c35ee570462cb2e0b4eb1c370/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java new file mode 100644 index 0000000000..0e19677881 --- /dev/null +++ b/src/test/resources/oracle/commits/jmeter-c7279348335b820c35ee570462cb2e0b4eb1c370/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jorphan; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.apache.jmeter.junit.JMeterTestCase; +import org.apache.jorphan.util.XMLBuffer; +import org.junit.jupiter.api.Test; + +public class TestXMLBuffer extends JMeterTestCase { + + @Test + public void test1() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("start"); + assertEquals("\n",xb.toString()); + } + + @Test + public void test2() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.tag("start","now"); + assertEquals("now\n",xb.toString()); + } + @Test + public void test3() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("abc"); + xb.closeTag("abc"); + assertEquals("\n",xb.toString()); + } + @Test + public void test4() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("abc"); + try { + xb.closeTag("abcd"); + fail("Should have caused IllegalArgumentException"); + } catch (IllegalArgumentException e) { + } + } +} diff --git a/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.json b/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.json new file mode 100644 index 0000000000..1a39077fa9 --- /dev/null +++ b/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9.json @@ -0,0 +1 @@ +{"parentCommitId":"c7279348335b820c35ee570462cb2e0b4eb1c370","currentCommitId":"d5b5b2f38c3341cbb934693c17d0574a241ad4f9","filesBefore":["src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java"],"filesCurrent":["src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["src/core/src/test","src/core/src/test/java/org","src/core/src/test/java/org/apache","src","src/core","src/core/src/test/java/org/apache/jorphan","src/core/src","src/core/src/test/java"],"repositoryDirectoriesCurrent":["src/core/src/test","src/core/src/test/java/org","src/core/src/test/java/org/apache","src","src/core","src/core/src/test/java/org/apache/jorphan","src/core/src","src/core/src/test/java"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java b/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java new file mode 100644 index 0000000000..52bd40d18e --- /dev/null +++ b/src/test/resources/oracle/commits/jmeter-d5b5b2f38c3341cbb934693c17d0574a241ad4f9/src/core/src/test/java/org/apache/jorphan/TestXMLBuffer.java @@ -0,0 +1,57 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jorphan; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import org.apache.jmeter.junit.JMeterTestCase; +import org.apache.jorphan.util.XMLBuffer; +import org.junit.jupiter.api.Test; + +public class TestXMLBuffer extends JMeterTestCase { + + @Test + public void test1() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("start"); + assertEquals("\n",xb.toString()); + } + + @Test + public void test2() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.tag("start","now"); + assertEquals("now\n",xb.toString()); + } + @Test + public void test3() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("abc"); + xb.closeTag("abc"); + assertEquals("\n",xb.toString()); + } + @Test + public void test4() throws Exception{ + XMLBuffer xb = new XMLBuffer(); + xb.openTag("abc"); + assertThrows(IllegalArgumentException.class, () -> { + xb.closeTag("abcd"); + }); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java new file mode 100644 index 0000000000..f01ffeb5f2 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java @@ -0,0 +1,604 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.bolt.v1.messaging; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetTime; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +import org.neo4j.bolt.messaging.BoltIOException; +import org.neo4j.bolt.messaging.Neo4jPack; +import org.neo4j.bolt.messaging.StructType; +import org.neo4j.bolt.v1.packstream.PackInput; +import org.neo4j.bolt.v1.packstream.PackOutput; +import org.neo4j.bolt.v1.packstream.PackStream; +import org.neo4j.bolt.v1.packstream.PackType; +import org.neo4j.kernel.api.exceptions.Status; +import org.neo4j.values.AnyValue; +import org.neo4j.values.AnyValueWriter; +import org.neo4j.values.storable.CoordinateReferenceSystem; +import org.neo4j.values.storable.TextArray; +import org.neo4j.values.storable.TextValue; +import org.neo4j.values.storable.Values; +import org.neo4j.values.virtual.ListValue; +import org.neo4j.values.virtual.MapValue; +import org.neo4j.values.virtual.MapValueBuilder; +import org.neo4j.values.virtual.NodeValue; +import org.neo4j.values.virtual.RelationshipValue; +import org.neo4j.values.virtual.VirtualValues; + +import static org.neo4j.bolt.v1.packstream.PackStream.UNKNOWN_SIZE; +import static org.neo4j.values.storable.Values.byteArray; + +/** + * Extended PackStream packer and unpacker classes for working + * with Neo4j-specific data types, represented as structures. + */ +public class Neo4jPackV1 implements Neo4jPack +{ + public static final long VERSION = 1; + + public static final byte NODE = 'N'; + public static final int NODE_SIZE = 3; + + public static final byte RELATIONSHIP = 'R'; + public static final int RELATIONSHIP_SIZE = 5; + + public static final byte UNBOUND_RELATIONSHIP = 'r'; + public static final int UNBOUND_RELATIONSHIP_SIZE = 3; + + public static final byte PATH = 'P'; + public static final int PATH_SIZE = 3; + + @Override + public Neo4jPack.Packer newPacker( PackOutput output ) + { + return new PackerV1( output ); + } + + @Override + public Neo4jPack.Unpacker newUnpacker( PackInput input ) + { + return new UnpackerV1( input ); + } + + @Override + public long version() + { + return VERSION; + } + + @Override + public String toString() + { + return getClass().getSimpleName(); + } + + protected static class PackerV1 extends PackStream.Packer implements AnyValueWriter, Neo4jPack.Packer + { + private static final int INITIAL_PATH_CAPACITY = 500; + private static final int NO_SUCH_ID = -1; + private final PrimitiveLongIntKeyValueArray nodeIndexes = + new PrimitiveLongIntKeyValueArray( INITIAL_PATH_CAPACITY + 1 ); + private final PrimitiveLongIntKeyValueArray relationshipIndexes = + new PrimitiveLongIntKeyValueArray( INITIAL_PATH_CAPACITY ); + + protected PackerV1( PackOutput output ) + { + super( output ); + } + + @Override + public void pack( AnyValue value ) throws IOException + { + value.writeTo( this ); + } + + @Override + public void writeNodeReference( long nodeId ) + { + throw new UnsupportedOperationException( "Cannot write a raw node reference" ); + } + + @Override + public void writeNode( long nodeId, TextArray labels, MapValue properties ) throws IOException + { + packStructHeader( NODE_SIZE, NODE ); + pack( nodeId ); + packListHeader( labels.length() ); + for ( int i = 0; i < labels.length(); i++ ) + { + labels.value( i ).writeTo( this ); + } + properties.writeTo( this ); + } + + @Override + public void writeRelationshipReference( long relationshipId ) + { + throw new UnsupportedOperationException( "Cannot write a raw relationship reference" ); + } + + @Override + public void writeRelationship( long relationshipId, long startNodeId, long endNodeId, TextValue type, MapValue properties ) + throws IOException + { + packStructHeader( RELATIONSHIP_SIZE, RELATIONSHIP ); + pack( relationshipId ); + pack( startNodeId ); + pack( endNodeId ); + type.writeTo( this ); + properties.writeTo( this ); + } + + @Override + public void beginMap( int size ) throws IOException + { + packMapHeader( size ); + } + + @Override + public void endMap() + { + //do nothing + } + + @Override + public void beginList( int size ) throws IOException + { + packListHeader( size ); + } + + @Override + public void endList() + { + //do nothing + } + + @Override + public void writePath( NodeValue[] nodes, RelationshipValue[] relationships ) throws IOException + { + //A path is serialized in the following form + // Given path: (a {id: 42})-[r1 {id: 10}]->(b {id: 43})<-[r1 {id: 11}]-(c {id: 44}) + //The serialization will look like: + // + // { + // [a, b, c] + // [r1, r2] + // [1, 1, -2, 2] + // } + // The first list contains all nodes where the first node (a) is guaranteed to be the start node of + // the path + // The second list contains all edges of the path + // The third list defines the path order, where every other item specifies the offset into the + // relationship and node list respectively. Since all paths is guaranteed to start with a 0, meaning + // that + // a is the start node in this case, those are excluded. So the first integer in the array refers to the + // position + // in the relationship array (1 indexed where sign denotes direction) and the second one refers to + // the offset + // into the + // node list (zero indexed) and so on. + packStructHeader( PATH_SIZE, PATH ); + + writeNodesForPath( nodes ); + writeRelationshipsForPath( relationships ); + + packListHeader( 2 * relationships.length ); + if ( relationships.length == 0 ) + { + return; + } + + NodeValue node = nodes[0]; + for ( int i = 1; i <= 2 * relationships.length; i++ ) + { + if ( i % 2 == 0 ) + { + node = nodes[i / 2]; + int index = nodeIndexes.getOrDefault( node.id(), NO_SUCH_ID ); + pack( index ); + } + else + { + RelationshipValue r = relationships[i / 2]; + int index = relationshipIndexes.getOrDefault( r.id(), NO_SUCH_ID ); + + if ( node.id() == r.startNode().id() ) + { + pack( index ); + } + else + { + pack( -index ); + } + } + + } + } + + private void writeNodesForPath( NodeValue[] nodes ) throws IOException + { + nodeIndexes.reset( nodes.length ); + for ( NodeValue node : nodes ) + { + nodeIndexes.putIfAbsent( node.id(), nodeIndexes.size() ); + } + + int size = nodeIndexes.size(); + packListHeader( size ); + if ( size > 0 ) + { + NodeValue node = nodes[0]; + for ( long id : nodeIndexes.keys() ) + { + int i = 1; + while ( node.id() != id ) + { + node = nodes[i++]; + } + node.writeTo( this ); + } + } + } + + private void writeRelationshipsForPath( RelationshipValue[] relationships ) throws IOException + { + relationshipIndexes.reset( relationships.length ); + for ( RelationshipValue node : relationships ) + { + // relationship indexes are one-based + relationshipIndexes.putIfAbsent( node.id(), relationshipIndexes.size() + 1 ); + } + + int size = relationshipIndexes.size(); + packListHeader( size ); + if ( size > 0 ) + { + { + RelationshipValue edge = relationships[0]; + for ( long id : relationshipIndexes.keys() ) + { + int i = 1; + while ( edge.id() != id ) + { + edge = relationships[i++]; + } + //Note that we are not doing relationship.writeTo(this) here since the serialization protocol + //requires these to be _unbound relationships_, thus relationships without any start node nor + // end node. + packStructHeader( UNBOUND_RELATIONSHIP_SIZE, UNBOUND_RELATIONSHIP ); + pack( edge.id() ); + edge.type().writeTo( this ); + edge.properties().writeTo( this ); + } + } + } + } + + @Override + public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Point is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDuration( long months, long days, long seconds, int nanos ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Duration is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDate( LocalDate localDate ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Date is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeLocalTime( LocalTime localTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "LocalTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeTime( OffsetTime offsetTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Time is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeLocalDateTime( LocalDateTime localDateTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "LocalDateTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDateTime( ZonedDateTime zonedDateTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "DateTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeNull() throws IOException + { + packNull(); + } + + @Override + public void writeBoolean( boolean value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( byte value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( short value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( int value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( long value ) throws IOException + { + pack( value ); + } + + @Override + public void writeFloatingPoint( float value ) throws IOException + { + pack( value ); + } + + @Override + public void writeFloatingPoint( double value ) throws IOException + { + pack( value ); + } + + @Override + public void writeUTF8( byte[] bytes, int offset, int length ) throws IOException + { + packUTF8(bytes, offset, length); + } + + @Override + public void writeString( String value ) throws IOException + { + pack( value ); + } + + @Override + public void writeString( char value ) throws IOException + { + pack( value ); + } + + @Override + public void beginArray( int size, ArrayType arrayType ) throws IOException + { + switch ( arrayType ) + { + case BYTE: + packBytesHeader( size ); + break; + default: + packListHeader( size ); + } + + } + + @Override + public void endArray() + { + //Do nothing + } + + @Override + public void writeByteArray( byte[] value ) throws IOException + { + pack( value ); + } + } + + protected static class UnpackerV1 extends PackStream.Unpacker implements Neo4jPack.Unpacker + { + protected UnpackerV1( PackInput input ) + { + super( input ); + } + + @Override + public AnyValue unpack() throws IOException + { + PackType valType = peekNextType(); + switch ( valType ) + { + case BYTES: + return byteArray( unpackBytes() ); + case STRING: + return Values.utf8Value( unpackUTF8() ); + case INTEGER: + return Values.longValue( unpackLong() ); + case FLOAT: + return Values.doubleValue( unpackDouble() ); + case BOOLEAN: + return Values.booleanValue( unpackBoolean() ); + case NULL: + // still need to move past the null value + unpackNull(); + return Values.NO_VALUE; + case LIST: + { + return unpackList(); + } + case MAP: + { + return unpackMap(); + } + case STRUCT: + { + long size = unpackStructHeader(); + char signature = unpackStructSignature(); + return unpackStruct( signature, size ); + } + case END_OF_STREAM: + { + unpackEndOfStream(); + return null; + } + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Unknown value type: " + valType ); + } + } + + ListValue unpackList() throws IOException + { + int size = (int) unpackListHeader(); + if ( size == 0 ) + { + return VirtualValues.EMPTY_LIST; + } + else if ( size == UNKNOWN_SIZE ) + { + List list = new ArrayList<>(); + boolean more = true; + while ( more ) + { + PackType keyType = peekNextType(); + switch ( keyType ) + { + case END_OF_STREAM: + unpack(); + more = false; + break; + default: + list.add( unpack() ); + } + } + return VirtualValues.list( list.toArray( new AnyValue[0] ) ); + } + else + { + AnyValue[] values = new AnyValue[size]; + for ( int i = 0; i < size; i++ ) + { + values[i] = unpack(); + } + return VirtualValues.list( values ); + } + } + + protected AnyValue unpackStruct( char signature, long size ) throws IOException + { + StructType structType = StructType.valueOf( signature ); + if ( structType == null ) + { + throw new BoltIOException( Status.Request.InvalidFormat, + String.format( "Struct types of 0x%s are not recognized.", Integer.toHexString( signature ) ) ); + } + + throw new BoltIOException( Status.Statement.TypeError, + String.format( "%s values cannot be unpacked with this version of bolt.", structType.description() ) ); + } + + @Override + public MapValue unpackMap() throws IOException + { + int size = (int) unpackMapHeader(); + if ( size == 0 ) + { + return VirtualValues.EMPTY_MAP; + } + MapValueBuilder map; + if ( size == UNKNOWN_SIZE ) + { + map = new MapValueBuilder( ); + boolean more = true; + while ( more ) + { + PackType keyType = peekNextType(); + String key; + AnyValue val; + switch ( keyType ) + { + case END_OF_STREAM: + unpack(); + more = false; + break; + case STRING: + key = unpackString(); + val = unpack(); + if ( map.add( key, val ) != null ) + { + throw new BoltIOException( Status.Request.Invalid, "Duplicate map key `" + key + "`." ); + } + break; + case NULL: + throw new BoltIOException( Status.Request.Invalid, "Value `null` is not supported as key in maps, must be a non-nullable string." ); + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Bad key type: " + keyType ); + } + } + } + else + { + map = new MapValueBuilder( size ); + for ( int i = 0; i < size; i++ ) + { + PackType keyType = peekNextType(); + String key; + switch ( keyType ) + { + case NULL: + throw new BoltIOException( Status.Request.Invalid, "Value `null` is not supported as key in maps, must be a non-nullable string." ); + case STRING: + key = unpackString(); + break; + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Bad key type: " + keyType ); + } + + AnyValue val = unpack(); + if ( map.add( key, val ) != null ) + { + throw new BoltIOException( Status.Request.Invalid, "Duplicate map key `" + key + "`." ); + } + } + } + return map.build(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArray.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArray.java new file mode 100644 index 0000000000..038a844782 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArray.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.bolt.v1.messaging; + +import java.util.Arrays; + +/** + * This collection class implements a minimal map-like interface + * for an ordered, primitive-based key-value array. The array both + * maintains insertion order and ensures key values are unique. + */ +class PrimitiveLongIntKeyValueArray +{ + public static final int DEFAULT_INITIAL_CAPACITY = 100; + public static final double DEFAULT_GROWTH_FACTOR = 0.2; + + private long[] naturalKeys = new long[DEFAULT_INITIAL_CAPACITY]; + private int[] naturalValues = new int[DEFAULT_INITIAL_CAPACITY]; + private long[] sortedKeys = new long[DEFAULT_INITIAL_CAPACITY]; + private int[] sortedValues = new int[DEFAULT_INITIAL_CAPACITY]; + private double growthFactor; + private int size; + + private PrimitiveLongIntKeyValueArray( int initialCapacity, double growthFactor ) + { + if ( initialCapacity <= 0 ) + { + throw new IllegalArgumentException( "Illegal initial capacity: " + initialCapacity ); + } + if ( growthFactor <= 0 ) + { + throw new IllegalArgumentException( "Illegal growth factor: " + growthFactor ); + } + naturalKeys = new long[DEFAULT_INITIAL_CAPACITY]; + naturalValues = new int[DEFAULT_INITIAL_CAPACITY]; + sortedKeys = new long[DEFAULT_INITIAL_CAPACITY]; + sortedValues = new int[DEFAULT_INITIAL_CAPACITY]; + this.growthFactor = growthFactor; + } + + PrimitiveLongIntKeyValueArray( int initialCapacity ) + { + this( initialCapacity, DEFAULT_GROWTH_FACTOR ); + } + + PrimitiveLongIntKeyValueArray() + { + this( DEFAULT_INITIAL_CAPACITY, DEFAULT_GROWTH_FACTOR ); + } + + /** + * The current capacity. + * + * @return current capacity + */ + public int capacity() + { + return naturalKeys.length; + } + + /** + * The proportion by which this array will automatically grow when full. + * + * @return the growth factor + */ + public double growthFactor() + { + return growthFactor; + } + + /** + * Ensure the array has at least the capacity requested. The + * capacity will only ever increase or stay the same. + * + * @param newCapacity the new capacity requirement + */ + public void ensureCapacity( int newCapacity ) + { + int capacity = naturalKeys.length; + if ( newCapacity > capacity ) + { + long[] newNaturalKeys = new long[newCapacity]; + int[] newNaturalValues = new int[newCapacity]; + long[] newSortedKeys = new long[newCapacity]; + int[] newSortedValues = new int[newCapacity]; + for ( int i = 0; i < capacity; i++ ) + { + newNaturalKeys[i] = naturalKeys[i]; + newNaturalValues[i] = naturalValues[i]; + newSortedKeys[i] = sortedKeys[i]; + newSortedValues[i] = sortedValues[i]; + } + naturalKeys = newNaturalKeys; + naturalValues = newNaturalValues; + sortedKeys = newSortedKeys; + sortedValues = newSortedValues; + } + } + + /** + * The number of items in this array. + * + * @return number of items in the array + */ + public int size() + { + return size; + } + + /** + * Fetch the integer mapped to the given key or defaultValue if + * that key does not exist. + * + * @param key the handle for the required value + * @param defaultValue value to return if the key is not found + * @return the integer value mapped to the key provided + */ + public int getOrDefault( long key, int defaultValue ) + { + int index = Arrays.binarySearch( sortedKeys, 0, size, key ); + if ( index >= 0 ) + { + return sortedValues[index]; + } + else + { + return defaultValue; + } + } + + /** + * Set the value for a given key if that key is not already in use. + * + * @param key the key against which to put the value + * @param value the value to include + * @return true if the value was successfully included, false otherwise + */ + public boolean putIfAbsent( long key, int value ) + { + int capacity = naturalKeys.length; + if ( size == capacity ) + { + ensureCapacity( (int) Math.floor( growthFactor * capacity ) ); + } + + int index = Arrays.binarySearch( sortedKeys, 0, size, key ); + if ( index >= 0 ) + { + return false; + } + else + { + index = -index - 1; + for ( int i = size; i > index; i-- ) + { + int j = i - 1; + sortedKeys[i] = sortedKeys[j]; + sortedValues[i] = sortedValues[j]; + } + naturalKeys[size] = key; + naturalValues[size] = value; + sortedKeys[index] = key; + sortedValues[index] = value; + + size += 1; + return true; + } + } + + /** + * Clear the array and set a new capacity if not already large enough. + * + * @param newCapacity the new capacity requirement + */ + public void reset( int newCapacity ) + { + size = 0; + ensureCapacity( newCapacity ); + } + + /** + * Return an array of all key values, in order of insertion. + * + * @return array of key values + */ + public long[] keys() + { + return Arrays.copyOfRange( naturalKeys, 0, size ); + } + +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/test/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArrayTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/test/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArrayTest.java new file mode 100644 index 0000000000..7dfcfe1a02 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/bolt/src/test/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArrayTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.bolt.v1.messaging; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; + +public class PrimitiveLongIntKeyValueArrayTest +{ + private static final int DEFAULT_VALUE = -1; + + @Test + public void testEnsureCapacity() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.capacity(), equalTo( PrimitiveLongIntKeyValueArray.DEFAULT_INITIAL_CAPACITY + ) ); + + map.ensureCapacity( 10 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 10 ) ); + + map.ensureCapacity( 100 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 100 ) ); + + map.ensureCapacity( 1000 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + + } + + @Test + public void testSize() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.size(), equalTo( 0 ) ); + + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + assertThat( map.size(), equalTo( 3 ) ); + + } + + @Test + public void testGetOrDefault() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + assertThat( map.getOrDefault( 1, DEFAULT_VALUE ), equalTo( 100 ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( DEFAULT_VALUE ) ); + + } + + @Test + public void testPutIfAbsent() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + + assertThat( map.putIfAbsent( 1, 100 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 2, 200 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 3, 300 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 3 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3} ) ); + + assertThat( map.putIfAbsent( 2, 2000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 3, 3000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 4, 4000 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 4 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 4} ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( 4000 ) ); + + } + + @Test + public void testReset() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + map.reset( 1000 ); + assertThat( map.size(), equalTo( 0 ) ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + + } + + @Test + public void testKeys() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 8, 800 ); + map.putIfAbsent( 7, 700 ); + map.putIfAbsent( 6, 600 ); + map.putIfAbsent( 5, 500 ); + + assertThat( map.size(), equalTo( 7 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 8, 7, 6, 5} ) ); + + } + +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java new file mode 100644 index 0000000000..c6f4ba9f6f --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +public class PrimitiveArraysTest +{ + private static final int[] NO_INTS = new int[0]; + private static final int[] ONE_INT = new int[]{1}; + private static final long[] NO_LONGS = new long[0]; + private static final long[] ONE_LONG = new long[]{1}; + + // union() null checks. Actual behaviour is tested in PrimitiveSortedArraySetUnionTest + + @Test + public void union_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.union( null, null ), nullValue() ); + assertThat( PrimitiveArrays.union( null, NO_INTS ), equalTo( NO_INTS ) ); + assertThat( PrimitiveArrays.union( NO_INTS, null ), equalTo( NO_INTS ) ); + assertThat( PrimitiveArrays.union( null, ONE_INT ), equalTo( ONE_INT ) ); + assertThat( PrimitiveArrays.union( ONE_INT, null ), equalTo( ONE_INT ) ); + } + + // intersect() + + @Test + public void intersect_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.intersect( null, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( null, NO_LONGS ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( NO_LONGS, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( null, ONE_LONG ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( ONE_LONG, null ), equalTo( NO_LONGS ) ); + } + + @Test + public void intersect_shouldHandleNonIntersectingArrays() + { + assertThat( PrimitiveArrays.intersect( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + equalTo( NO_LONGS ) ); + + assertThat( PrimitiveArrays.intersect( new long[]{14, 15, 16}, new long[]{1, 2, 3} ), + equalTo( NO_LONGS ) ); + } + + @Test + public void intersect_shouldHandleIntersectingArrays() + { + assertThat( PrimitiveArrays.intersect( new long[]{1, 2, 3}, new long[]{3, 4, 5} ), + isArray( 3 ) ); + + assertThat( PrimitiveArrays.intersect( new long[]{3, 4, 5}, new long[]{1, 2, 3, 4} ), + isArray( 3, 4 ) ); + } + + @Test + public void intersect_shouldHandleComplexIntersectingArraysWithGaps() + { + assertThat( + PrimitiveArrays.intersect( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isArray( 4, 9, 12 ) ); + assertThat( + PrimitiveArrays.intersect( new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19}, new long[]{4, 6, 9, 11, 12, 15} ), + isArray( 4, 9, 12 ) ); + } + + // symmetricDifference() + + @Test + public void symDiff_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.symmetricDifference( null, null ), equalTo( null ) ); + assertThat( PrimitiveArrays.symmetricDifference( null, NO_LONGS ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.symmetricDifference( NO_LONGS, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.symmetricDifference( null, ONE_LONG ), equalTo( ONE_LONG ) ); + assertThat( PrimitiveArrays.symmetricDifference( ONE_LONG, null ), equalTo( ONE_LONG ) ); + } + + @Test + public void symDiff_shouldHandleNonIntersectingArrays() + { + assertThat( PrimitiveArrays.symmetricDifference( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + isArray( 1, 2, 3, 4, 5, 6 ) ); + + assertThat( PrimitiveArrays.symmetricDifference( new long[]{14, 15, 16}, new long[]{1, 2, 3} ), + isArray( 1, 2, 3, 14, 15, 16 ) ); + } + + @Test + public void symDiff_shouldHandleIntersectingArrays() + { + assertThat( PrimitiveArrays.symmetricDifference( new long[]{1, 2, 3}, new long[]{3, 4, 5} ), + isArray( 1, 2, 4, 5 ) ); + + assertThat( PrimitiveArrays.symmetricDifference( new long[]{3, 4, 5}, new long[]{1, 2, 3, 4} ), + isArray( 1, 2, 5 ) ); + } + + @Test + public void symDiff_shouldHandleComplexIntersectingArraysWithGaps() + { + assertThat( + PrimitiveArrays + .symmetricDifference( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isArray( 2, 3, 6, 7, 8, 11, 15, 16, 19 ) ); + assertThat( + PrimitiveArrays + .symmetricDifference( new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19}, new long[]{4, 6, 9, 11, 12, 15} ), + isArray( 2, 3, 6, 7, 8, 11, 15, 16, 19 ) ); + } + + // count unique + + @Test + public void shouldCountUnique() + { + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + isIntPair( 3, 3 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{3, 6} ), + isIntPair( 2, 1 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{3} ), + isIntPair( 2, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3}, new long[]{1, 2, 3} ), + isIntPair( 0, 2 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3}, new long[]{3} ), + isIntPair( 0, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3, 6, 8}, new long[]{} ), + isIntPair( 3, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{}, new long[]{3, 6, 8} ), + isIntPair( 0, 3 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{}, new long[]{} ), + isIntPair( 0, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isIntPair( 3, 6 ) ); + } + + // helpers + + private Matcher isIntPair( int left, int right ) + { + return new BaseMatcher() + { + @Override + public void describeTo( Description description ) + { + description.appendValue( left ); + description.appendValue( right ); + } + + @Override + public boolean matches( Object o ) + { + return o instanceof Long && ((Long) o) == (((long) left << 32) | right); + } + }; + } + + private static Matcher isArray( long... values ) + { + return equalTo( values ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java new file mode 100644 index 0000000000..5fc505345a --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import org.neo4j.memory.LocalMemoryTracker; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class PrimitiveCollectionsAllocationsTest +{ + + @Test + public void trackPrimitiveMemoryAllocations() + { + LocalMemoryTracker memoryTracker = new LocalMemoryTracker(); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( memoryTracker ); + assertTrue( memoryTracker.usedDirectMemory() > 0 ); + + offHeapIntSet.close(); + assertEquals( 0, memoryTracker.usedDirectMemory() ); + } + + @Test + public void trackPrimitiveMemoryOnResize() + { + LocalMemoryTracker memoryTracker = new LocalMemoryTracker(); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( memoryTracker ); + long originalSetMemory = memoryTracker.usedDirectMemory(); + + for ( int i = 0; i < Primitive.DEFAULT_OFFHEAP_CAPACITY + 1; i++ ) + { + offHeapIntSet.add( i ); + } + + assertTrue( memoryTracker.usedDirectMemory() > originalSetMemory ); + + offHeapIntSet.close(); + assertEquals( 0, memoryTracker.usedDirectMemory() ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java new file mode 100644 index 0000000000..f0befefbda --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.memory.GlobalMemoryTracker; + +import static java.util.Arrays.asList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PrimitiveIntCollectionsTest +{ + @Test + public void arrayOfItemsAsIterator() + { + // GIVEN + int[] items = new int[]{2, 5, 234}; + + // WHEN + PrimitiveIntIterator iterator = PrimitiveIntCollections.iterator( items ); + + // THEN + assertItems( iterator, items ); + } + + @Test + public void convertCollectionToLongArray() + { + PrimitiveIntSet heapSet = PrimitiveIntCollections.asSet( new int[]{1, 2, 3} ); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( GlobalMemoryTracker.INSTANCE ); + offHeapIntSet.add( 7 ); + offHeapIntSet.add( 8 ); + assertArrayEquals( new long[]{1, 2, 3}, PrimitiveIntCollections.asLongArray( heapSet ) ); + assertArrayEquals( new long[]{7, 8}, PrimitiveIntCollections.asLongArray( offHeapIntSet ) ); + } + + @Test + public void concatenateTwoIterators() + { + // GIVEN + PrimitiveIntIterator firstItems = PrimitiveIntCollections.iterator( 10, 3, 203, 32 ); + PrimitiveIntIterator otherItems = PrimitiveIntCollections.iterator( 1, 2, 5 ); + + // WHEN + PrimitiveIntIterator iterator = PrimitiveIntCollections.concat( asList( firstItems, otherItems ).iterator() ); + + // THEN + assertItems( iterator, 10, 3, 203, 32, 1, 2, 5 ); + } + + @Test + public void filter() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveIntIterator filtered = PrimitiveIntCollections.filter( items, item -> item != 2 ); + + // THEN + assertItems( filtered, 1, 3 ); + } + + @Test + public void deduplicate() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 1, 2, 3, 2 ); + + // WHEN + PrimitiveIntIterator deduped = PrimitiveIntCollections.deduplicate( items ); + + // THEN + assertItems( deduped, 1, 2, 3 ); + } + + private static final class CountingPrimitiveIntIteratorResource implements PrimitiveIntIterator, AutoCloseable + { + private final PrimitiveIntIterator delegate; + private final AtomicInteger closeCounter; + + private CountingPrimitiveIntIteratorResource( PrimitiveIntIterator delegate, AtomicInteger closeCounter ) + { + this.delegate = delegate; + this.closeCounter = closeCounter; + } + + @Override + public void close() + { + closeCounter.incrementAndGet(); + } + + @Override + public boolean hasNext() + { + return delegate.hasNext(); + } + + @Override + public int next() + { + return delegate.next(); + } + } + + @Test + public void iteratorAsSet() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveIntSet set = PrimitiveIntCollections.asSet( items ); + + // THEN + assertTrue( set.contains( 1 ) ); + assertTrue( set.contains( 2 ) ); + assertTrue( set.contains( 3 ) ); + assertFalse( set.contains( 4 ) ); + try + { + PrimitiveIntCollections.asSet( PrimitiveIntCollections.iterator( 1, 2, 1 ) ); + fail( "Should fail on duplicates" ); + } + catch ( IllegalStateException e ) + { // good + } + } + + @Test + public void shouldNotContinueToCallNextOnHasNextFalse() + { + // GIVEN + AtomicInteger count = new AtomicInteger( 2 ); + PrimitiveIntIterator iterator = new PrimitiveIntCollections.PrimitiveIntBaseIterator() + { + @Override + protected boolean fetchNext() + { + return count.decrementAndGet() >= 0 && next( count.get() ); + } + }; + + // WHEN/THEN + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 1L, iterator.next() ); + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 0L, iterator.next() ); + assertFalse( iterator.hasNext() ); + assertFalse( iterator.hasNext() ); + assertEquals( -1L, count.get() ); + } + + @Test + public void shouldDeduplicate() + { + // GIVEN + int[] array = new int[]{1, 6, 2, 5, 6, 1, 6}; + + // WHEN + int[] deduped = PrimitiveIntCollections.deduplicate( array ); + + // THEN + assertArrayEquals( new int[]{1, 6, 2, 5}, deduped ); + } + + @Test + public void copyMap() + { + PrimitiveIntObjectMap originalMap = Primitive.intObjectMap(); + originalMap.put( 1, "a" ); + originalMap.put( 2, "b" ); + originalMap.put( 3, "c" ); + PrimitiveIntObjectMap copyMap = PrimitiveIntCollections.copy( originalMap ); + assertNotSame( originalMap, copyMap ); + assertEquals( 3, copyMap.size() ); + assertEquals( "a", copyMap.get( 1 ) ); + assertEquals( "b", copyMap.get( 2 ) ); + assertEquals( "c", copyMap.get( 3 ) ); + } + + private void assertNoMoreItems( PrimitiveIntIterator iterator ) + { + assertFalse( iterator + " should have no more items", iterator.hasNext() ); + try + { + iterator.next(); + fail( "Invoking next() on " + iterator + + " which has no items left should have thrown NoSuchElementException" ); + } + catch ( NoSuchElementException e ) + { // Good + } + } + + private void assertNextEquals( long expected, PrimitiveIntIterator iterator ) + { + assertTrue( iterator + " should have had more items", iterator.hasNext() ); + assertEquals( expected, iterator.next() ); + } + + private void assertItems( PrimitiveIntIterator iterator, int... expectedItems ) + { + for ( long expectedItem: expectedItems ) + { + assertNextEquals( expectedItem, iterator ); + } + assertNoMoreItems( iterator ); + } + + private int[] reverse( int[] items ) + { + int[] result = new int[items.length]; + for ( int i = 0; i < items.length; i++ ) + { + result[i] = items[items.length - i - 1]; + } + return result; + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java new file mode 100644 index 0000000000..ff8e8efc6e --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PrimitiveIntStackTest +{ + @Test + public void shouldPushAndPollSomeEntities() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack( 6 ); + + // WHEN/THEN + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + + stack.push( 123 ); + assertFalse( stack.isEmpty() ); + + stack.push( 456 ); + assertFalse( stack.isEmpty() ); + assertEquals( 456, stack.poll() ); + + assertFalse( stack.isEmpty() ); + assertEquals( 123, stack.poll() ); + + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + public void shouldGrowArray() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack( 5 ); + + // WHEN + for ( int i = 0; i <= 7; i++ ) + { + stack.push( i ); + } + + // THEN + for ( int i = 7; i >= 0; i-- ) + { + assertFalse( stack.isEmpty() ); + assertEquals( i, stack.poll() ); + } + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + public void shouldIterate() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack(); + + // WHEN + for ( int i = 0; i < 7; i++ ) + { + stack.push( i ); + } + + // THEN + PrimitiveIntIterator iterator = stack.iterator(); + int i = 0; + while ( iterator.hasNext() ) + { + assertEquals( i++, iterator.next() ); + } + assertEquals( 7, i ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java new file mode 100644 index 0000000000..2b12f35f7e --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PrimitiveLongArrayQueueTest +{ + + @Test + public void newQueueIsEmpty() + { + assertTrue( createQueue().isEmpty() ); + } + + @Test + public void growQueueOnElementOffer() + { + PrimitiveLongArrayQueue longArrayQueue = createQueue(); + for ( int i = 1; i < 1000; i++ ) + { + longArrayQueue.enqueue( i ); + assertEquals( i, longArrayQueue.size() ); + } + } + + @Test + public void addRemoveElementKeepQueueEmpty() + { + PrimitiveLongArrayQueue longArrayQueue = createQueue(); + for ( int i = 0; i < 1000; i++ ) + { + longArrayQueue.enqueue( i ); + assertEquals( i, longArrayQueue.dequeue() ); + assertTrue( longArrayQueue.isEmpty() ); + } + } + + @Test + public void offerLessThenQueueCapacityElements() + { + PrimitiveLongArrayQueue arrayQueue = createQueue(); + for ( int i = 1; i < 16; i++ ) + { + arrayQueue.enqueue( i ); + assertEquals( i, arrayQueue.size() ); + } + } + + @Test( expected = IllegalStateException.class ) + public void failToRemoveElementFromNewEmptyQueue() + { + createQueue().dequeue(); + } + + @Test + public void offerMoreThenQueueCapacityElements() + { + PrimitiveLongArrayQueue arrayQueue = createQueue(); + for ( int i = 1; i < 1234; i++ ) + { + arrayQueue.enqueue( i ); + } + int currentValue = 1; + while ( !arrayQueue.isEmpty() ) + { + assertEquals( currentValue++, arrayQueue.dequeue() ); + } + } + + @Test + public void emptyQueueAfterClear() + { + PrimitiveLongArrayQueue queue = createQueue(); + queue.enqueue( 2 ); + queue.enqueue( 3 ); + assertFalse( queue.isEmpty() ); + assertEquals( 2, queue.size() ); + + queue.clear(); + + assertTrue( queue.isEmpty() ); + } + + @Test + public void tailBeforeHeadCorrectSize() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 24; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 14, queue.size() ); + } + + @Test + public void tailBeforeHeadCorrectResize() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 34; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 24, queue.size() ); + for ( int j = 10; j < 34; j++ ) + { + assertEquals( j, queue.dequeue() ); + } + } + + @Test + public void tailBeforeHeadCorrectIteration() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 24; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 14, queue.size() ); + PrimitiveLongIterator iterator = queue.iterator(); + for ( int j = 10; j < 24; j++ ) + { + assertTrue( iterator.hasNext() ); + assertEquals( j, iterator.next() ); + } + assertFalse( iterator.hasNext() ); + } + + @Test( expected = NoSuchElementException.class ) + public void failToGetNextOnEmptyQueueIterator() + { + createQueue().iterator().next(); + } + + @Test + public void addAllElementsFromOtherQueue() + { + PrimitiveLongArrayQueue queue = createQueue(); + queue.enqueue( 1 ); + queue.enqueue( 2 ); + PrimitiveLongArrayQueue otherQueue = createQueue(); + otherQueue.enqueue( 3 ); + otherQueue.enqueue( 4 ); + queue.addAll( otherQueue ); + + assertTrue( otherQueue.isEmpty() ); + assertEquals( 0, otherQueue.size() ); + assertEquals( 4, queue.size() ); + for ( int value = 1; value <= 4; value++ ) + { + assertEquals( value, queue.dequeue() ); + } + assertTrue( queue.isEmpty() ); + } + + @Test( expected = AssertionError.class ) + public void doNotAllowCreationOfQueueWithRandomCapacity() + { + new PrimitiveLongArrayQueue( 7 ); + } + + private PrimitiveLongArrayQueue createQueue() + { + return new PrimitiveLongArrayQueue(); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java new file mode 100644 index 0000000000..aa850c8176 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.neo4j.collection.primitive.PrimitiveLongCollections.PrimitiveLongBaseIterator; + +import static java.util.Arrays.asList; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PrimitiveLongCollectionsTest +{ + @Test + public void arrayOfItemsAsIterator() + { + // GIVEN + long[] items = new long[]{2, 5, 234}; + + // WHEN + PrimitiveLongIterator iterator = PrimitiveLongCollections.iterator( items ); + + // THEN + assertItems( iterator, items ); + } + + @Test + public void filter() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveLongIterator filtered = PrimitiveLongCollections.filter( items, item -> item != 2 ); + + // THEN + assertItems( filtered, 1, 3 ); + } + + private static final class CountingPrimitiveLongIteratorResource implements PrimitiveLongIterator, AutoCloseable + { + private final PrimitiveLongIterator delegate; + private final AtomicInteger closeCounter; + + private CountingPrimitiveLongIteratorResource( PrimitiveLongIterator delegate, AtomicInteger closeCounter ) + { + this.delegate = delegate; + this.closeCounter = closeCounter; + } + + @Override + public void close() + { + closeCounter.incrementAndGet(); + } + + @Override + public boolean hasNext() + { + return delegate.hasNext(); + } + + @Override + public long next() + { + return delegate.next(); + } + } + + @Test + public void singleWithDefaultMustAutoCloseIterator() + { + AtomicInteger counter = new AtomicInteger(); + CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource( + PrimitiveLongCollections.iterator( 13 ), counter ); + assertEquals( PrimitiveLongCollections.single( itr, 2 ), 13 ); + assertEquals( 1, counter.get() ); + } + + @Test + public void singleWithDefaultMustAutoCloseEmptyIterator() + { + AtomicInteger counter = new AtomicInteger(); + CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource( + PrimitiveLongCollections.emptyIterator(), counter ); + assertEquals( PrimitiveLongCollections.single( itr, 2 ), 2 ); + assertEquals( 1, counter.get() ); + } + + @Test + public void indexOf() + { + // GIVEN + PrimitiveLongIterable items = () -> PrimitiveLongCollections.iterator( 10, 20, 30 ); + + // THEN + assertEquals( -1, PrimitiveLongCollections.indexOf( items.iterator(), 55 ) ); + assertEquals( 0, PrimitiveLongCollections.indexOf( items.iterator(), 10 ) ); + assertEquals( 1, PrimitiveLongCollections.indexOf( items.iterator(), 20 ) ); + assertEquals( 2, PrimitiveLongCollections.indexOf( items.iterator(), 30 ) ); + } + + @Test + public void iteratorAsSet() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveLongSet set = PrimitiveLongCollections.asSet( items ); + + // THEN + assertTrue( set.contains( 1 ) ); + assertTrue( set.contains( 2 ) ); + assertTrue( set.contains( 3 ) ); + assertFalse( set.contains( 4 ) ); + } + + @Test + public void count() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + int count = PrimitiveLongCollections.count( items ); + + // THEN + assertEquals( 3, count ); + } + + @Test + public void asArray() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + long[] array = PrimitiveLongCollections.asArray( items ); + + // THEN + assertTrue( Arrays.equals( new long[]{1, 2, 3}, array ) ); + } + + @Test + public void shouldDeduplicate() + { + // GIVEN + long[] array = new long[]{1L, 1L, 2L, 5L, 6L, 6L}; + + // WHEN + long[] deduped = PrimitiveLongCollections.deduplicate( array ); + + // THEN + assertArrayEquals( new long[]{1L, 2L, 5L, 6L}, deduped ); + } + + @Test + public void shouldNotContinueToCallNextOnHasNextFalse() + { + // GIVEN + AtomicLong count = new AtomicLong( 2 ); + PrimitiveLongIterator iterator = new PrimitiveLongBaseIterator() + { + @Override + protected boolean fetchNext() + { + return count.decrementAndGet() >= 0 && next( count.get() ); + } + }; + + // WHEN/THEN + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 1L, iterator.next() ); + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 0L, iterator.next() ); + assertFalse( iterator.hasNext() ); + assertFalse( iterator.hasNext() ); + assertEquals( -1L, count.get() ); + } + + @Test + public void copyPrimitiveSet() + { + PrimitiveLongSet longSet = PrimitiveLongCollections.setOf( 1L, 3L, 5L ); + PrimitiveLongSet copySet = PrimitiveLongCollections.asSet( longSet ); + assertNotSame( copySet, longSet ); + + assertTrue( copySet.contains( 1L ) ); + assertTrue( copySet.contains( 3L ) ); + assertTrue( copySet.contains( 5L ) ); + assertEquals( 3, copySet.size() ); + } + + @Test + public void convertJavaCollectionToSetOfPrimitives() + { + List longs = asList( 1L, 4L, 7L ); + PrimitiveLongSet longSet = PrimitiveLongCollections.asSet( longs ); + assertTrue( longSet.contains( 1L ) ); + assertTrue( longSet.contains( 4L ) ); + assertTrue( longSet.contains( 7L ) ); + assertEquals( 3, longSet.size() ); + } + + @Test + public void convertPrimitiveSetToJavaSet() + { + PrimitiveLongSet longSet = PrimitiveLongCollections.setOf( 1L, 3L, 5L ); + Set longs = PrimitiveLongCollections.toSet( longSet ); + assertThat( longs, containsInAnyOrder( 1L, 3L, 5L ) ); + } + + @Test + public void copyMap() + { + PrimitiveLongObjectMap originalMap = Primitive.longObjectMap(); + originalMap.put( 1L, "a" ); + originalMap.put( 2L, "b" ); + originalMap.put( 3L, "c" ); + PrimitiveLongObjectMap copyMap = PrimitiveLongCollections.copy( originalMap ); + assertNotSame( originalMap, copyMap ); + assertEquals( 3, copyMap.size() ); + assertEquals( "a", copyMap.get( 1L ) ); + assertEquals( "b", copyMap.get( 2L ) ); + assertEquals( "c", copyMap.get( 3L ) ); + } + + private void assertNoMoreItems( PrimitiveLongIterator iterator ) + { + assertFalse( iterator + " should have no more items", iterator.hasNext() ); + try + { + iterator.next(); + fail( "Invoking next() on " + iterator + + " which has no items left should have thrown NoSuchElementException" ); + } + catch ( NoSuchElementException e ) + { // Good + } + } + + private void assertNextEquals( long expected, PrimitiveLongIterator iterator ) + { + assertTrue( iterator + " should have had more items", iterator.hasNext() ); + assertEquals( expected, iterator.next() ); + } + + private void assertItems( PrimitiveLongIterator iterator, long... expectedItems ) + { + for ( long expectedItem: expectedItems ) + { + assertNextEquals( expectedItem, iterator ); + } + assertNoMoreItems( iterator ); + } + + private long[] reverse( long[] items ) + { + long[] result = new long[items.length]; + for ( int i = 0; i < items.length; i++ ) + { + result[i] = items[items.length - i - 1]; + } + return result; + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java new file mode 100644 index 0000000000..69d7bd6eee --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; + +public class PrimitiveLongIntKeyValueArrayTest +{ + private static final int DEFAULT_VALUE = -1; + + @Test + public void testEnsureCapacity() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.capacity(), equalTo( PrimitiveLongIntKeyValueArray.DEFAULT_INITIAL_CAPACITY + ) ); + + map.ensureCapacity( 10 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 10 ) ); + + map.ensureCapacity( 100 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 100 ) ); + + map.ensureCapacity( 1000 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + } + + @Test + public void testSize() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.size(), equalTo( 0 ) ); + + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + assertThat( map.size(), equalTo( 3 ) ); + } + + @Test + public void testGetOrDefault() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + assertThat( map.getOrDefault( 1, DEFAULT_VALUE ), equalTo( 100 ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( DEFAULT_VALUE ) ); + } + + @Test + public void testPutIfAbsent() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + + assertThat( map.putIfAbsent( 1, 100 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 2, 200 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 3, 300 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 3 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3} ) ); + + assertThat( map.putIfAbsent( 2, 2000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 3, 3000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 4, 4000 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 4 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 4} ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( 4000 ) ); + } + + @Test + public void testReset() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + map.reset( 1000 ); + assertThat( map.size(), equalTo( 0 ) ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + } + + @Test + public void testKeys() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 8, 800 ); + map.putIfAbsent( 7, 700 ); + map.putIfAbsent( 6, 600 ); + map.putIfAbsent( 5, 500 ); + + assertThat( map.size(), equalTo( 7 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 8, 7, 6, 5} ) ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java new file mode 100644 index 0000000000..ed585f6f15 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PrimitiveLongListTest +{ + + @Test + public void newListIsEmpty() + { + assertTrue( new PrimitiveLongList().isEmpty() ); + assertTrue( new PrimitiveLongList( 12 ).isEmpty() ); + } + + @Test + public void newListHasZeroSize() + { + assertEquals( 0, new PrimitiveLongList().size() ); + assertEquals( 0, new PrimitiveLongList( 12 ).size() ); + } + + @Test + public void addingElementsChangeSize() + { + PrimitiveLongList longList = new PrimitiveLongList(); + longList.add( 1L ); + + assertFalse( longList.isEmpty() ); + assertEquals( 1, longList.size() ); + + longList.add( 2L ); + assertFalse( longList.isEmpty() ); + assertEquals( 2, longList.size() ); + + longList.add( 3L ); + + assertFalse( longList.isEmpty() ); + assertEquals( 3, longList.size() ); + } + + @Test + public void accessAddedElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + for ( long i = 1; i < 6L; i++ ) + { + longList.add( i ); + } + + assertEquals( 5L, longList.get( 4 ) ); + assertEquals( 1L, longList.get( 0 ) ); + } + + @Test( expected = IndexOutOfBoundsException.class ) + public void throwExceptionOnAccessingNonExistentElement() + { + PrimitiveLongList longList = new PrimitiveLongList(); + longList.get( 0 ); + } + + @Test + public void iterateOverListElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + for ( long i = 0; i < 10L; i++ ) + { + longList.add( i ); + } + + int iteratorElements = 0; + long value = 0; + PrimitiveLongIterator iterator = longList.iterator(); + while ( iterator.hasNext() ) + { + iteratorElements++; + assertEquals( value++, iterator.next() ); + } + + assertEquals( iteratorElements, longList.size() ); + } + + @Test + public void clearResetListSize() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 10; + for ( long i = 0; i < 10L; i++ ) + { + longList.add( i ); + } + assertEquals( size, longList.size() ); + + longList.clear(); + + assertEquals( 0, longList.size() ); + assertTrue( longList.isEmpty() ); + } + + @Test + public void transformListToArray() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 24L; + for ( long i = 0; i < size; i++ ) + { + longList.add( i ); + } + + long[] longs = longList.toArray(); + assertEquals( size, longs.length ); + for ( int i = 0; i < longs.length; i++ ) + { + assertEquals( i, longs[i] ); + } + } + + @Test + public void holdLotsOfElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 13077L; + for ( long i = 0; i < size; i++ ) + { + longList.add( i ); + } + + assertEquals( size, longList.size() ); + for ( int i = 0; i < size; i++ ) + { + assertEquals( i, longList.get( i ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java new file mode 100644 index 0000000000..d1a28004b5 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PrimitiveLongPeekingIteratorTest +{ + @Test + public void shouldDetectMultipleValues() + { + // GIVEN + long[] values = new long[]{1, 2, 3}; + PrimitiveLongIterator actual = PrimitiveLongCollections.iterator( values ); + PrimitiveLongPeekingIterator peekingIterator = new PrimitiveLongPeekingIterator( actual ); + + // THEN + assertTrue( peekingIterator.hasMultipleValues() ); + for ( long value: values ) + { + assertEquals( value, peekingIterator.next() ); + } + assertFalse( peekingIterator.hasNext() ); + assertTrue( peekingIterator.hasMultipleValues() ); + } + + @Test + public void shouldDetectSingleValue() + { + // GIVEN + long[] values = new long[]{1}; + PrimitiveLongIterator actual = PrimitiveLongCollections.iterator( values ); + PrimitiveLongPeekingIterator peekingIterator = new PrimitiveLongPeekingIterator( actual ); + // THEN + assertFalse( peekingIterator.hasMultipleValues() ); + for ( long value: values ) + { + assertEquals( value, peekingIterator.next() ); + } + assertFalse( peekingIterator.hasNext() ); + assertFalse( peekingIterator.hasMultipleValues() ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java new file mode 100644 index 0000000000..0302413dcf --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.LongPredicate; + +import org.neo4j.graphdb.Resource; + +import static org.junit.Assert.assertEquals; + +public class PrimitiveLongResourceCollectionsTest +{ + private static final LongPredicate EVEN = value -> value % 2 == 0; + + // ITERATOR + + @Test + public void simpleIterator() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator iterator = PrimitiveLongResourceCollections.iterator( resource, 1, 2, 3, 4 ); + + // Then + assertContent( iterator, 1, 2, 3, 4 ); + + // When + iterator.close(); + + // Then + assertEquals( "exactly one call to close", 1, resource.closeCount() ); + } + + // FILTER + + @Test + public void filterItems() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator iterator = PrimitiveLongResourceCollections.iterator( resource, 1, 2, 3, 4 ); + + // When + PrimitiveLongResourceIterator filtered = PrimitiveLongResourceCollections.filter( iterator, EVEN ); + + // Then + assertContent( filtered, 2, 4 ); + + // When + filtered.close(); + + // Then + assertEquals( "exactly one call to close", 1, resource.closeCount() ); + } + + // CONCAT + + @Test + public void concatIterators() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator first = PrimitiveLongResourceCollections.iterator( resource, 1, 2 ); + PrimitiveLongResourceIterator second = PrimitiveLongResourceCollections.iterator( resource, 3, 4 ); + + // When + PrimitiveLongResourceIterator concat = PrimitiveLongResourceCollections.concat( first, second ); + + // Then + assertContent( concat, 1, 2, 3, 4 ); + + // When + concat.close(); + + // Then + assertEquals( "all concatenated iterators are closed", 2, resource.closeCount() ); + } + + private void assertContent( PrimitiveLongResourceIterator iterator, long... expected ) + { + int i = 0; + while ( iterator.hasNext() ) + { + assertEquals( "has expected value", expected[i++], iterator.next() ); + } + assertEquals( "has all expected values", expected.length, i ); + } + + private static class CountingResource implements Resource + { + private AtomicInteger closed = new AtomicInteger(); + + @Override + public void close() + { + closed.incrementAndGet(); + } + + int closeCount() + { + return closed.get(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java new file mode 100644 index 0000000000..8499af47f3 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PrimitiveLongStackTest +{ + @Test + public void shouldPushAndPollSomeEntities() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 6 ); + + // WHEN/THEN + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + + stack.push( 123 ); + assertFalse( stack.isEmpty() ); + + stack.push( 456 ); + assertFalse( stack.isEmpty() ); + assertEquals( 456, stack.poll() ); + + assertFalse( stack.isEmpty() ); + assertEquals( 123, stack.poll() ); + + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + public void shouldGrowArray() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 5 ); + + // WHEN + for ( int i = 0; i <= 7; i++ ) + { + stack.push( i ); + } + + // THEN + for ( int i = 7; i >= 0; i-- ) + { + assertFalse( stack.isEmpty() ); + assertEquals( i, stack.poll() ); + } + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + public void shouldStoreLongs() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 5 ); + long value1 = 10L * Integer.MAX_VALUE; + long value2 = 101L * Integer.MAX_VALUE; + stack.push( value1 ); + stack.push( value2 ); + + // WHEN + long firstPolledValue = stack.poll(); + long secondPolledValue = stack.poll(); + + // THEN + assertEquals( value2, firstPolledValue ); + assertEquals( value1, secondPolledValue ); + assertTrue( stack.isEmpty() ); + } + + @Test + public void shouldIterate() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack(); + + // WHEN + for ( int i = 0; i < 7; i++ ) + { + stack.push( i ); + } + + // THEN + PrimitiveLongIterator iterator = stack.iterator(); + long i = 0; + while ( iterator.hasNext() ) + { + assertEquals( i++, iterator.next() ); + } + assertEquals( 7L, i ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java new file mode 100644 index 0000000000..0153bcb2ce --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +@SuppressWarnings( "unchecked" ) +public class ClosingTablesTest +{ + @Test + public void intCollectionsMustDelegateCloseToTable() + { + // Given + Table table = mock( Table.class ); + AbstractIntHopScotchCollection coll = new AbstractIntHopScotchCollection( table ) + { + @Override + public boolean equals( Object other ) + { + return false; + } + + @Override + public int hashCode() + { + return 0; + } + }; + + // When + coll.close(); + + // Then + verify( table ).close(); + } + + @Test + public void longCollectionsMustDelegateCloseToTable() + { + // Given + Table table = mock( Table.class ); + AbstractLongHopScotchCollection coll = + new AbstractLongHopScotchCollection( table ) + { + @Override + public boolean equals( Object other ) + { + return false; + } + + @Override + public int hashCode() + { + return 0; + } + }; + + // When + coll.close(); + + // Then + verify( table ).close(); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/DebugMonitor.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/DebugMonitor.java new file mode 100644 index 0000000000..f0cb2b8a29 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/DebugMonitor.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import java.util.HashSet; +import java.util.Set; + +import org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.Monitor; + +import static java.lang.String.format; + +class DebugMonitor extends Monitor.Adapter +{ + // This is not the place to use primitive collections, since we're debugging issues in them + private final Set indexes = new HashSet<>(); + private final Set values = new HashSet<>(); + + DebugMonitor( int[] relevantIndexes, long[] relevantValues ) + { + for ( int index: relevantIndexes ) + { + indexes.add( index ); + } + for ( long value: relevantValues ) + { + values.add( value ); + } + } + + private String hopBitsAsString( long hopBits ) + { + StringBuilder builder = new StringBuilder( "[" ); + while ( hopBits > 0 ) + { + int indexDistance = Long.numberOfTrailingZeros( hopBits ); + hopBits &= hopBits - 1; + builder.append( builder.length() > 1 ? "," : "" ).append( indexDistance + 1 ); + } + return builder.append( "]" ).toString(); + } + + private String hopBitsAsString( long oldHopBits, long newHopBits ) + { + return hopBitsAsString( oldHopBits ) + " > " + hopBitsAsString( newHopBits ); + } + + @Override + public boolean placedAtFreedIndex( int intendedIndex, long newHopBits, long key, int actualIndex ) + { + if ( indexes.contains( intendedIndex ) || indexes.contains( actualIndex ) || values.contains( key ) ) + { + System.out.println( format( "[%d] --> |%d| <-- %d %s", intendedIndex, actualIndex, key, + hopBitsAsString( newHopBits ) ) ); + } + return true; + } + + @Override + public boolean placedAtFreeAndIntendedIndex( long key, int index ) + { + if ( indexes.contains( index ) || values.contains( key ) ) + { + System.out.println( format( "[%d] <-- %d", index, key ) ); + } + return true; + } + + @Override + public boolean pushedToFreeIndex( int intendedIndex, long oldNeighborHopBits, long newNeighborHopBits, + int neighborIndex, long key, int fromIndex, int toIndex ) + { + if ( indexes.contains( intendedIndex ) || indexes.contains( neighborIndex ) || + indexes.contains( fromIndex ) || indexes.contains( toIndex ) || values.contains( key ) ) + { + System.out.println( format( "[%d] --- [%d] -->> [%d] --> %d --> [%d] %s", + intendedIndex, neighborIndex, fromIndex, key, toIndex, + hopBitsAsString( oldNeighborHopBits, newNeighborHopBits ) ) ); + } + return true; + } + + @Override + public boolean pulledToFreeIndex( int intendedIndex, long newHopBits, long key, int fromIndex, int toIndex ) + { + if ( indexes.contains( intendedIndex ) || + indexes.contains( fromIndex ) || indexes.contains( toIndex ) || values.contains( key ) ) + { + System.out.println( format( "[%d] --- [%d] <<-- %d <-- [%d] %s", + intendedIndex, toIndex, key, fromIndex, + hopBitsAsString( newHopBits ) ) ); + } + return true; + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java new file mode 100644 index 0000000000..32ceaf783b --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.neo4j.collection.primitive.PrimitiveLongIterator; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.Monitor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.neo4j.collection.primitive.Primitive.VALUE_MARKER; +import static org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.DEFAULT_H; + +public class HopScotchHashingAlgorithmTest +{ + @Test + public void shouldSupportIteratingThroughResize() + { + // GIVEN + int threshold = figureOutGrowthThreshold(); + TableGrowthAwareMonitor monitor = new TableGrowthAwareMonitor(); + PrimitiveLongSet set = new PrimitiveLongHashSet( + new LongKeyTable<>( DEFAULT_H, VALUE_MARKER ), VALUE_MARKER, monitor ); + Set added = new HashSet<>(); + for ( long i = 0; i < threshold - 1; i++ ) + { + long value = i * 3; + set.add( value ); + added.add( value ); + } + + // WHEN + PrimitiveLongIterator iterator = set.iterator(); + Set iterated = new HashSet<>(); + for ( int i = 0; i < threshold / 2; i++ ) + { + iterated.add( iterator.next() ); + } + assertFalse( monitor.checkAndReset() ); + // will push it over the edge, to grow the table + set.add( (threshold - 1) * 3 ); + assertTrue( monitor.checkAndReset() ); + while ( iterator.hasNext() ) + { + iterated.add( iterator.next() ); + } + + // THEN + assertEquals( added, iterated ); + } + + private static class TableGrowthAwareMonitor extends Monitor.Adapter + { + private boolean grew; + + @Override + public boolean tableGrew( int fromCapacity, int toCapacity, int currentSize ) + { + return grew = true; + } + + public boolean checkAndReset() + { + try + { + return grew; + } + finally + { + grew = false; + } + } + } + + private int figureOutGrowthThreshold() + { + final AtomicBoolean grew = new AtomicBoolean(); + Monitor monitor = new Monitor.Adapter() + { + @Override + public boolean tableGrew( int fromCapacity, int toCapacity, int currentSize ) + { + grew.set( true ); + return true; + } + }; + try ( PrimitiveLongSet set = new PrimitiveLongHashSet( + new LongKeyTable<>( DEFAULT_H, VALUE_MARKER ), VALUE_MARKER, monitor ) ) + { + int i = 0; + for ( i = 0; !grew.get(); i++ ) + { + set.add( i * 3 ); + } + return i; + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java new file mode 100644 index 0000000000..e20a96ae4d --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicLong; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongSet; + +public class JumpingSequencePutTest +{ + @Test + public void shouldHandlePathologicalSequenceCase() + { + // Given + PrimitiveLongSet set = Primitive.longSet(); + Sequence seqGen = new Sequence(); + + // When + for ( int i = 0; i < 10000; i++ ) + { + set.add( seqGen.next() ); + } + + // Then it should not have run out of RAM + } + + /** + * To be frank, I don't understand the intricacies of how this works, but + * this is a cut-out version of the sequence generator that triggered the original bug. + * The gist is that it generates sequences of ids that "jump" to a much higher number + * every one hundred ids or so. + */ + private class Sequence + { + private static final int sizePerJump = 100; + private final AtomicLong nextId = new AtomicLong(); + private int leftToNextJump = sizePerJump / 2; + private long highBits; + + public long next() + { + long result = tryNextId(); + if ( --leftToNextJump == 0 ) + { + leftToNextJump = sizePerJump; + nextId.set( (0xFFFFFFFFL | (highBits++ << 32)) - sizePerJump / 2 + 1 ); + } + return result; + } + + private long tryNextId() + { + long result = nextId.getAndIncrement(); + if ( result == 0xFFFFFFFFL ) // 4294967295L + { + result = nextId.getAndIncrement(); + leftToNextJump--; + } + return result; + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java new file mode 100644 index 0000000000..847faa2b77 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveCollection; +import org.neo4j.collection.primitive.PrimitiveIntLongMap; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; +import org.neo4j.collection.primitive.PrimitiveIntSet; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.collection.primitive.PrimitiveLongLongMap; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.function.Factory; +import org.neo4j.memory.GlobalMemoryTracker; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assume.assumeTrue; + +@SuppressWarnings( "unchecked" ) +@RunWith( Theories.class ) +public class PrimitiveCollectionEqualityTest +{ + private interface Value + { + void add( T coll ); + + /** + * @return 'true' if what was removed was exactly the value that was put in. + */ + boolean remove( T coll ); + } + + private abstract static class ValueProducer + { + private final Class applicableType; + + ValueProducer( Class applicableType ) + { + this.applicableType = applicableType; + } + + public boolean isApplicable( Factory factory ) + { + try ( PrimitiveCollection coll = factory.newInstance() ) + { + return applicableType.isInstance( coll ); + } + } + + public abstract Value randomValue(); + } + + // ==== Test Value Producers ==== + + @DataPoint + public static ValueProducer intV = new ValueProducer( PrimitiveIntSet.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + return new Value() + { + @Override + public void add( PrimitiveIntSet coll ) + { + coll.add( x ); + } + + @Override + public boolean remove( PrimitiveIntSet coll ) + { + return coll.remove( x ); + } + }; + } + }; + + @DataPoint + public static ValueProducer longV = + new ValueProducer( PrimitiveLongSet.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveLongSet coll ) + { + coll.add( x ); + } + + @Override + public boolean remove( PrimitiveLongSet coll ) + { + return coll.remove( x ); + } + }; + } + }; + + @DataPoint + public static ValueProducer intLongV = new ValueProducer( + PrimitiveIntLongMap.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + final long y = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveIntLongMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveIntLongMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longIntV = new ValueProducer( + PrimitiveLongIntMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final int y = randomInt(); + return new Value() + { + @Override + public void add( PrimitiveLongIntMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongIntMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longLongV = new ValueProducer( + PrimitiveLongLongMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final long y = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveLongLongMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongLongMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer intObjV = + new ValueProducer( PrimitiveIntObjectMap.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + final Object y = new Object(); + return new Value() + { + @Override + public void add( PrimitiveIntObjectMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveIntObjectMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longObjV = + new ValueProducer( PrimitiveLongObjectMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final Object y = new Object(); + return new Value() + { + @Override + public void add( PrimitiveLongObjectMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongObjectMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + // ==== Primitive Collection Implementations ==== + + @DataPoint + public static Factory intSet = Primitive::intSet; + + @DataPoint + public static Factory intSetWithCapacity = () -> Primitive.intSet( randomCapacity() ); + + @DataPoint + public static Factory offheapIntSet = + () -> Primitive.offHeapIntSet( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapIntSetWithCapacity = + () -> Primitive.offHeapIntSet( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory longSet = Primitive::longSet; + + @DataPoint + public static Factory longSetWithCapacity = () -> Primitive.longSet( randomCapacity() ); + + @DataPoint + public static Factory offheapLongSet = + () -> Primitive.offHeapLongSet( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapLongSetWithCapacity = + () -> Primitive.offHeapLongSet( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory intLongMap = Primitive::intLongMap; + + @DataPoint + public static Factory intLongMapWithCapacity = () -> Primitive.intLongMap( randomCapacity() ); + + @DataPoint + public static Factory longIntMap = Primitive::longIntMap; + + @DataPoint + public static Factory longIntMapWithCapacity = () -> Primitive.longIntMap( randomCapacity() ); + + @DataPoint + public static Factory longLongMap = Primitive::longLongMap; + + @DataPoint + public static Factory longLongMapWithCapacity = + () -> Primitive.longLongMap( randomCapacity() ); + + @DataPoint + public static Factory offheapLongLongMap = + () -> Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapLongLongMapWithCapacity = + () -> Primitive.offHeapLongLongMap( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory intObjMap = Primitive::intObjectMap; + + @DataPoint + public static Factory intObjMapWithCapacity = + () -> Primitive.intObjectMap( randomCapacity() ); + + @DataPoint + public static Factory longObjectMap = Primitive::longObjectMap; + + @DataPoint + public static Factory longObjectMapWithCapacity = + () -> Primitive.longObjectMap( randomCapacity() ); + + private static final PrimitiveIntSet observedRandomInts = Primitive.intSet(); + private static final PrimitiveLongSet observedRandomLongs = Primitive.longSet(); + + /** + * Produce a random int that hasn't been seen before by any test. + */ + private static int randomInt() + { + int n; + do + { + n = ThreadLocalRandom.current().nextInt(); + } + while ( n == -1 || !observedRandomInts.add( n ) ); + return n; + } + + /** + * Produce a random long that hasn't been seen before by any test. + */ + private static long randomLong() + { + long n; + do + { + n = ThreadLocalRandom.current().nextLong(); + } + while ( n == -1 || !observedRandomLongs.add( n ) ); + return n; + } + + private static int randomCapacity() + { + return ThreadLocalRandom.current().nextInt( 30, 1200 ); + } + + private void assertEquals( PrimitiveCollection a, PrimitiveCollection b ) + { + assertThat( a, is( equalTo( b ) ) ); + assertThat( b, is( equalTo( a ) ) ); + assertThat( a.hashCode(), is( equalTo( b.hashCode() ) ) ); + } + + @Theory + public void collectionsAreNotEqualToObjectsOfOtherTypes( Factory factory ) + { + try ( PrimitiveCollection coll = factory.newInstance() ) + { + assertNotEquals( coll, new Object() ); + } + } + + @Theory + public void emptyCollectionsAreEqual( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + assertEquals( a, b ); + } + } + + @Theory + public void addingTheSameValuesMustProduceEqualCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + Value value = values.randomValue(); + value.add( a ); + value.add( b ); + assertEquals( a, b ); + } + } + + @Theory + public void addingDifferentValuesMustProduceUnequalCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + values.randomValue().add( a ); + values.randomValue().add( b ); + assertNotEquals( a, b ); + } + } + + @Theory + public void differentButEquivalentMutationsShouldProduceEqualCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + // Note that this test, cute as it is, also verifies that the hashCode implementation is order-invariant :) + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + Value x = values.randomValue(); + Value y = values.randomValue(); + Value z = values.randomValue(); + + x.add( a ); + z.add( a ); + + z.add( b ); + y.add( b ); + x.add( b ); + y.remove( b ); + + assertEquals( a, b ); + } + } + + @Theory + public void capacityDifferencesMustNotInfluenceEquality( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + List tmps = new ArrayList<>(); + for ( int i = 0; i < 5000; i++ ) + { + Value value = values.randomValue(); + value.add( b ); + tmps.add( value ); + } + + Value specificValue = values.randomValue(); + specificValue.add( a ); + specificValue.add( b ); + + for ( int i = 0; i < 5000; i++ ) + { + Value value = values.randomValue(); + value.add( b ); + tmps.add( value ); + } + + Collections.shuffle( tmps ); + for ( Value value: tmps ) + { + value.remove( b ); + } + + assertEquals( a, b ); + } + } + + @Theory + public void hashCodeMustFollowValues( + ValueProducer values, Factory factory ) + { + assumeTrue( values.isApplicable( factory ) ); + try ( PrimitiveCollection a = factory.newInstance() ) + { + Value x = values.randomValue(); + Value y = values.randomValue(); + Value z = values.randomValue(); + + int i = a.hashCode(); + x.add( a ); + int j = a.hashCode(); + y.add( a ); + int k = a.hashCode(); + z.add( a ); + int l = a.hashCode(); + z.remove( a ); + int m = a.hashCode(); + y.remove( a ); + int n = a.hashCode(); + x.remove( a ); + int o = a.hashCode(); + + assertThat( "0 elm hashcode equal", o, is( i ) ); + assertThat( "1 elm hashcode equal", n, is( j ) ); + assertThat( "2 elm hashcode equal", m, is( k ) ); + assertThat( "3 elm hashcode distinct", l, not( isOneOf( i, j, k, m, n, o ) ) ); + assertThat( "2 elm hashcode distinct", k, not( isOneOf( i, j, l, n, o ) ) ); + assertThat( "1 elm hashcode distinct", n, not( isOneOf( i, k, l, m, o ) ) ); + assertThat( "0 elm hashcode distinct", i, not( isOneOf( j, k, l, m, n ) ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java new file mode 100644 index 0000000000..ee10e75dec --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; + +import static org.junit.Assert.assertEquals; + +public class PrimitiveIntObjectHashMapTest +{ + + @Test + public void doNotComputeValueIfPresent() + { + PrimitiveIntObjectMap intObjectMap = Primitive.intObjectMap(); + intObjectMap.put( 1, "a" ); + assertEquals( "a", intObjectMap.computeIfAbsent( 1, value -> "b" ) ); + } + + @Test + public void computeValueIfAbsent() + { + PrimitiveIntObjectMap intObjectMap = Primitive.intObjectMap(); + intObjectMap.put( 1, "a" ); + assertEquals( "b", intObjectMap.computeIfAbsent( 2, value -> "b" ) ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java new file mode 100644 index 0000000000..489dfce888 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PrimitiveLongIntMapRIT +{ + @Test + public void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( mapFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + + fullVerification( result.getTarget(), random ); + } + } + + private void fullVerification( Maps target, Random random ) + { + for ( Map.Entry entry: target.normalMap.entrySet() ) + { + assertTrue( target.map.containsKey( entry.getKey() ) ); + assertEquals( entry.getValue().intValue(), target.map.get( entry.getKey() ) ); + } + + for ( int i = 0; i < target.normalMap.size(); i++ ) + { + assertFalse( target.map.containsKey( randomNonExisting( random, target.normalMap ) ) ); + } + } + + private Printable given() + { + return out -> out.println( PrimitiveLongIntMap.class.getSimpleName() + " map = " + + Primitive.class.getSimpleName() + ".longIntMap();" ); + } + + private ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private TargetFactory mapFactory() + { + return Maps::new; + } + + protected Action generateAction( Random random, Maps from ) + { + boolean anExisting = !from.normalMap.isEmpty() && random.nextInt( 3 ) == 0; + long key = anExisting ? + randomExisting( random, from.normalMap ) : + randomNonExisting( random, from.normalMap ); + Integer value = random.nextInt( 100 ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( key ); + } + + // add + return new AddAction( key, value ); + } + + private long randomNonExisting( Random random, Map existing ) + { + while ( true ) + { + long key = Math.abs( random.nextLong() ); + if ( !existing.containsKey( key ) ) + { + return key; + } + } + } + + private long randomExisting( Random random, Map existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.keySet().iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long key; + private final int value; + + AddAction( long key, int value ) + { + this.key = key; + this.value = value; + } + + @Override + public String apply( Maps target ) + { + boolean existing = target.normalMap.containsKey( key ); + int existingValue = existing ? target.normalMap.get( key ) : -1; + int actualSizeBefore = target.normalMap.size(); + + int sizeBefore = target.map.size(); + boolean existedBefore = target.map.containsKey( key ); + int valueBefore = target.map.get( key ); + int previous = target.map.put( key, value ); + boolean existsAfter = target.map.containsKey( key ); + int valueAfter = target.map.get( key ); + target.normalMap.put( key, value ); + int sizeAfter = target.map.size(); + + int actualSizeAfter = target.normalMap.size(); + boolean ok = + (sizeBefore == actualSizeBefore) & + (existedBefore == existing) & + (existingValue == valueBefore) & + (existingValue == previous) & + (valueAfter == value) & + existsAfter & + (sizeAfter == actualSizeAfter); + return ok ? null : "" + key + ":" + value + "," + existingValue + "," + existedBefore + + "," + previous + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + String addition = "map.put( " + key + ", " + value + " );"; + if ( includeChecks ) + { + boolean existing = source.normalMap.containsKey( key ); + int existingValue = existing ? source.normalMap.get( key ) : -1; + out.println( format( "int sizeBefore = map.size();" ) ); + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "int valueBefore = map.get( %d );", key ) ); + out.println( format( "int previous = %s", addition ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "int valueAfter = map.get( %d );", key ) ); + out.println( format( "int sizeAfter = map.size();" ) ); + + int actualSizeBefore = source.normalMap.size(); + out.println( format( "assertEquals( \"%s\", %d, sizeBefore );", + "Size before put should have been " + actualSizeBefore, actualSizeBefore ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", %d, previous );", + "value returned from put should be " + existingValue, existingValue ) ); + out.println( format( "assertTrue( \"%s\", existsAfter );", + key + " should exist" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueAfter );", + "value after putting should be " + value, value ) ); + int actualSizeAfter = existing ? actualSizeBefore : actualSizeBefore + 1; + out.println( format( "assertEquals( \"%s\", %d, sizeAfter );", + "Size after put should have been " + actualSizeAfter, actualSizeAfter ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long key; + + RemoveAction( long key ) + { + this.key = key; + } + + @Override + public String apply( Maps target ) + { + boolean existing = target.normalMap.containsKey( key ); + int existingValue = existing ? target.normalMap.get( key ) : -1; + + boolean existedBefore = target.map.containsKey( key ); + int valueBefore = target.map.get( key ); + int removed = target.map.remove( key ); + boolean existsAfter = target.map.containsKey( key ); + int valueAfter = target.map.get( key ); + target.normalMap.remove( key ); + + boolean ok = + (existedBefore == existing) & + (existingValue == valueBefore) & + (existingValue == removed) & + (valueAfter == -1) & + !existsAfter; + return ok ? null : "" + key + "," + existingValue + "," + existedBefore + + "," + removed + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + String removal = "map.remove( " + key + " );"; + if ( includeChecks ) + { + boolean existing = source.normalMap.containsKey( key ); + int existingValue = existing ? source.normalMap.get( key ) : -1; + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "int valueBefore = map.get( %d );", key ) ); + out.println( format( "int removed = %s", removal ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "int valueAfter = map.get( %d );", key ) ); + + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before removing here" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", %d, removed );", + "value returned from remove should be " + existingValue, existingValue ) ); + out.println( format( "assertFalse( \"%s\", existsAfter );", + key + " should not exist" ) ); + out.println( format( "assertEquals( \"%s\", -1, valueAfter );", + "value after removing should be -1" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Maps implements TestResource + { + final Map normalMap = new HashMap<>(); + final PrimitiveLongIntMap map = Primitive.longIntMap(); + + @Override + public String toString() + { + return map.toString(); + } + + @Override + public void close() + { + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java new file mode 100644 index 0000000000..4616da6bad --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java @@ -0,0 +1,1373 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntLongMap; +import org.neo4j.collection.primitive.PrimitiveIntLongVisitor; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; +import org.neo4j.collection.primitive.PrimitiveIntObjectVisitor; +import org.neo4j.collection.primitive.PrimitiveIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.collection.primitive.PrimitiveLongIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongLongMap; +import org.neo4j.collection.primitive.PrimitiveLongLongVisitor; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.collection.primitive.PrimitiveLongObjectVisitor; +import org.neo4j.collection.primitive.PrimitiveLongVisitor; +import org.neo4j.memory.GlobalMemoryTracker; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class PrimitiveLongMapTest +{ + @Test + public void shouldContainAddedValues() + { + // GIVEN + Map expectedEntries = new HashMap<>(); + expectedEntries.put( 1994703545L, 59 ); + expectedEntries.put( 1583732120L, 98 ); + expectedEntries.put( 756530774L, 56 ); + expectedEntries.put( 1433091763L, 22 ); + + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + for ( Map.Entry entry: expectedEntries.entrySet() ) + { + map.put( entry.getKey(), entry.getValue() ); + } + + // WHEN/THEN + boolean existedBefore = map.containsKey( 1433091763 ); + Integer valueBefore = map.get( 1433091763 ); + Integer previous = map.put( 1433091763, 35 ); + boolean existsAfter = map.containsKey( 1433091763 ); + Integer valueAfter = map.get( 1433091763 ); + assertTrue( "1433091763 should exist before putting here", existedBefore ); + assertEquals( (Integer) 22, valueBefore ); + assertEquals( (Integer) 22, previous ); + assertTrue( "(1433091763, 35) should exist", existsAfter ); + assertEquals( (Integer) 35, valueAfter ); + expectedEntries.put( 1433091763L, 35 ); + + final Map visitedEntries = new HashMap<>(); + map.visitEntries( ( key, value ) -> + { + visitedEntries.put( key, value ); + return false; + } ); + assertEquals( expectedEntries, visitedEntries ); + } + + @Test + public void shouldContainAddedValues_2() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1950736976, 4 ); + map.put( 1054824202, 58 ); + map.put( 348690619, 54 ); + map.put( 1224909480, 79 ); + map.put( 1508493474, 82 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 1508493474 ); + Integer valueBefore = map.get( 1508493474 ); + Integer previous = map.put( 1508493474, 62 ); + boolean existsAfter = map.containsKey( 1508493474 ); + Integer valueAfter = map.get( 1508493474 ); + assertTrue( "1508493474 should exist before putting here", existedBefore ); + assertEquals( "value before should be 82", (Integer) 82, valueBefore ); + assertEquals( "value returned from put should be 82", (Integer) 82, previous ); + assertTrue( "1508493474 should exist", existsAfter ); + assertEquals( "value after putting should be 62", (Integer) 62, valueAfter ); + } + + @Test + public void shouldContainAddedValues_3() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.remove( 1338037218 ); + map.put( 680125236, 83 ); + map.put( 680125236, 76 ); + map.put( 680125236, 47 ); + map.put( 680125236, 30 ); + map.put( 2080483597, 52 ); + map.put( 867107519, 80 ); + map.remove( 710100384 ); + map.put( 671477921, 88 ); + map.put( 1163609643, 17 ); + map.put( 680125236, 57 ); + map.put( 1163609643, 70 ); + map.put( 2080483597, 89 ); + map.put( 1472451898, 62 ); + map.put( 1379499183, 93 ); + map.put( 680125236, 17 ); + map.put( 567842571, 43 ); + map.put( 2045599221, 60 ); + map.remove( 641295711 ); + map.remove( 867107519 ); + map.put( 2045599221, 30 ); + map.remove( 2094689486 ); + map.put( 1572965945, 79 ); + map.remove( 1329473388 ); + map.put( 1572965945, 39 ); + map.put( 264067586, 60 ); + map.put( 1751846500, 5 ); + map.put( 1163609643, 25 ); + map.put( 1379499183, 54 ); + map.remove( 671477921 ); + map.put( 1572965945, 59 ); + map.put( 880140639, 87 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 468007595 ); + Integer valueBefore = map.get( 468007595 ); + Integer previous = map.put( 468007595, 67 ); + boolean existsAfter = map.containsKey( 468007595 ); + Integer valueAfter = map.get( 468007595 ); + assertFalse( "468007595 should not exist before putting here", existedBefore ); + assertNull( "value before putting should be null", valueBefore ); + assertNull( "value returned from putting should be null", previous ); + assertTrue( "468007595 should exist", existsAfter ); + assertEquals( "value after putting should be 67", (Integer) 67, valueAfter ); + } + + @Test + public void shouldHaveCorrectSize() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 152407843, 17 ); + map.put( 435803197, 29 ); + map.put( 2063473573, 75 ); + map.put( 162922679, 36 ); + map.put( 923042422, 47 ); + map.put( 204556993, 28 ); + map.put( 109670524, 80 ); + map.put( 214127443, 88 ); + map.put( 297958695, 97 ); + map.put( 873122371, 73 ); + map.put( 398704786, 25 ); + map.put( 376378917, 62 ); + map.put( 1948985185, 3 ); + map.put( 918339266, 4 ); + map.put( 1126937431, 48 ); + map.put( 568627750, 6 ); + map.put( 887668742, 1 ); + map.put( 888089153, 88 ); + map.put( 1671871078, 26 ); + map.put( 479217936, 11 ); + map.put( 1874408328, 56 ); + map.put( 1517450283, 83 ); + map.put( 1352952211, 57 ); + map.put( 686066722, 92 ); + map.put( 1593196310, 71 ); + map.put( 1535351391, 62 ); + map.put( 296560052, 59 ); + map.put( 1513542622, 49 ); + map.put( 1899330306, 57 ); + map.put( 746190595, 31 ); + map.put( 1216091366, 90 ); + map.put( 353922939, 16 ); + map.put( 680935464, 16 ); + map.put( 235368309, 8 ); + map.put( 1988133681, 32 ); + map.put( 330747855, 81 ); + map.put( 492627887, 74 ); + map.put( 1005495348, 8 ); + map.put( 2107419277, 82 ); + map.put( 1421265494, 15 ); + map.put( 1669915469, 92 ); + map.put( 2008247215, 9 ); + map.put( 2010142383, 77 ); + map.put( 829081830, 25 ); + map.put( 1349259272, 38 ); + map.put( 1987482877, 8 ); + map.put( 974334859, 83 ); + map.put( 1376908873, 10 ); + map.put( 2120105656, 22 ); + map.put( 1634193445, 8 ); + map.put( 1160987255, 34 ); + map.put( 2030156381, 16 ); + map.put( 2012943328, 22 ); + map.put( 75749275, 54 ); + map.put( 1415817090, 35 ); + map.put( 562352348, 43 ); + map.put( 658501173, 96 ); + map.put( 441278652, 24 ); + map.put( 633855945, 82 ); + map.put( 579807215, 31 ); + map.put( 1125922962, 33 ); + map.put( 1995076951, 91 ); + map.put( 322776761, 4 ); + map.put( 1011369342, 36 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 679686325 ); + Integer valueBefore = map.get( 679686325 ); + Integer previous = map.put( 679686325, 63 ); + boolean existsAfter = map.containsKey( 679686325 ); + Integer valueAfter = map.get( 679686325 ); + int sizeAfter = map.size(); + assertEquals( "Size before put should have been 64", 64, sizeBefore ); + assertFalse( "679686325 should not exist before putting here", existedBefore ); + assertNull( "value before putting should be null", valueBefore ); + assertNull( "value returned from putting should be null", previous ); + assertTrue( "679686325 should exist", existsAfter ); + assertEquals( "value after putting should be 63", (Integer) 63, valueAfter ); + assertEquals( "Size after put should have been 65", 65, sizeAfter ); + } + + @Test + public void shouldMoveValuesWhenMovingEntriesAround() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 206243105, 47 ); + map.put( 2083304695, 63 ); + map.put( 689837337, 7 ); + map.remove( 206243105 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 689837337 ); + Integer valueBefore = map.get( 689837337 ); + Integer previous = map.put( 689837337, 20 ); + boolean existsAfter = map.containsKey( 689837337 ); + Integer valueAfter = map.get( 689837337 ); + int sizeAfter = map.size(); + assertEquals( "Size before put should have been 2", 2, sizeBefore ); + assertTrue( "689837337 should exist before putting here", existedBefore ); + assertEquals( "value before should be 7", (Integer) 7, valueBefore ); + assertEquals( "value returned from put should be 7", (Integer) 7, previous ); + assertTrue( "689837337 should exist", existsAfter ); + assertEquals( "value after putting should be 20", (Integer) 20, valueAfter ); + assertEquals( "Size after put should have been 2", 2, sizeAfter ); + } + + @Test + public void shouldReturnCorrectPreviousValue() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.remove( 2050585513 ); + map.put( 429170228, 99 ); + map.put( 1356282827, 24 ); + map.remove( 1341095873 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 429170228 ); + int valueBefore = map.get( 429170228 ); + int previous = map.put( 429170228, 1 ); + boolean existsAfter = map.containsKey( 429170228 ); + int valueAfter = map.get( 429170228 ); + int sizeAfter = map.size(); + assertEquals( "Size before put should have been 2", 2, sizeBefore ); + assertTrue( "429170228 should exist before putting here", existedBefore ); + assertEquals( "value before should be 99", 99, valueBefore ); + assertEquals( "value returned from put should be 99", 99, previous ); + assertTrue( "429170228 should exist", existsAfter ); + assertEquals( "value after putting should be 1", 1, valueAfter ); + assertEquals( "Size after put should have been 2", 2, sizeAfter ); + } + + @Test + public void shouldOnlyContainAddedValues() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1179059774, 54 ); + map.put( 612612792, 91 ); + map.put( 853030395, 81 ); + map.put( 1821941016, 69 ); + map.put( 815540261, 54 ); + map.put( 2120470777, 63 ); + map.put( 866144206, 41 ); + map.put( 905659306, 86 ); + map.put( 602586792, 24 ); + map.put( 1033857549, 61 ); + map.put( 1570231638, 69 ); + map.put( 30675820, 53 ); + map.put( 433666923, 14 ); + map.put( 1668952952, 52 ); + map.put( 1733960171, 14 ); + map.put( 1240027317, 64 ); + map.put( 250830995, 71 ); + map.put( 1446519846, 17 ); + map.put( 1857052106, 78 ); + map.put( 37351838, 26 ); + map.put( 1523695604, 78 ); + map.put( 1024540180, 12 ); + map.put( 603632507, 81 ); + map.put( 483087335, 37 ); + map.put( 216300592, 55 ); + map.put( 1729046213, 72 ); + map.put( 1397559084, 78 ); + map.put( 802042428, 34 ); + map.put( 1127990805, 6 ); + map.put( 2081866795, 53 ); + map.put( 1528122026, 39 ); + map.put( 642547543, 78 ); + map.put( 1909701557, 35 ); + map.put( 2070740876, 40 ); + map.put( 316027755, 18 ); + map.put( 824089651, 63 ); + map.put( 1082682044, 85 ); + map.put( 154864377, 44 ); + map.put( 26918244, 73 ); + map.put( 808069768, 20 ); + map.put( 38089155, 17 ); + map.put( 1772700678, 35 ); + map.put( 1790535392, 82 ); + map.put( 159186757, 10 ); + map.put( 73305650, 52 ); + map.put( 2025019209, 38 ); + map.put( 922996536, 53 ); + map.put( 1852424925, 34 ); + map.put( 1181179273, 9 ); + map.put( 107520967, 11 ); + map.put( 1702904247, 55 ); + map.put( 1819417390, 50 ); + map.put( 1163114165, 57 ); + map.put( 2036796587, 40 ); + map.put( 2130510197, 26 ); + map.put( 1710533919, 70 ); + map.put( 497498438, 48 ); + map.put( 147722732, 8 ); + map.remove( 802042428 ); + map.put( 1355114893, 90 ); + map.put( 419675404, 62 ); + map.put( 1722846265, 41 ); + map.put( 1287254514, 61 ); + map.put( 1925017947, 8 ); + map.put( 1290391303, 59 ); + map.put( 1938779966, 27 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 1452811669 ); + int valueBefore = map.get( 1452811669 ); + int previous = map.put( 1452811669, 16 ); + boolean existsAfter = map.containsKey( 1452811669 ); + int valueAfter = map.get( 1452811669 ); + int sizeAfter = map.size(); + assertEquals( "Size before put should have been 64", 64, sizeBefore ); + assertFalse( "1452811669 should not exist before putting here", existedBefore ); + assertEquals( "value before should be -1", -1, valueBefore ); + assertEquals( "value returned from put should be -1", -1, previous ); + assertTrue( "1452811669 should exist", existsAfter ); + assertEquals( "value after putting should be 16", 16, valueAfter ); + assertEquals( "Size after put should have been 65", 65, sizeAfter ); + } + + @Test + public void shouldOnlyContainAddedValues_2() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 913910231, 25 ); + map.put( 102310782, 40 ); + map.put( 634960377, 32 ); + map.put( 947168147, 96 ); + map.put( 947430652, 26 ); + map.put( 1391472521, 72 ); + map.put( 7905512, 10 ); + map.put( 7905512, 2 ); + map.put( 1391472521, 66 ); + map.put( 824376092, 79 ); + map.remove( 750639810 ); + map.put( 947168147, 61 ); + map.put( 831409018, 57 ); + map.put( 241941283, 76 ); + map.put( 824376092, 45 ); + map.remove( 2125994926 ); + map.put( 824376092, 47 ); + map.put( 1477982280, 1 ); + map.remove( 2129508263 ); + map.put( 1477982280, 41 ); + map.put( 642178985, 69 ); + map.put( 1447441709, 85 ); + map.put( 642178985, 27 ); + map.put( 875840384, 72 ); + map.put( 1967716733, 55 ); + map.put( 1965379174, 5 ); + map.put( 913910231, 40 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 947430652 ); + int valueBefore = map.get( 947430652 ); + int removed = map.remove( 947430652 ); + boolean existsAfter = map.containsKey( 947430652 ); + int valueAfter = map.get( 947430652 ); + assertTrue( "947430652 should exist before removing here", existedBefore ); + assertEquals( "value before should be 26", 26, valueBefore ); + assertEquals( "value returned from remove should be 26", 26, removed ); + assertFalse( "947430652 should not exist", existsAfter ); + assertEquals( "value after removing should be -1", -1, valueAfter ); + } + + @Test + public void shouldOnlyContainAddedValues_3() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 2083704227957337692L, 50 ); + map.put( 1039748383662879297L, 12 ); + map.put( 6296247210943123044L, 45 ); + map.put( 8004677065031068097L, 5 ); + map.put( 1039748383662879297L, 70 ); + map.put( 5386804704064477958L, 97 ); + map.remove( 1506507783133586973L ); + map.put( 4287434858289406631L, 29 ); + map.put( 8004677065031068097L, 17 ); + map.put( 986286772325632801L, 14 ); + map.put( 7880139640446289959L, 68 ); + map.put( 8004677065031068097L, 23 ); + map.put( 5386804704064477958L, 72 ); + map.put( 5386804704064477958L, 71 ); + map.put( 2300381985575721987L, 0 ); + map.put( 6144230340727188436L, 31 ); + map.put( 425423457410117293L, 88 ); + map.put( 2083704227957337692L, 65 ); + map.put( 7805027477403310582L, 72 ); + map.put( 2254081933055750443L, 66 ); + map.put( 5386804704064477958L, 46 ); + map.put( 5787098127909281443L, 45 ); + map.put( 5508645210651400664L, 45 ); + map.put( 6092264867460428040L, 65 ); + map.put( 4551026293109220157L, 52 ); + map.put( 4669163071261559807L, 33 ); + map.put( 5790325306669462860L, 96 ); + map.put( 4337317298737908324L, 78 ); + map.put( 986286772325632801L, 71 ); + map.put( 4287434858289406631L, 47 ); + map.put( 1827085004206892313L, 30 ); + map.put( 6070945099342863711L, 88 ); + map.remove( 6300957726732252611L ); + map.put( 2300381985575721987L, 22 ); + map.put( 2083704227957337692L, 2 ); + map.put( 2885272279767063039L, 71 ); + map.put( 3627867780921264529L, 5 ); + map.remove( 5330274310754559602L ); + map.put( 8902857048431919030L, 23 ); + map.remove( 4287434858289406631L ); + map.put( 5459968256561120197L, 8 ); + map.put( 5790325306669462860L, 17 ); + map.put( 9003964541346458616L, 45 ); + map.put( 3832091967762842783L, 79 ); + map.put( 1332274446340546922L, 62 ); + map.put( 6610784890222945257L, 20 ); + map.put( 3627867780921264529L, 65 ); + map.put( 7988336790991560848L, 89 ); + map.put( 5386804704064477958L, 15 ); + map.put( 6296247210943123044L, 19 ); + map.put( 7776019112299874624L, 67 ); + map.put( 5827611175622537127L, 18 ); + map.remove( 8004677065031068097L ); + map.put( 2451971987846333787L, 48 ); + map.put( 3627867780921264529L, 16 ); + map.put( 2506727685914893570L, 61 ); + map.put( 6629089416451699826L, 89 ); + map.put( 875078333857781813L, 38 ); + map.put( 439984342972777679L, 51 ); + map.put( 9077428346047966819L, 19 ); + map.put( 7045299269724516542L, 73 ); + map.put( 8055487013098459354L, 24 ); + map.put( 6610784890222945257L, 65 ); + map.put( 986286772325632801L, 29 ); + map.put( 133928815519522465L, 81 ); + map.put( 5780114596098993316L, 15 ); + map.put( 3790785290324207363L, 91 ); + map.put( 2795040354588080479L, 48 ); + map.put( 4218658174275197144L, 59 ); + map.put( 6610784890222945257L, 70 ); + map.remove( 3722940212039795685L ); + map.put( 1817899559164238906L, 30 ); + map.put( 4551026293109220157L, 35 ); + map.put( 986286772325632801L, 57 ); + map.put( 3811462607668925015L, 57 ); + map.put( 2795040354588080479L, 85 ); + map.put( 8460476221939231932L, 86 ); + map.remove( 8957537157979159052L ); + map.put( 2032224502814063026L, 57 ); + map.remove( 8924941903092284834L ); + map.put( 5386804704064477958L, 2 ); + map.put( 6629089416451699826L, 18 ); + map.put( 425423457410117293L, 31 ); + map.put( 4337317298737908324L, 35 ); + map.remove( 5337770067730257989L ); + map.put( 6150561851033498431L, 49 ); + map.put( 5067121328094576685L, 46 ); + map.remove( 3742103310924563011L ); + map.put( 1327614778938791146L, 49 ); + map.put( 255729841510922319L, 16 ); + map.put( 8785988080128503533L, 69 ); + map.put( 4218658174275197144L, 20 ); + map.put( 1265271287408386915L, 43 ); + map.put( 255729841510922319L, 5 ); + map.put( 8651736753344997668L, 41 ); + map.put( 4363375305508283265L, 4 ); + map.put( 4185381066643227500L, 29 ); + map.put( 3790785290324207363L, 58 ); + map.put( 3058911485922749695L, 1 ); + map.put( 8629268898854377850L, 66 ); + map.put( 1762013345156514959L, 5 ); + map.remove( 4354754593499656793L ); + map.put( 1332274446340546922L, 16 ); + map.put( 4953501292937412915L, 87 ); + map.put( 2330841365833073849L, 83 ); + map.put( 8096564328797694553L, 44 ); + map.put( 8935185623148330821L, 7 ); + map.put( 6150561851033498431L, 48 ); + map.remove( 5827611175622537127L ); + map.put( 8048363335369773749L, 25 ); + map.put( 3627867780921264529L, 48 ); + map.put( 4806848030248674690L, 14 ); + map.put( 5430628648110105698L, 30 ); + map.remove( 7261476188677343032L ); + map.put( 1265271287408386915L, 61 ); + map.put( 9077428346047966819L, 32 ); + map.put( 1827085004206892313L, 95 ); + map.put( 6377023652046870199L, 8 ); + map.remove( 8096564328797694553L ); + map.put( 458594253548258561L, 37 ); + map.put( 4418108647578170347L, 60 ); + map.put( 4363375305508283265L, 50 ); + map.remove( 3220719966247388754L ); + map.put( 5067121328094576685L, 86 ); + map.put( 8030171618634928529L, 9 ); + map.remove( 5790325306669462860L ); + map.remove( 1693435088303118108L ); + map.put( 1817899559164238906L, 48 ); + map.put( 2823063986711596775L, 58 ); + map.put( 5065867711051034527L, 1 ); + map.put( 6144553725832876585L, 16 ); + map.put( 6066303112518690730L, 96 ); + map.put( 1627429134135319103L, 64 ); + map.put( 2083704227957337692L, 48 ); + map.put( 5074984076240598083L, 46 ); + map.put( 273737562207470342L, 60 ); + map.put( 5065867711051034527L, 7 ); + map.put( 1425720210238734727L, 23 ); + map.put( 8840483239403421070L, 42 ); + map.put( 622393419539870960L, 66 ); + map.put( 4649317581471627693L, 84 ); + map.put( 6344284253098418581L, 10 ); + map.put( 6066303112518690730L, 14 ); + map.put( 2032224502814063026L, 72 ); + map.put( 3860451022347437817L, 26 ); + map.put( 1931469116507191845L, 30 ); + map.put( 7264376865632246862L, 81 ); + map.put( 875078333857781813L, 41 ); + map.put( 6066303112518690730L, 65 ); + map.put( 357446231240164192L, 80 ); + map.put( 90138258774469874L, 73 ); + map.put( 2550828149718879762L, 72 ); + map.put( 357446231240164192L, 17 ); + map.put( 4233359298058523722L, 83 ); + map.put( 7879882017779927485L, 33 ); + map.put( 4554977248866184403L, 64 ); + map.put( 2032224502814063026L, 11 ); + map.put( 8460476221939231932L, 65 ); + map.put( 4404294840535520232L, 58 ); + map.put( 439984342972777679L, 83 ); + map.put( 143440583901416159L, 59 ); + map.put( 6980461179076170770L, 9 ); + map.put( 4253079906814783119L, 93 ); + map.put( 6377023652046870199L, 20 ); + map.put( 2885272279767063039L, 5 ); + map.put( 1115850061381524772L, 37 ); + map.put( 4288489609244987651L, 22 ); + map.put( 1869499448099043543L, 73 ); + map.put( 2233583342469238733L, 84 ); + map.put( 8785988080128503533L, 61 ); + map.put( 7396264003126204068L, 81 ); + map.put( 6553509363155186775L, 96 ); + map.put( 1265663249510580286L, 89 ); + map.put( 8824139147632000339L, 49 ); + map.put( 8629268898854377850L, 10 ); + map.put( 6463027127151126151L, 57 ); + map.put( 2577561266405706623L, 46 ); + map.put( 2942302849662258387L, 40 ); + map.put( 2233583342469238733L, 56 ); + map.put( 7971826071187872579L, 53 ); + map.put( 1425720210238734727L, 27 ); + map.remove( 7194434791627009043L ); + map.put( 1429250394105883546L, 82 ); + map.put( 8048363335369773749L, 19 ); + map.put( 425423457410117293L, 51 ); + map.remove( 3570674569632664356L ); + map.remove( 5925614419318569326L ); + map.put( 245367449754197583L, 27 ); + map.put( 8724491045048677021L, 55 ); + map.put( 1037934857236019066L, 66 ); + map.put( 8902857048431919030L, 61 ); + map.put( 4806848030248674690L, 17 ); + map.put( 8840483239403421070L, 95 ); + map.put( 2931578375554111170L, 54 ); + map.put( 5352224688502007093L, 36 ); + map.put( 6675404627060358866L, 64 ); + map.put( 5011448804620449550L, 48 ); + map.put( 9003964541346458616L, 44 ); + map.put( 8614830761978541860L, 70 ); + map.put( 3790785290324207363L, 95 ); + map.put( 3524676886726253569L, 54 ); + map.put( 6858076293577130289L, 60 ); + map.put( 6721253107702965701L, 41 ); + map.put( 655525227420977141L, 94 ); + map.put( 2344362186561469072L, 29 ); + map.put( 6144230340727188436L, 76 ); + map.put( 6751209943070153529L, 22 ); + map.put( 5528119873376392874L, 44 ); + map.put( 6675404627060358866L, 20 ); + map.put( 6167523814676644161L, 50 ); + map.put( 4288489609244987651L, 82 ); + map.remove( 3362704467864439992L ); + map.put( 8629268898854377850L, 50 ); + map.remove( 8824139147632000339L ); + map.remove( 8563575034946766108L ); + map.put( 4391871381220263726L, 20 ); + map.remove( 6143313773038364355L ); + map.remove( 3225044803974988142L ); + map.remove( 8048363335369773749L ); + map.remove( 439984342972777679L ); + map.put( 7776019112299874624L, 8 ); + map.put( 5414055783993307402L, 13 ); + map.put( 425423457410117293L, 91 ); + map.put( 8407567928758710341L, 30 ); + map.put( 6070945099342863711L, 14 ); + map.put( 5644323748441073606L, 91 ); + map.put( 5297141920581728538L, 61 ); + map.put( 7880139640446289959L, 1 ); + map.put( 2300381985575721987L, 92 ); + map.put( 8253246663621301435L, 26 ); + map.remove( 2074764355175726009L ); + map.remove( 3823843425563676964L ); + map.put( 8314906688468605292L, 91 ); + map.put( 6864119235983684905L, 56 ); + map.put( 6610784890222945257L, 85 ); + map.put( 3790785290324207363L, 7 ); + map.put( 9077428346047966819L, 20 ); + map.put( 5594781060356781714L, 76 ); + map.put( 4288489609244987651L, 24 ); + map.put( 5427718399315377322L, 93 ); + map.put( 6858076293577130289L, 41 ); + map.put( 4233359298058523722L, 43 ); + map.put( 3058911485922749695L, 88 ); + map.remove( 1327614778938791146L ); + map.put( 4665341449948530032L, 26 ); + map.remove( 2860868006143077426L ); + map.put( 6167523814676644161L, 70 ); + map.remove( 8314906688468605292L ); + map.put( 6396314739926743170L, 25 ); + map.put( 8924527320597926970L, 40 ); + map.put( 1817899559164238906L, 84 ); + map.remove( 4391871381220263726L ); + map.put( 8850817829384121639L, 50 ); + map.put( 6513548978704592547L, 52 ); + map.remove( 6066303112518690730L ); + map.remove( 3946964103425920940L ); + map.put( 7971826071187872579L, 71 ); + map.put( 90138258774469874L, 78 ); + map.put( 8309039683334256753L, 44 ); + map.put( 327300646665050265L, 52 ); + map.put( 4239841777571533415L, 22 ); + map.put( 7391753878925882699L, 46 ); + map.put( 5987501380005333533L, 31 ); + map.put( 6734545541042861356L, 45 ); + map.remove( 6566682167801344029L ); + map.put( 4218658174275197144L, 16 ); + map.put( 4363586488886891680L, 88 ); + map.put( 8030171618634928529L, 19 ); + map.put( 6513548978704592547L, 95 ); + map.put( 6721253107702965701L, 55 ); + map.put( 2153470608693815785L, 9 ); + map.put( 5807454155419905847L, 7 ); + map.remove( 4528425347504500078L ); + map.put( 339083533777732657L, 72 ); + map.put( 5162811261582626928L, 68 ); + map.put( 5459968256561120197L, 89 ); + map.put( 946125626260258615L, 97 ); + map.put( 986286772325632801L, 26 ); + map.put( 8309039683334256753L, 74 ); + map.put( 1609193622622537433L, 84 ); + map.put( 2506727685914893570L, 9 ); + map.put( 143440583901416159L, 33 ); + map.put( 7716482408003289208L, 30 ); + map.put( 7880139640446289959L, 74 ); + map.put( 5472992709007694577L, 27 ); + map.put( 3367972495572249232L, 8 ); + map.put( 6002824320296423294L, 71 ); + map.put( 5162811261582626928L, 10 ); + map.remove( 8309039683334256753L ); + map.put( 3103455156394998975L, 1 ); + map.put( 4943074037151902792L, 38 ); + map.put( 1455801901314190156L, 98 ); + map.put( 3502583509759951230L, 22 ); + map.remove( 8464127935014315372L ); + map.put( 6858076293577130289L, 35 ); + map.put( 8487179770790306175L, 5 ); + map.put( 946125626260258615L, 85 ); + map.put( 722144778357869055L, 1 ); + map.remove( 6832604792388788147L ); + map.remove( 7879882017779927485L ); + map.put( 4636443662717865247L, 98 ); + map.put( 6950926592851406543L, 12 ); + map.put( 8536120340569832116L, 73 ); + map.put( 86730768989854734L, 66 ); + map.put( 4558683789229895837L, 26 ); + map.put( 4806848030248674690L, 11 ); + map.put( 425423457410117293L, 38 ); + map.put( 8713875164075871710L, 97 ); + map.put( 3790785290324207363L, 77 ); + map.put( 4632006356221328093L, 21 ); + map.put( 7628512490650429100L, 28 ); + map.remove( 4651124484202085669L ); + map.put( 4320012891688937760L, 22 ); + map.put( 6092264867460428040L, 86 ); + map.put( 6610784890222945257L, 71 ); + map.remove( 3515175120945606156L ); + map.put( 5787098127909281443L, 10 ); + map.put( 5057609667342409825L, 50 ); + map.put( 5903362554916539560L, 75 ); + map.remove( 5339209082212961633L ); + map.put( 3502583509759951230L, 36 ); + map.put( 4198420341072443663L, 75 ); + map.put( 5037754181090593008L, 34 ); + map.put( 39606137866137388L, 19 ); + map.remove( 622393419539870960L ); + map.put( 2783004740411041924L, 79 ); + map.put( 6232331175163415825L, 72 ); + map.put( 4367206208262757151L, 33 ); + map.remove( 5879159150292946046L ); + map.put( 722144778357869055L, 80 ); + map.put( 9006426844471489361L, 92 ); + map.put( 550025535839604778L, 32 ); + map.remove( 5855895659233120621L ); + map.put( 1455801901314190156L, 24 ); + map.put( 3860451022347437817L, 81 ); + map.put( 2672104991948169160L, 57 ); + map.remove( 3860451022347437817L ); + map.remove( 655525227420977141L ); + map.put( 2413633498546493443L, 68 ); + map.put( 4185381066643227500L, 54 ); + map.put( 1280345971255663584L, 39 ); + map.put( 5796123963544961504L, 76 ); + map.put( 1892786158672061630L, 55 ); + map.remove( 5352224688502007093L ); + map.put( 3711105805930144213L, 47 ); + map.put( 4608237982157900285L, 41 ); + map.put( 4175794211341763944L, 31 ); + map.put( 2315250912582233395L, 81 ); + map.put( 357446231240164192L, 87 ); + map.put( 4110861648946406824L, 75 ); + map.put( 6912381889380280106L, 22 ); + map.put( 6721253107702965701L, 43 ); + map.put( 8536120340569832116L, 87 ); + map.put( 9134483648483594929L, 77 ); + map.put( 9132976039160654816L, 69 ); + map.remove( 7698175804504341415L ); + map.remove( 9134483648483594929L ); + map.put( 215721718639621876L, 11 ); + map.put( 8367455298026304238L, 78 ); + map.put( 215721718639621876L, 13 ); + map.put( 1398628381776162625L, 12 ); + map.put( 3818698536247649025L, 91 ); + map.put( 146020861698406718L, 41 ); + map.put( 39606137866137388L, 93 ); + map.put( 2032224502814063026L, 29 ); + map.remove( 6363504799104250810L ); + map.put( 7198198302699040275L, 75 ); + map.put( 1659665859871881503L, 35 ); + map.put( 2032224502814063026L, 25 ); + map.put( 7006780191094382053L, 2 ); + map.put( 2626850727701928459L, 97 ); + map.put( 5371963064889126677L, 49 ); + map.put( 2777831232791546183L, 35 ); + map.remove( 1265271287408386915L ); + map.remove( 1078791602714388223L ); + map.put( 7355915493826998767L, 39 ); + map.remove( 1557741259882614531L ); + map.put( 318456745029053198L, 18 ); + map.put( 5731549637584761783L, 77 ); + map.put( 875078333857781813L, 80 ); + map.remove( 4288489609244987651L ); + map.put( 6296247210943123044L, 67 ); + map.put( 6513548978704592547L, 60 ); + map.put( 7484688824700837146L, 79 ); + map.put( 4551026293109220157L, 77 ); + map.put( 2961669147182343860L, 80 ); + map.put( 4481942776688563562L, 28 ); + map.put( 5879809531485088687L, 63 ); + map.put( 5799223884087101214L, 94 ); + map.put( 8394473765965282856L, 59 ); + map.remove( 7273585073251585620L ); + map.remove( 5518575735665118270L ); + map.put( 1946691597339845823L, 64 ); + map.put( 1191724556568067952L, 33 ); + map.remove( 1803989601564179749L ); + map.put( 7909563548070411816L, 98 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 5826258075197365143L ); + Integer valueBefore = map.get( 5826258075197365143L ); + Integer previous = map.put( 5826258075197365143L, 6 ); + boolean existsAfter = map.containsKey( 5826258075197365143L ); + Integer valueAfter = map.get( 5826258075197365143L ); + int sizeAfter = map.size(); + assertEquals( "Size before put should have been 199", 199, sizeBefore ); + assertFalse( "5826258075197365143 should not exist before putting here", existedBefore ); + assertNull( "value before putting should be null", valueBefore ); + assertNull( "value returned from putting should be null", previous ); + assertTrue( "5826258075197365143 should exist", existsAfter ); + assertEquals( "value after putting should be 6", (Integer) 6, valueAfter ); + assertEquals( "Size after put should have been 200", 200, sizeAfter ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longIntEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongIntVisitor visitor = mock( PrimitiveLongIntVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longIntEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void intLongEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntLongMap map = Primitive.intLongMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntLongVisitor visitor = mock( PrimitiveIntLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void intLongEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntLongMap map = Primitive.intLongMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longLongEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongLongVisitor visitor; + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + visitor = mock( PrimitiveLongLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + } + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longLongEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longLongOffHeapEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongLongVisitor visitor; + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + visitor = mock( PrimitiveLongLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + } + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longLongOffHeapEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longObjectEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongObjectVisitor visitor = mock( PrimitiveLongObjectVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longObjectEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void intObjectEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntObjectVisitor visitor = mock( PrimitiveIntObjectVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void intObjectEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longIntKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longIntKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longLongKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + + // WHEN + map.visitKeys( visitor ); + } + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longLongKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longLongOffHeapKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + + // WHEN + map.visitKeys( visitor ); + } + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longLongOffHeapKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longObjectKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longObjectKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void intObjectKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntVisitor visitor = mock( PrimitiveIntVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void intObjectKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @Test + public void longObjectMapValuesContainsAllValues() + { + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, "a" ); + map.put( 2, "b" ); + map.put( 3, "c" ); + + assertThat( map.values(), containsInAnyOrder( "a", "b", "c" ) ); + } + + @Test + public void recursivePutGrowInterleavingShouldNotDropOriginalValues() + { + // List of values which causes calls to put() call grow(), which will call put() which calls grow() again + List lst = Arrays.asList( + 44988L, 44868L, 44271L, 44399L, 44502L, 44655L, 44348L, 44843L, + 44254L, 44774L, 44476L, 44664L, 44485L, 44237L, 44953L, 44468L, + 44970L, 44808L, 44527L, 44987L, 44672L, 44647L, 44467L, 44825L, + 44740L, 44220L, 44851L, 44902L, 44791L, 44416L, 44365L, 44382L, + 44885L, 44510L, 44553L, 44894L, 44288L, 44306L, 44450L, 44689L, + 44305L, 44374L, 44323L, 44493L, 44706L, 44681L, 44578L, 44723L, + 44331L, 44936L, 44289L, 44919L, 44433L, 44826L, 44757L, 44561L, + 44595L, 44612L, 44996L, 44646L, 44834L, 44314L, 44544L, 44629L, + 44357L // <-- this value will cause a grow, which during new table population will cause another grow. + ); + + verifyMapRetainsAllEntries( lst ); + } + + @Test + public void recursivePutGrowInterleavingShouldNotDropOriginalValuesEvenWhenFirstGrowAddsMoreValuesAfterSecondGrow() + { + // List of values that cause recursive growth like above, but this time the first grow wants to add more values + // to the table *after* the second grow has occurred. + List lst = Arrays.asList( + 85380L, 85124L, 85252L, 85259L, 85005L, 85260L, 85132L, 85141L, + 85397L, 85013L, 85269L, 85277L, 85149L, 85404L, 85022L, 85150L, + 85029L, 85414L, 85158L, 85286L, 85421L, 85039L, 85167L, 85294L, + 85166L, 85431L, 85303L, 85046L, 85311L, 85439L, 85438L, 85184L, + 85056L, 85063L, 85320L, 85448L, 85201L, 85073L, 85329L, 85456L, + 85328L, 85337L, 85081L, 85465L, 85080L, 85208L, 85473L, 85218L, + 85346L, 85090L, 85097L, 85225L, 85354L, 85098L, 85482L, 85235L, + 85363L, 85107L, 85490L, 85115L, 85499L, 85242L, 85175L, 85371L, + 85192L // <-- this value will cause a grow, which during new table population will cause another grow. + ); + + verifyMapRetainsAllEntries( lst ); + } + + private void verifyMapRetainsAllEntries( List lst ) + { + PrimitiveLongIntMap map = Primitive.longIntMap(); + Set set = new HashSet<>(); + for ( Long value: lst ) + { + assertThat( map.put( value, 1 ), is( -1 ) ); + assertTrue( set.add( value ) ); + } + + assertThat( map.size(), is( set.size() ) ); + for ( Long aLong: set ) + { + assertThat( map.get( aLong ), is( 1 ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java new file mode 100644 index 0000000000..93b00f6fa9 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PrimitiveLongObjectMapRIT +{ + @Test + public void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( mapFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + + fullVerification( result.getTarget(), random ); + } + } + + private void fullVerification( Maps target, Random random ) + { + for ( Map.Entry entry: target.normalMap.entrySet() ) + { + assertTrue( target.map.containsKey( entry.getKey() ) ); + assertEquals( entry.getValue(), target.map.get( entry.getKey() ) ); + } + + for ( int i = 0; i < target.normalMap.size(); i++ ) + { + assertFalse( target.map.containsKey( randomNonExisting( random, target.normalMap ) ) ); + } + } + + private Printable given() + { + return out -> out.println( PrimitiveLongObjectMap.class.getSimpleName() + " map = " + + Primitive.class.getSimpleName() + ".longObjectMap();" ); + } + + private ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private TargetFactory mapFactory() + { + return Maps::new; + } + + protected Action generateAction( Random random, Maps from ) + { + boolean anExisting = !from.normalMap.isEmpty() && random.nextInt( 3 ) == 0; + long key = anExisting ? + randomExisting( random, from.normalMap ) : + randomNonExisting( random, from.normalMap ); + Integer value = random.nextInt( 100 ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( key ); + } + + // add + return new AddAction( key, value ); + } + + private long randomNonExisting( Random random, Map existing ) + { + while ( true ) + { + long key = Math.abs( random.nextLong() ); + if ( !existing.containsKey( key ) ) + { + return key; + } + } + } + + private long randomExisting( Random random, Map existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.keySet().iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long key; + private final Integer value; + + AddAction( long key, Integer value ) + { + this.key = key; + this.value = value; + } + + @Override + public String apply( Maps target ) + { + Integer existingValue = target.normalMap.get( key ); + int actualSizeBefore = target.normalMap.size(); + + int sizeBefore = target.map.size(); + boolean existedBefore = target.map.containsKey( key ); + Integer valueBefore = target.map.get( key ); + Integer previous = target.map.put( key, value ); + boolean existsAfter = target.map.containsKey( key ); + Integer valueAfter = target.map.get( key ); + target.normalMap.put( key, value ); + int sizeAfter = target.map.size(); + + int actualSizeAfter = target.normalMap.size(); + boolean existing = existingValue != null; + boolean ok = + (sizeBefore == actualSizeBefore) & + (existedBefore == existing) & + (existing ? existingValue.equals( valueBefore ) : valueBefore == null) & + (existing ? previous.equals( existingValue ) : previous == null) & + (valueAfter != null && valueAfter.equals( value )) & + existsAfter & + (sizeAfter == actualSizeAfter); + return ok ? null : "" + key + ":" + value + "," + existingValue + "," + existedBefore + + "," + previous + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + Integer existingValue = source.normalMap.get( key ); + + String addition = "map.put( " + key + ", " + value + " );"; + if ( includeChecks ) + { + boolean existing = existingValue != null; + out.println( format( "int sizeBefore = map.size();" ) ); + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueBefore = map.get( %d );", key ) ); + out.println( format( "Integer previous = %s", addition ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueAfter = map.get( %d );", key ) ); + out.println( format( "int sizeAfter = map.size();" ) ); + + int actualSizeBefore = source.normalMap.size(); + out.println( format( "assertEquals( \"%s\", %d, sizeBefore );", + "Size before put should have been " + actualSizeBefore, actualSizeBefore ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + if ( existing ) + { + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, previous );", + "value returned from put should be " + existingValue, existingValue ) ); + } + else + { + out.println( format( "assertNull( \"%s\", valueBefore );", + "value before putting should be null" ) ); + out.println( format( "assertNull( \"%s\", previous );", + "value returned from putting should be null" ) ); + } + out.println( format( "assertTrue( \"%s\", existsAfter );", + key + " should exist" ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueAfter );", + "value after putting should be " + value, value ) ); + int actualSizeAfter = existing ? actualSizeBefore : actualSizeBefore + 1; + out.println( format( "assertEquals( \"%s\", %d, sizeAfter );", + "Size after put should have been " + actualSizeAfter, actualSizeAfter ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long key; + + RemoveAction( long key ) + { + this.key = key; + } + + @Override + public String apply( Maps target ) + { + Integer existingValue = target.normalMap.get( key ); + + boolean existedBefore = target.map.containsKey( key ); + Integer valueBefore = target.map.get( key ); + Integer removed = target.map.remove( key ); + boolean existsAfter = target.map.containsKey( key ); + Integer valueAfter = target.map.get( key ); + target.normalMap.remove( key ); + + boolean existing = existingValue != null; + boolean ok = + (existedBefore == existing) & + (existing ? valueBefore.equals( existingValue ) : valueBefore == null) & + (existing ? removed.equals( existingValue ) : removed == null) & + (valueAfter == null) & !existsAfter; + return ok ? null : "" + key + "," + existingValue + "," + existedBefore + + "," + removed + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + Integer existingValue = source.normalMap.get( key ); + + String removal = "map.remove( " + key + " );"; + if ( includeChecks ) + { + boolean existing = existingValue != null; + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueBefore = map.get( %d );", key ) ); + out.println( format( "Integer removed = %s", removal ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueAfter = map.get( %d );", key ) ); + + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + if ( existing ) + { + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, removed );", + "value returned from put should be " + existingValue, existingValue ) ); + } + else + { + out.println( format( "assertNull( \"%s\", valueBefore );", + "value before putting should be null" ) ); + out.println( format( "assertNull( \"%s\", removed );", + "value returned from putting should be null" ) ); + } + out.println( format( "assertFalse( \"%s\", existsAfter );", + key + " should not exist" ) ); + out.println( format( "assertNull( \"%s\", valueAfter );", + "value after removing should be null" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Maps implements TestResource + { + final Map normalMap = new HashMap<>(); + final PrimitiveLongObjectMap map = Primitive.longObjectMap(); + + @Override + public String toString() + { + return map.toString(); + } + + @Override + public void close() + { + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java new file mode 100644 index 0000000000..96c675844a --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Random; +import java.util.Set; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PrimitiveLongSetRIT +{ + @Test + public void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( setFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + fullVerification( result.getTarget(), random ); + } + } + + private void fullVerification( Sets target, Random random ) + { + for ( Long value: target.normalSet ) + { + assertTrue( target.set.contains( value ) ); + } + + for ( int i = 0; i < target.normalSet.size(); i++ ) + { + assertFalse( target.set.contains( randomNonExisting( random, target.normalSet ) ) ); + } + } + + private Printable given() + { + return out -> out.println( PrimitiveLongSet.class.getSimpleName() + " set = " + + Primitive.class.getSimpleName() + ".longSet();" ); + } + + private ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private TargetFactory setFactory() + { + return Sets::new; + } + + protected Action generateAction( Random random, Sets from ) + { + boolean anExisting = !from.normalSet.isEmpty() && random.nextInt( 3 ) == 0; + long value = anExisting ? + randomExisting( random, from.normalSet ) : + randomNonExisting( random, from.normalSet ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( value ); + } + + // add + return new AddAction( value ); + } + + private long randomNonExisting( Random random, Set existing ) + { + while ( true ) + { + long value = Math.abs( random.nextLong() ); + if ( !existing.contains( value ) ) + { + return value; + } + } + } + + private long randomExisting( Random random, Set existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long value; + + AddAction( long value ) + { + this.value = value; + } + + @Override + public String apply( Sets target ) + { + try + { + boolean alreadyExisting = target.normalSet.contains( value ); + + PrimitiveLongSet set = target.set; + boolean existedBefore = set.contains( value ); + boolean added = set.add( value ); + boolean existsAfter = set.contains( value ); + target.normalSet.add( value ); + + boolean ok = (existedBefore == alreadyExisting) & (added == !alreadyExisting) & existsAfter; + return ok ? null : "" + value + alreadyExisting + "," + existedBefore + "," + added + "," + existsAfter; + } + catch ( Exception e ) + { + return "exception:" + e.getMessage(); + } + } + + @Override + public void printAsCode( Sets source, LinePrinter out, boolean includeChecks ) + { + boolean alreadyExisting = source.normalSet.contains( value ); + String addition = "set.add( " + value + "L );"; + if ( includeChecks ) + { + out.println( format( "boolean existedBefore = set.contains( %dL );", value ) ); + out.println( format( "boolean added = %s", addition ) ); + out.println( format( "boolean existsAfter = set.contains( %dL );", value ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "exist before adding here" ) ); + out.println( format( "assert%s( \"%s\", added );", capitilize( !alreadyExisting ), + value + " should " + (!alreadyExisting ? "" : "not ") + "be reported as added here" ) ); + out.println( format( "assertTrue( \"%s\", existsAfter );", value + " should exist" ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long value; + + RemoveAction( long value ) + { + this.value = value; + } + + @Override + public String apply( Sets target ) + { + try + { + boolean alreadyExisting = target.normalSet.contains( value ); + PrimitiveLongSet set = target.set; + boolean existedBefore = set.contains( value ); + boolean removed = set.remove( value ); + boolean existsAfter = set.contains( value ); + target.normalSet.remove( value ); + + boolean ok = (existedBefore == alreadyExisting) & (removed == alreadyExisting) & !existsAfter; + return ok ? null : "" + value + alreadyExisting + "," + existedBefore + "," + removed + "," + existsAfter; + } + catch ( Exception e ) + { + return "exception: " + e.getMessage(); + } + } + + @Override + public void printAsCode( Sets source, LinePrinter out, boolean includeChecks ) + { + boolean alreadyExisting = source.normalSet.contains( value ); + String removal = "set.remove( " + value + "L );"; + if ( includeChecks ) + { + out.println( format( "boolean existedBefore = set.contains( %dL );", value ) ); + out.println( format( "boolean removed = %s", removal ) ); + out.println( format( "boolean existsAfter = set.contains( %dL );", value ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "exist before removing here" ) ); + out.println( format( "assert%s( \"%s\", removed );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "be reported as removed here" ) ); + out.println( format( "assertFalse( \"%s\", existsAfter );", + value + " should not exist" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Sets implements TestResource + { + final Set normalSet = new HashSet<>(); + final PrimitiveLongSet set = Primitive.longSet(); + + @Override + public void close() + { + set.close(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java new file mode 100644 index 0000000000..79d4d361d7 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java @@ -0,0 +1,441 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntSet; +import org.neo4j.collection.primitive.PrimitiveIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.collection.primitive.PrimitiveLongVisitor; +import org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.Monitor; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.neo4j.collection.primitive.Primitive.VALUE_MARKER; +import static org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.NO_MONITOR; + +public class PrimitiveLongSetTest +{ + private PrimitiveLongHashSet newSet( int h ) + { + return newSet( h, NO_MONITOR ); + } + + private PrimitiveLongHashSet newSet( int h, Monitor monitor ) + { + return new PrimitiveLongHashSet( + new LongKeyTable<>( h, VALUE_MARKER ), VALUE_MARKER, monitor ); + } + + @Test + public void shouldContainAddedValues_generated_1() + { + // GIVEN + PrimitiveLongSet set = newSet( 15 ); + Set expectedValues = new HashSet<>(); + long[] valuesToAdd = new long[]{ + 1207043189, + 380713862, + 1902858197, + 1996873101, + 1357024628, + 1044248801, + 1558157493, + 2040311008, + 2017660098, + 1332670047, + 663662790, + 2063747422, + 1554358949, + 1761477445, + 1141526838, + 1698679618, + 1279767067, + 508574, + 2071755904 + }; + for ( long key: valuesToAdd ) + { + set.add( key ); + expectedValues.add( key ); + } + + // WHEN/THEN + boolean existedBefore = set.contains( 679990875 ); + boolean added = set.add( 679990875 ); + boolean existsAfter = set.contains( 679990875 ); + assertFalse( "679990875 should not exist before adding here", existedBefore ); + assertTrue( "679990875 should be reported as added here", added ); + assertTrue( "679990875 should exist", existsAfter ); + expectedValues.add( 679990875L ); + + final Set visitedKeys = new HashSet<>(); + set.visitKeys( value -> + { + assertTrue( visitedKeys.add( value ) ); + return false; + } ); + assertEquals( expectedValues, visitedKeys ); + } + + @Test + public void shouldContainAddedValues_generated_6() + { + // GIVEN + PrimitiveLongSet set = newSet( 11 ); + set.add( 492321488 ); + set.add( 877087251 ); + set.add( 1809668113 ); + set.add( 1766034186 ); + set.add( 1879253467 ); + set.add( 669295491 ); + set.add( 176011165 ); + set.add( 1638959981 ); + set.add( 1093132636 ); + set.add( 6133241 ); + set.add( 486112773 ); + set.add( 205218385 ); + set.add( 1756491867 ); + set.add( 90390732 ); + set.add( 937266036 ); + set.add( 1269020584 ); + set.add( 521469166 ); + set.add( 1314928747 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 2095121629 ); + boolean added = set.add( 2095121629 ); + boolean existsAfter = set.contains( 2095121629 ); + assertFalse( "2095121629 should not exist before adding here", existedBefore ); + assertTrue( "2095121629 should be reported as added here", added ); + assertTrue( "2095121629 should exist", existsAfter ); + } + + @Test + public void shouldContainAddedValues_generated_4() + { + // GIVEN + PrimitiveLongSet set = newSet( 9 ); + set.add( 1934106304 ); + set.add( 783754072 ); + set.remove( 1934106304 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 783754072 ); + boolean added = set.add( 783754072 ); + boolean existsAfter = set.contains( 783754072 ); + assertTrue( "783754072 should exist before adding here", existedBefore ); + assertFalse( "783754072 should not be reported as added here", added ); + assertTrue( "783754072 should exist", existsAfter ); + } + + @Test + public void shouldOnlyContainAddedValues_generated_8() + { + // GIVEN + PrimitiveLongSet set = newSet( 7 ); + set.add( 375712513 ); + set.remove( 1507941820 ); + set.add( 671750317 ); + set.remove( 1054641019 ); + set.add( 671750317 ); + set.add( 1768202223 ); + set.add( 1768202223 ); + set.add( 1927780165 ); + set.add( 2139399764 ); + set.remove( 1243370828 ); + set.add( 1768202223 ); + set.add( 1335041891 ); + set.remove( 1578984313 ); + set.add( 1227954408 ); + set.remove( 946917826 ); + set.add( 1768202223 ); + set.add( 375712513 ); + set.add( 1668515054 ); + set.add( 401047579 ); + set.add( 33226244 ); + set.add( 126791689 ); + set.add( 401047579 ); + set.add( 1963437853 ); + set.add( 1739617766 ); + set.add( 671750317 ); + set.add( 401047579 ); + set.add( 789094467 ); + set.add( 1291421506 ); + set.add( 1694968582 ); + set.add( 1508353936 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 1739617766 ); + boolean added = set.add( 1739617766 ); + boolean existsAfter = set.contains( 1739617766 ); + assertTrue( "1739617766 should exist before adding here", existedBefore ); + assertFalse( "1739617766 should not be reported as added here", added ); + assertTrue( "1739617766 should exist", existsAfter ); + } + + @Test + public void shouldContainReallyBigLongValue() + { + // GIVEN + PrimitiveLongSet set = newSet( 10 ); + set.add( 7416509207113022571L ); + + // WHEN/THEN + boolean existedBefore = set.contains( 7620037383187366331L ); + boolean added = set.add( 7620037383187366331L ); + boolean existsAfter = set.contains( 7620037383187366331L ); + assertFalse( "7620037383187366331 should not exist before adding here", existedBefore ); + assertTrue( "7620037383187366331 should be reported as added here", added ); + assertTrue( "7620037383187366331 should exist", existsAfter ); + } + + @Test + public void shouldOnlyContainAddedValues() + { + // GIVEN + PrimitiveLongSet set = newSet( 13 ); + set.add( 52450040186687566L ); + set.add( 52450040186687566L ); + set.add( 5165002753277288833L ); + set.add( 4276883133717080762L ); + set.add( 5547940863757133161L ); + set.add( 8933830774911919116L ); + set.add( 3298254474623565974L ); + set.add( 3366017425691021883L ); + set.add( 8933830774911919116L ); + set.add( 2962608069916354604L ); + set.add( 3366017425691021883L ); + set.remove( 4008464697042048519L ); + set.add( 5547940863757133161L ); + set.add( 52450040186687566L ); + set.add( 4276883133717080762L ); + set.remove( 3298254474623565974L ); + set.remove( 180852386934131061L ); + set.add( 4835176885665539239L ); + set.add( 52450040186687566L ); + set.add( 4591251124405056753L ); + set.add( 5165002753277288833L ); + set.add( 8933830774911919116L ); + set.remove( 3458250832356869483L ); + set.add( 3038543946711308923L ); + set.add( 8743060827282266460L ); + set.add( 5771902951077476377L ); + set.add( 4591251124405056753L ); + set.add( 4835176885665539239L ); + set.remove( 4827343064671369647L ); + set.add( 1533535091190658734L ); + set.remove( 7125666881901305989L ); + set.add( 1533535091190658734L ); + set.add( 52450040186687566L ); + set.remove( 1333521853804287175L ); + set.add( 2962608069916354604L ); + set.add( 5914630622072544054L ); + set.add( 52450040186687566L ); + set.add( 8933830774911919116L ); + set.add( 6198968672674664718L ); + set.add( 6239021001199390909L ); + set.add( 6563452500080365738L ); + set.add( 6128819131542184648L ); + set.add( 5914630622072544054L ); + set.add( 7024933384543504364L ); + set.remove( 3949644814017615281L ); + set.add( 3459376060749741528L ); + set.add( 3201250389951283395L ); + set.add( 4463681497523421181L ); + set.add( 4304197328678536531L ); + set.remove( 4559066538220393098L ); + set.add( 2870119173652414003L ); + set.add( 4048902329274369372L ); + set.add( 3366017425691021883L ); + set.remove( 1092409052848583664L ); + set.add( 7024933384543504364L ); + set.add( 4276883133717080762L ); + set.add( 5914630622072544054L ); + set.add( 4048902329274369372L ); + set.add( 4304197328678536531L ); + set.add( 4151178923662618318L ); + set.remove( 51389524801735953L ); + set.add( 5371788772386487501L ); + set.remove( 8933830774911919116L ); + set.add( 4928410670964886834L ); + set.add( 8306393274966855450L ); + set.add( 2870119173652414003L ); + set.add( 8281622709908651825L ); + set.remove( 9194058056102544672L ); + set.remove( 5547940863757133161L ); + set.add( 9184590238993521817L ); + set.add( 5085293141623130492L ); + set.add( 5633993155928642090L ); + set.remove( 8794875254017117580L ); + set.add( 5894404415376700909L ); + set.add( 4835176885665539239L ); + set.remove( 8743060827282266460L ); + set.remove( 3460096065015553722L ); + set.remove( 3296380689310185627L ); + set.add( 337242488691685550L ); + set.add( 6239021001199390909L ); + set.add( 9104240733803011297L ); + set.add( 807326424150812437L ); + set.add( 3336115330297894183L ); + set.add( 1788796898879121715L ); + set.add( 5756965080438171769L ); + set.remove( 4366313798399763194L ); + set.add( 6198968672674664718L ); + set.add( 486897301084183614L ); + set.add( 2870119173652414003L ); + set.add( 5085293141623130492L ); + set.add( 5771902951077476377L ); + set.remove( 6563452500080365738L ); + set.add( 5347453991851285676L ); + set.add( 7437999035528158926L ); + set.add( 3223908005448803428L ); + set.add( 4300856565210203390L ); + set.remove( 4732570527126410147L ); + set.add( 2180591071166584277L ); + set.add( 5160374384234262648L ); + set.remove( 5165002753277288833L ); + set.add( 4463681497523421181L ); + set.add( 7360196143740041480L ); + set.add( 4928410670964886834L ); + set.add( 807326424150812437L ); + set.remove( 4069279832998820447L ); + set.remove( 337242488691685550L ); + set.add( 3201250389951283395L ); + set.add( 4012293068834101219L ); + set.add( 2333643358471038273L ); + set.add( 1158824602601458449L ); + set.remove( 3906518453155830597L ); + set.add( 7402912598585277900L ); + set.add( 6556025329057634951L ); + set.add( 6684709657047103197L ); + set.remove( 3448774195820272496L ); + set.add( 715736913341007544L ); + set.add( 9104240733803011297L ); + + // WHEN/THEN + boolean existedBefore = set.contains( 1103190229303827372L ); + boolean added = set.add( 1103190229303827372L ); + boolean existsAfter = set.contains( 1103190229303827372L ); + assertFalse( "1103190229303827372 should not exist before adding here", existedBefore ); + assertTrue( "1103190229303827372 should be reported as added here", added ); + assertTrue( "1103190229303827372 should exist", existsAfter ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void longVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongSet set = Primitive.longSet(); + set.add( 1 ); + set.add( 2 ); + set.add( 3 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + set.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void longVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntSet map = Primitive.intSet(); + map.add( 1 ); + map.add( 2 ); + map.add( 3 ); + map.add( 4 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + public void intVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntSet set = Primitive.intSet(); + set.add( 1 ); + set.add( 2 ); + set.add( 3 ); + PrimitiveIntVisitor visitor = mock( PrimitiveIntVisitor.class ); + + // WHEN + set.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + public void intVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntSet map = Primitive.intSet(); + map.add( 1 ); + map.add( 2 ); + map.add( 3 ); + map.add( 4 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @Test + public void shouldHandleEmptySet() + { + // GIVEN + PrimitiveLongSet set = Primitive.longSet( 0 ); + + // THEN + assertFalse( set.contains( 564 ) ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java new file mode 100644 index 0000000000..2a6c557357 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-9f3c602071ec41e7c8afa420abd07c09b47c14e4/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.test.randomized; + +import java.io.PrintStream; + +public class PrintStreamLinePrinter implements LinePrinter +{ + private final PrintStream out; + private final int indentation; + + public PrintStreamLinePrinter( PrintStream out ) + { + this( out, 0 ); + } + + public PrintStreamLinePrinter( PrintStream out, int indentation ) + { + this.out = out; + this.indentation = indentation; + } + + @Override + public void println( String line ) + { + for ( int i = 0; i < indentation; i++ ) + { + out.print( " " ); + } + out.println( line ); + } + + @Override + public LinePrinter indent() + { + return new PrintStreamLinePrinter( out, indentation + 1 ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.json b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.json new file mode 100644 index 0000000000..7548eb98fc --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29.json @@ -0,0 +1 @@ +{"parentCommitId":"9f3c602071ec41e7c8afa420abd07c09b47c14e4","currentCommitId":"b44c62bcdd6f7218bc97dae183ea0f6587bacd29","filesBefore":["community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java","community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArray.java","community/bolt/src/test/java/org/neo4j/bolt/v1/messaging/PrimitiveLongIntKeyValueArrayTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/DebugMonitor.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java","community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java"],"filesCurrent":["community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java","community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["community/bolt/src/main","community/bolt/src","community/bolt/src/main/java","community/bolt/src/main/java/org/neo4j/bolt/v1","community/legacy/src/test/java/org","community/bolt/src/test/java/org/neo4j/bolt/v1/messaging","community/bolt","community/legacy/src/test/java","community/bolt/src/main/java/org/neo4j/bolt/v1/messaging","community/bolt/src/main/java/org/neo4j/bolt","community/bolt/src/test/java/org/neo4j/bolt","community/bolt/src/main/java/org","community/bolt/src/test/java/org","community/legacy/src/test/java/org/neo4j/collection","community/legacy/src/test/java/org/neo4j/test","community/legacy/src/test","community/bolt/src/test/java","community/legacy/src","community/legacy/src/test/java/org/neo4j/test/randomized","community/legacy/src/test/java/org/neo4j/collection/primitive","community","community/bolt/src/main/java/org/neo4j","community/bolt/src/test","community/bolt/src/test/java/org/neo4j","community/legacy/src/test/java/org/neo4j","community/legacy","community/bolt/src/test/java/org/neo4j/bolt/v1","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch"],"repositoryDirectoriesCurrent":["community/legacy/src","community/bolt/src/main","community/bolt/src","community/bolt/src/main/java","community/bolt/src/main/java/org/neo4j/bolt/v1","community/legacy/src/test/java/org","community/legacy/src/test/java/org/neo4j/test/randomized","community/bolt","community/legacy/src/test/java","community/bolt/src/main/java/org/neo4j/bolt/v1/messaging","community/legacy/src/test/java/org/neo4j/collection/primitive","community/bolt/src/main/java/org/neo4j/bolt","community","community/bolt/src/main/java/org/neo4j","community/bolt/src/main/java/org","community/legacy","community/legacy/src/test/java/org/neo4j","community/legacy/src/test/java/org/neo4j/collection","community/legacy/src/test/java/org/neo4j/test","community/legacy/src/test","community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java new file mode 100644 index 0000000000..1376baeab6 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/bolt/src/main/java/org/neo4j/bolt/v1/messaging/Neo4jPackV1.java @@ -0,0 +1,605 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.bolt.v1.messaging; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetTime; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; + +import org.neo4j.bolt.messaging.BoltIOException; +import org.neo4j.bolt.messaging.Neo4jPack; +import org.neo4j.bolt.messaging.StructType; +import org.neo4j.bolt.v1.packstream.PackInput; +import org.neo4j.bolt.v1.packstream.PackOutput; +import org.neo4j.bolt.v1.packstream.PackStream; +import org.neo4j.bolt.v1.packstream.PackType; +import org.neo4j.collection.primitive.PrimitiveLongIntKeyValueArray; +import org.neo4j.kernel.api.exceptions.Status; +import org.neo4j.values.AnyValue; +import org.neo4j.values.AnyValueWriter; +import org.neo4j.values.storable.CoordinateReferenceSystem; +import org.neo4j.values.storable.TextArray; +import org.neo4j.values.storable.TextValue; +import org.neo4j.values.storable.Values; +import org.neo4j.values.virtual.ListValue; +import org.neo4j.values.virtual.MapValue; +import org.neo4j.values.virtual.MapValueBuilder; +import org.neo4j.values.virtual.NodeValue; +import org.neo4j.values.virtual.RelationshipValue; +import org.neo4j.values.virtual.VirtualValues; + +import static org.neo4j.bolt.v1.packstream.PackStream.UNKNOWN_SIZE; +import static org.neo4j.values.storable.Values.byteArray; + +/** + * Extended PackStream packer and unpacker classes for working + * with Neo4j-specific data types, represented as structures. + */ +public class Neo4jPackV1 implements Neo4jPack +{ + public static final long VERSION = 1; + + public static final byte NODE = 'N'; + public static final int NODE_SIZE = 3; + + public static final byte RELATIONSHIP = 'R'; + public static final int RELATIONSHIP_SIZE = 5; + + public static final byte UNBOUND_RELATIONSHIP = 'r'; + public static final int UNBOUND_RELATIONSHIP_SIZE = 3; + + public static final byte PATH = 'P'; + public static final int PATH_SIZE = 3; + + @Override + public Neo4jPack.Packer newPacker( PackOutput output ) + { + return new PackerV1( output ); + } + + @Override + public Neo4jPack.Unpacker newUnpacker( PackInput input ) + { + return new UnpackerV1( input ); + } + + @Override + public long version() + { + return VERSION; + } + + @Override + public String toString() + { + return getClass().getSimpleName(); + } + + protected static class PackerV1 extends PackStream.Packer implements AnyValueWriter, Neo4jPack.Packer + { + private static final int INITIAL_PATH_CAPACITY = 500; + private static final int NO_SUCH_ID = -1; + private final PrimitiveLongIntKeyValueArray nodeIndexes = + new PrimitiveLongIntKeyValueArray( INITIAL_PATH_CAPACITY + 1 ); + private final PrimitiveLongIntKeyValueArray relationshipIndexes = + new PrimitiveLongIntKeyValueArray( INITIAL_PATH_CAPACITY ); + + protected PackerV1( PackOutput output ) + { + super( output ); + } + + @Override + public void pack( AnyValue value ) throws IOException + { + value.writeTo( this ); + } + + @Override + public void writeNodeReference( long nodeId ) + { + throw new UnsupportedOperationException( "Cannot write a raw node reference" ); + } + + @Override + public void writeNode( long nodeId, TextArray labels, MapValue properties ) throws IOException + { + packStructHeader( NODE_SIZE, NODE ); + pack( nodeId ); + packListHeader( labels.length() ); + for ( int i = 0; i < labels.length(); i++ ) + { + labels.value( i ).writeTo( this ); + } + properties.writeTo( this ); + } + + @Override + public void writeRelationshipReference( long relationshipId ) + { + throw new UnsupportedOperationException( "Cannot write a raw relationship reference" ); + } + + @Override + public void writeRelationship( long relationshipId, long startNodeId, long endNodeId, TextValue type, MapValue properties ) + throws IOException + { + packStructHeader( RELATIONSHIP_SIZE, RELATIONSHIP ); + pack( relationshipId ); + pack( startNodeId ); + pack( endNodeId ); + type.writeTo( this ); + properties.writeTo( this ); + } + + @Override + public void beginMap( int size ) throws IOException + { + packMapHeader( size ); + } + + @Override + public void endMap() + { + //do nothing + } + + @Override + public void beginList( int size ) throws IOException + { + packListHeader( size ); + } + + @Override + public void endList() + { + //do nothing + } + + @Override + public void writePath( NodeValue[] nodes, RelationshipValue[] relationships ) throws IOException + { + //A path is serialized in the following form + // Given path: (a {id: 42})-[r1 {id: 10}]->(b {id: 43})<-[r1 {id: 11}]-(c {id: 44}) + //The serialization will look like: + // + // { + // [a, b, c] + // [r1, r2] + // [1, 1, -2, 2] + // } + // The first list contains all nodes where the first node (a) is guaranteed to be the start node of + // the path + // The second list contains all edges of the path + // The third list defines the path order, where every other item specifies the offset into the + // relationship and node list respectively. Since all paths is guaranteed to start with a 0, meaning + // that + // a is the start node in this case, those are excluded. So the first integer in the array refers to the + // position + // in the relationship array (1 indexed where sign denotes direction) and the second one refers to + // the offset + // into the + // node list (zero indexed) and so on. + packStructHeader( PATH_SIZE, PATH ); + + writeNodesForPath( nodes ); + writeRelationshipsForPath( relationships ); + + packListHeader( 2 * relationships.length ); + if ( relationships.length == 0 ) + { + return; + } + + NodeValue node = nodes[0]; + for ( int i = 1; i <= 2 * relationships.length; i++ ) + { + if ( i % 2 == 0 ) + { + node = nodes[i / 2]; + int index = nodeIndexes.getOrDefault( node.id(), NO_SUCH_ID ); + pack( index ); + } + else + { + RelationshipValue r = relationships[i / 2]; + int index = relationshipIndexes.getOrDefault( r.id(), NO_SUCH_ID ); + + if ( node.id() == r.startNode().id() ) + { + pack( index ); + } + else + { + pack( -index ); + } + } + + } + } + + private void writeNodesForPath( NodeValue[] nodes ) throws IOException + { + nodeIndexes.reset( nodes.length ); + for ( NodeValue node : nodes ) + { + nodeIndexes.putIfAbsent( node.id(), nodeIndexes.size() ); + } + + int size = nodeIndexes.size(); + packListHeader( size ); + if ( size > 0 ) + { + NodeValue node = nodes[0]; + for ( long id : nodeIndexes.keys() ) + { + int i = 1; + while ( node.id() != id ) + { + node = nodes[i++]; + } + node.writeTo( this ); + } + } + } + + private void writeRelationshipsForPath( RelationshipValue[] relationships ) throws IOException + { + relationshipIndexes.reset( relationships.length ); + for ( RelationshipValue node : relationships ) + { + // relationship indexes are one-based + relationshipIndexes.putIfAbsent( node.id(), relationshipIndexes.size() + 1 ); + } + + int size = relationshipIndexes.size(); + packListHeader( size ); + if ( size > 0 ) + { + { + RelationshipValue edge = relationships[0]; + for ( long id : relationshipIndexes.keys() ) + { + int i = 1; + while ( edge.id() != id ) + { + edge = relationships[i++]; + } + //Note that we are not doing relationship.writeTo(this) here since the serialization protocol + //requires these to be _unbound relationships_, thus relationships without any start node nor + // end node. + packStructHeader( UNBOUND_RELATIONSHIP_SIZE, UNBOUND_RELATIONSHIP ); + pack( edge.id() ); + edge.type().writeTo( this ); + edge.properties().writeTo( this ); + } + } + } + } + + @Override + public void writePoint( CoordinateReferenceSystem crs, double[] coordinate ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Point is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDuration( long months, long days, long seconds, int nanos ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Duration is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDate( LocalDate localDate ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Date is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeLocalTime( LocalTime localTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "LocalTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeTime( OffsetTime offsetTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "Time is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeLocalDateTime( LocalDateTime localDateTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "LocalDateTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeDateTime( ZonedDateTime zonedDateTime ) throws IOException + { + throw new BoltIOException( Status.Request.Invalid, "DateTime is not yet supported as a return type in Bolt" ); + } + + @Override + public void writeNull() throws IOException + { + packNull(); + } + + @Override + public void writeBoolean( boolean value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( byte value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( short value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( int value ) throws IOException + { + pack( value ); + } + + @Override + public void writeInteger( long value ) throws IOException + { + pack( value ); + } + + @Override + public void writeFloatingPoint( float value ) throws IOException + { + pack( value ); + } + + @Override + public void writeFloatingPoint( double value ) throws IOException + { + pack( value ); + } + + @Override + public void writeUTF8( byte[] bytes, int offset, int length ) throws IOException + { + packUTF8(bytes, offset, length); + } + + @Override + public void writeString( String value ) throws IOException + { + pack( value ); + } + + @Override + public void writeString( char value ) throws IOException + { + pack( value ); + } + + @Override + public void beginArray( int size, ArrayType arrayType ) throws IOException + { + switch ( arrayType ) + { + case BYTE: + packBytesHeader( size ); + break; + default: + packListHeader( size ); + } + + } + + @Override + public void endArray() + { + //Do nothing + } + + @Override + public void writeByteArray( byte[] value ) throws IOException + { + pack( value ); + } + } + + protected static class UnpackerV1 extends PackStream.Unpacker implements Neo4jPack.Unpacker + { + protected UnpackerV1( PackInput input ) + { + super( input ); + } + + @Override + public AnyValue unpack() throws IOException + { + PackType valType = peekNextType(); + switch ( valType ) + { + case BYTES: + return byteArray( unpackBytes() ); + case STRING: + return Values.utf8Value( unpackUTF8() ); + case INTEGER: + return Values.longValue( unpackLong() ); + case FLOAT: + return Values.doubleValue( unpackDouble() ); + case BOOLEAN: + return Values.booleanValue( unpackBoolean() ); + case NULL: + // still need to move past the null value + unpackNull(); + return Values.NO_VALUE; + case LIST: + { + return unpackList(); + } + case MAP: + { + return unpackMap(); + } + case STRUCT: + { + long size = unpackStructHeader(); + char signature = unpackStructSignature(); + return unpackStruct( signature, size ); + } + case END_OF_STREAM: + { + unpackEndOfStream(); + return null; + } + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Unknown value type: " + valType ); + } + } + + ListValue unpackList() throws IOException + { + int size = (int) unpackListHeader(); + if ( size == 0 ) + { + return VirtualValues.EMPTY_LIST; + } + else if ( size == UNKNOWN_SIZE ) + { + List list = new ArrayList<>(); + boolean more = true; + while ( more ) + { + PackType keyType = peekNextType(); + switch ( keyType ) + { + case END_OF_STREAM: + unpack(); + more = false; + break; + default: + list.add( unpack() ); + } + } + return VirtualValues.list( list.toArray( new AnyValue[0] ) ); + } + else + { + AnyValue[] values = new AnyValue[size]; + for ( int i = 0; i < size; i++ ) + { + values[i] = unpack(); + } + return VirtualValues.list( values ); + } + } + + protected AnyValue unpackStruct( char signature, long size ) throws IOException + { + StructType structType = StructType.valueOf( signature ); + if ( structType == null ) + { + throw new BoltIOException( Status.Request.InvalidFormat, + String.format( "Struct types of 0x%s are not recognized.", Integer.toHexString( signature ) ) ); + } + + throw new BoltIOException( Status.Statement.TypeError, + String.format( "%s values cannot be unpacked with this version of bolt.", structType.description() ) ); + } + + @Override + public MapValue unpackMap() throws IOException + { + int size = (int) unpackMapHeader(); + if ( size == 0 ) + { + return VirtualValues.EMPTY_MAP; + } + MapValueBuilder map; + if ( size == UNKNOWN_SIZE ) + { + map = new MapValueBuilder( ); + boolean more = true; + while ( more ) + { + PackType keyType = peekNextType(); + String key; + AnyValue val; + switch ( keyType ) + { + case END_OF_STREAM: + unpack(); + more = false; + break; + case STRING: + key = unpackString(); + val = unpack(); + if ( map.add( key, val ) != null ) + { + throw new BoltIOException( Status.Request.Invalid, "Duplicate map key `" + key + "`." ); + } + break; + case NULL: + throw new BoltIOException( Status.Request.Invalid, "Value `null` is not supported as key in maps, must be a non-nullable string." ); + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Bad key type: " + keyType ); + } + } + } + else + { + map = new MapValueBuilder( size ); + for ( int i = 0; i < size; i++ ) + { + PackType keyType = peekNextType(); + String key; + switch ( keyType ) + { + case NULL: + throw new BoltIOException( Status.Request.Invalid, "Value `null` is not supported as key in maps, must be a non-nullable string." ); + case STRING: + key = unpackString(); + break; + default: + throw new BoltIOException( Status.Request.InvalidFormat, "Bad key type: " + keyType ); + } + + AnyValue val = unpack(); + if ( map.add( key, val ) != null ) + { + throw new BoltIOException( Status.Request.Invalid, "Duplicate map key `" + key + "`." ); + } + } + } + return map.build(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java new file mode 100644 index 0000000000..0910abcdec --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveArraysTest.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +class PrimitiveArraysTest +{ + private static final int[] NO_INTS = new int[0]; + private static final int[] ONE_INT = new int[]{1}; + private static final long[] NO_LONGS = new long[0]; + private static final long[] ONE_LONG = new long[]{1}; + + // union() null checks. Actual behaviour is tested in PrimitiveSortedArraySetUnionTest + + @Test + void union_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.union( null, null ), nullValue() ); + assertThat( PrimitiveArrays.union( null, NO_INTS ), equalTo( NO_INTS ) ); + assertThat( PrimitiveArrays.union( NO_INTS, null ), equalTo( NO_INTS ) ); + assertThat( PrimitiveArrays.union( null, ONE_INT ), equalTo( ONE_INT ) ); + assertThat( PrimitiveArrays.union( ONE_INT, null ), equalTo( ONE_INT ) ); + } + + // intersect() + + @Test + void intersect_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.intersect( null, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( null, NO_LONGS ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( NO_LONGS, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( null, ONE_LONG ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.intersect( ONE_LONG, null ), equalTo( NO_LONGS ) ); + } + + @Test + void intersect_shouldHandleNonIntersectingArrays() + { + assertThat( PrimitiveArrays.intersect( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + equalTo( NO_LONGS ) ); + + assertThat( PrimitiveArrays.intersect( new long[]{14, 15, 16}, new long[]{1, 2, 3} ), + equalTo( NO_LONGS ) ); + } + + @Test + void intersect_shouldHandleIntersectingArrays() + { + assertThat( PrimitiveArrays.intersect( new long[]{1, 2, 3}, new long[]{3, 4, 5} ), + isArray( 3 ) ); + + assertThat( PrimitiveArrays.intersect( new long[]{3, 4, 5}, new long[]{1, 2, 3, 4} ), + isArray( 3, 4 ) ); + } + + @Test + void intersect_shouldHandleComplexIntersectingArraysWithGaps() + { + assertThat( + PrimitiveArrays.intersect( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isArray( 4, 9, 12 ) ); + assertThat( + PrimitiveArrays.intersect( new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19}, new long[]{4, 6, 9, 11, 12, 15} ), + isArray( 4, 9, 12 ) ); + } + + // symmetricDifference() + + @Test + void symDiff_shouldHandleNullInput() + { + assertThat( PrimitiveArrays.symmetricDifference( null, null ), equalTo( null ) ); + assertThat( PrimitiveArrays.symmetricDifference( null, NO_LONGS ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.symmetricDifference( NO_LONGS, null ), equalTo( NO_LONGS ) ); + assertThat( PrimitiveArrays.symmetricDifference( null, ONE_LONG ), equalTo( ONE_LONG ) ); + assertThat( PrimitiveArrays.symmetricDifference( ONE_LONG, null ), equalTo( ONE_LONG ) ); + } + + @Test + void symDiff_shouldHandleNonIntersectingArrays() + { + assertThat( PrimitiveArrays.symmetricDifference( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + isArray( 1, 2, 3, 4, 5, 6 ) ); + + assertThat( PrimitiveArrays.symmetricDifference( new long[]{14, 15, 16}, new long[]{1, 2, 3} ), + isArray( 1, 2, 3, 14, 15, 16 ) ); + } + + @Test + void symDiff_shouldHandleIntersectingArrays() + { + assertThat( PrimitiveArrays.symmetricDifference( new long[]{1, 2, 3}, new long[]{3, 4, 5} ), + isArray( 1, 2, 4, 5 ) ); + + assertThat( PrimitiveArrays.symmetricDifference( new long[]{3, 4, 5}, new long[]{1, 2, 3, 4} ), + isArray( 1, 2, 5 ) ); + } + + @Test + void symDiff_shouldHandleComplexIntersectingArraysWithGaps() + { + assertThat( + PrimitiveArrays + .symmetricDifference( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isArray( 2, 3, 6, 7, 8, 11, 15, 16, 19 ) ); + assertThat( + PrimitiveArrays + .symmetricDifference( new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19}, new long[]{4, 6, 9, 11, 12, 15} ), + isArray( 2, 3, 6, 7, 8, 11, 15, 16, 19 ) ); + } + + // count unique + + @Test + void shouldCountUnique() + { + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{4, 5, 6} ), + isIntPair( 3, 3 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{3, 6} ), + isIntPair( 2, 1 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{1, 2, 3}, new long[]{3} ), + isIntPair( 2, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3}, new long[]{1, 2, 3} ), + isIntPair( 0, 2 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3}, new long[]{3} ), + isIntPair( 0, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{3, 6, 8}, new long[]{} ), + isIntPair( 3, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{}, new long[]{3, 6, 8} ), + isIntPair( 0, 3 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{}, new long[]{} ), + isIntPair( 0, 0 ) ); + + assertThat( + PrimitiveArrays.countUnique( new long[]{4, 6, 9, 11, 12, 15}, new long[]{2, 3, 4, 7, 8, 9, 12, 16, 19} ), + isIntPair( 3, 6 ) ); + } + + // helpers + + private static Matcher isIntPair( int left, int right ) + { + return new BaseMatcher() + { + @Override + public void describeTo( Description description ) + { + description.appendValue( left ); + description.appendValue( right ); + } + + @Override + public boolean matches( Object o ) + { + return o instanceof Long && ((Long) o) == (((long) left << 32) | right); + } + }; + } + + private static Matcher isArray( long... values ) + { + return equalTo( values ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java new file mode 100644 index 0000000000..648f262ee8 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveCollectionsAllocationsTest.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import org.neo4j.memory.LocalMemoryTracker; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveCollectionsAllocationsTest +{ + + @Test + void trackPrimitiveMemoryAllocations() + { + LocalMemoryTracker memoryTracker = new LocalMemoryTracker(); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( memoryTracker ); + assertTrue( memoryTracker.usedDirectMemory() > 0 ); + + offHeapIntSet.close(); + assertEquals( 0, memoryTracker.usedDirectMemory() ); + } + + @Test + void trackPrimitiveMemoryOnResize() + { + LocalMemoryTracker memoryTracker = new LocalMemoryTracker(); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( memoryTracker ); + long originalSetMemory = memoryTracker.usedDirectMemory(); + + for ( int i = 0; i < Primitive.DEFAULT_OFFHEAP_CAPACITY + 1; i++ ) + { + offHeapIntSet.add( i ); + } + + assertTrue( memoryTracker.usedDirectMemory() > originalSetMemory ); + + offHeapIntSet.close(); + assertEquals( 0, memoryTracker.usedDirectMemory() ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java new file mode 100644 index 0000000000..9ba777314f --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntCollectionsTest.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.memory.GlobalMemoryTracker; + +import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveIntCollectionsTest +{ + @Test + void arrayOfItemsAsIterator() + { + // GIVEN + int[] items = new int[]{2, 5, 234}; + + // WHEN + PrimitiveIntIterator iterator = PrimitiveIntCollections.iterator( items ); + + // THEN + assertItems( iterator, items ); + } + + @Test + void convertCollectionToLongArray() + { + PrimitiveIntSet heapSet = PrimitiveIntCollections.asSet( new int[]{1, 2, 3} ); + PrimitiveIntSet offHeapIntSet = Primitive.offHeapIntSet( GlobalMemoryTracker.INSTANCE ); + offHeapIntSet.add( 7 ); + offHeapIntSet.add( 8 ); + assertArrayEquals( new long[]{1, 2, 3}, PrimitiveIntCollections.asLongArray( heapSet ) ); + assertArrayEquals( new long[]{7, 8}, PrimitiveIntCollections.asLongArray( offHeapIntSet ) ); + } + + @Test + void concatenateTwoIterators() + { + // GIVEN + PrimitiveIntIterator firstItems = PrimitiveIntCollections.iterator( 10, 3, 203, 32 ); + PrimitiveIntIterator otherItems = PrimitiveIntCollections.iterator( 1, 2, 5 ); + + // WHEN + PrimitiveIntIterator iterator = PrimitiveIntCollections.concat( asList( firstItems, otherItems ).iterator() ); + + // THEN + assertItems( iterator, 10, 3, 203, 32, 1, 2, 5 ); + } + + @Test + void filter() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveIntIterator filtered = PrimitiveIntCollections.filter( items, item -> item != 2 ); + + // THEN + assertItems( filtered, 1, 3 ); + } + + @Test + void deduplicate() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 1, 2, 3, 2 ); + + // WHEN + PrimitiveIntIterator deduped = PrimitiveIntCollections.deduplicate( items ); + + // THEN + assertItems( deduped, 1, 2, 3 ); + } + + private static final class CountingPrimitiveIntIteratorResource implements PrimitiveIntIterator, AutoCloseable + { + private final PrimitiveIntIterator delegate; + private final AtomicInteger closeCounter; + + private CountingPrimitiveIntIteratorResource( PrimitiveIntIterator delegate, AtomicInteger closeCounter ) + { + this.delegate = delegate; + this.closeCounter = closeCounter; + } + + @Override + public void close() + { + closeCounter.incrementAndGet(); + } + + @Override + public boolean hasNext() + { + return delegate.hasNext(); + } + + @Override + public int next() + { + return delegate.next(); + } + } + + @Test + void iteratorAsSet() + { + // GIVEN + PrimitiveIntIterator items = PrimitiveIntCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveIntSet set = PrimitiveIntCollections.asSet( items ); + + // THEN + assertTrue( set.contains( 1 ) ); + assertTrue( set.contains( 2 ) ); + assertTrue( set.contains( 3 ) ); + assertFalse( set.contains( 4 ) ); + assertThrows( IllegalStateException.class, () -> PrimitiveIntCollections.asSet( PrimitiveIntCollections.iterator( 1, 2, 1 ) ) ); + } + + @Test + void shouldNotContinueToCallNextOnHasNextFalse() + { + // GIVEN + AtomicInteger count = new AtomicInteger( 2 ); + PrimitiveIntIterator iterator = new PrimitiveIntCollections.PrimitiveIntBaseIterator() + { + @Override + protected boolean fetchNext() + { + return count.decrementAndGet() >= 0 && next( count.get() ); + } + }; + + // WHEN/THEN + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 1L, iterator.next() ); + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 0L, iterator.next() ); + assertFalse( iterator.hasNext() ); + assertFalse( iterator.hasNext() ); + assertEquals( -1L, count.get() ); + } + + @Test + void shouldDeduplicate() + { + // GIVEN + int[] array = new int[]{1, 6, 2, 5, 6, 1, 6}; + + // WHEN + int[] deduped = PrimitiveIntCollections.deduplicate( array ); + + // THEN + assertArrayEquals( new int[]{1, 6, 2, 5}, deduped ); + } + + @Test + void copyMap() + { + PrimitiveIntObjectMap originalMap = Primitive.intObjectMap(); + originalMap.put( 1, "a" ); + originalMap.put( 2, "b" ); + originalMap.put( 3, "c" ); + PrimitiveIntObjectMap copyMap = PrimitiveIntCollections.copy( originalMap ); + assertNotSame( originalMap, copyMap ); + assertEquals( 3, copyMap.size() ); + assertEquals( "a", copyMap.get( 1 ) ); + assertEquals( "b", copyMap.get( 2 ) ); + assertEquals( "c", copyMap.get( 3 ) ); + } + + private static void assertNoMoreItems( PrimitiveIntIterator iterator ) + { + assertFalse( iterator.hasNext(), iterator + " should have no more items" ); + assertThrows( NoSuchElementException.class, iterator::next ); + } + + private static void assertNextEquals( long expected, PrimitiveIntIterator iterator ) + { + assertTrue( iterator.hasNext(), iterator + " should have had more items" ); + assertEquals( expected, iterator.next() ); + } + + private static void assertItems( PrimitiveIntIterator iterator, int... expectedItems ) + { + for ( long expectedItem: expectedItems ) + { + assertNextEquals( expectedItem, iterator ); + } + assertNoMoreItems( iterator ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java new file mode 100644 index 0000000000..30afe44a0d --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveIntStackTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveIntStackTest +{ + @Test + void shouldPushAndPollSomeEntities() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack( 6 ); + + // WHEN/THEN + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + + stack.push( 123 ); + assertFalse( stack.isEmpty() ); + + stack.push( 456 ); + assertFalse( stack.isEmpty() ); + assertEquals( 456, stack.poll() ); + + assertFalse( stack.isEmpty() ); + assertEquals( 123, stack.poll() ); + + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + void shouldGrowArray() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack( 5 ); + + // WHEN + for ( int i = 0; i <= 7; i++ ) + { + stack.push( i ); + } + + // THEN + for ( int i = 7; i >= 0; i-- ) + { + assertFalse( stack.isEmpty() ); + assertEquals( i, stack.poll() ); + } + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + void shouldIterate() + { + // GIVEN + PrimitiveIntStack stack = new PrimitiveIntStack(); + + // WHEN + for ( int i = 0; i < 7; i++ ) + { + stack.push( i ); + } + + // THEN + PrimitiveIntIterator iterator = stack.iterator(); + int i = 0; + while ( iterator.hasNext() ) + { + assertEquals( i++, iterator.next() ); + } + assertEquals( 7, i ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java new file mode 100644 index 0000000000..931cfbfe16 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongArrayQueueTest.java @@ -0,0 +1,217 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import java.util.NoSuchElementException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveLongArrayQueueTest +{ + + @Test + void newQueueIsEmpty() + { + assertTrue( createQueue().isEmpty() ); + } + + @Test + void growQueueOnElementOffer() + { + PrimitiveLongArrayQueue longArrayQueue = createQueue(); + for ( int i = 1; i < 1000; i++ ) + { + longArrayQueue.enqueue( i ); + assertEquals( i, longArrayQueue.size() ); + } + } + + @Test + void addRemoveElementKeepQueueEmpty() + { + PrimitiveLongArrayQueue longArrayQueue = createQueue(); + for ( int i = 0; i < 1000; i++ ) + { + longArrayQueue.enqueue( i ); + assertEquals( i, longArrayQueue.dequeue() ); + assertTrue( longArrayQueue.isEmpty() ); + } + } + + @Test + void offerLessThenQueueCapacityElements() + { + PrimitiveLongArrayQueue arrayQueue = createQueue(); + for ( int i = 1; i < 16; i++ ) + { + arrayQueue.enqueue( i ); + assertEquals( i, arrayQueue.size() ); + } + } + + @Test + void failToRemoveElementFromNewEmptyQueue() + { + assertThrows( IllegalStateException.class, () -> createQueue().dequeue() ); + } + + @Test + void offerMoreThenQueueCapacityElements() + { + PrimitiveLongArrayQueue arrayQueue = createQueue(); + for ( int i = 1; i < 1234; i++ ) + { + arrayQueue.enqueue( i ); + } + int currentValue = 1; + while ( !arrayQueue.isEmpty() ) + { + assertEquals( currentValue++, arrayQueue.dequeue() ); + } + } + + @Test + void emptyQueueAfterClear() + { + PrimitiveLongArrayQueue queue = createQueue(); + queue.enqueue( 2 ); + queue.enqueue( 3 ); + assertFalse( queue.isEmpty() ); + assertEquals( 2, queue.size() ); + + queue.clear(); + + assertTrue( queue.isEmpty() ); + } + + @Test + void tailBeforeHeadCorrectSize() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 24; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 14, queue.size() ); + } + + @Test + void tailBeforeHeadCorrectResize() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 34; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 24, queue.size() ); + for ( int j = 10; j < 34; j++ ) + { + assertEquals( j, queue.dequeue() ); + } + } + + @Test + void tailBeforeHeadCorrectIteration() + { + PrimitiveLongArrayQueue queue = createQueue(); + for ( int i = 0; i < 14; i++ ) + { + queue.enqueue( i ); + } + for ( int i = 0; i < 10; i++ ) + { + assertEquals( i, queue.dequeue() ); + } + for ( int i = 14; i < 24; i++ ) + { + queue.enqueue( i ); + } + + assertEquals( 14, queue.size() ); + PrimitiveLongIterator iterator = queue.iterator(); + for ( int j = 10; j < 24; j++ ) + { + assertTrue( iterator.hasNext() ); + assertEquals( j, iterator.next() ); + } + assertFalse( iterator.hasNext() ); + } + + @Test + void failToGetNextOnEmptyQueueIterator() + { + assertThrows( NoSuchElementException.class, () -> createQueue().iterator().next() ); + } + + @Test + void addAllElementsFromOtherQueue() + { + PrimitiveLongArrayQueue queue = createQueue(); + queue.enqueue( 1 ); + queue.enqueue( 2 ); + PrimitiveLongArrayQueue otherQueue = createQueue(); + otherQueue.enqueue( 3 ); + otherQueue.enqueue( 4 ); + queue.addAll( otherQueue ); + + assertTrue( otherQueue.isEmpty() ); + assertEquals( 0, otherQueue.size() ); + assertEquals( 4, queue.size() ); + for ( int value = 1; value <= 4; value++ ) + { + assertEquals( value, queue.dequeue() ); + } + assertTrue( queue.isEmpty() ); + } + + @Test + void doNotAllowCreationOfQueueWithRandomCapacity() + { + assertThrows( AssertionError.class, () -> new PrimitiveLongArrayQueue( 7 ) ); + } + + private static PrimitiveLongArrayQueue createQueue() + { + return new PrimitiveLongArrayQueue(); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java new file mode 100644 index 0000000000..e95a589baa --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongCollectionsTest.java @@ -0,0 +1,282 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.neo4j.collection.primitive.PrimitiveLongCollections.PrimitiveLongBaseIterator; + +import static java.util.Arrays.asList; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveLongCollectionsTest +{ + @Test + void arrayOfItemsAsIterator() + { + // GIVEN + long[] items = new long[]{2, 5, 234}; + + // WHEN + PrimitiveLongIterator iterator = PrimitiveLongCollections.iterator( items ); + + // THEN + assertItems( iterator, items ); + } + + @Test + void filter() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveLongIterator filtered = PrimitiveLongCollections.filter( items, item -> item != 2 ); + + // THEN + assertItems( filtered, 1, 3 ); + } + + private static final class CountingPrimitiveLongIteratorResource implements PrimitiveLongIterator, AutoCloseable + { + private final PrimitiveLongIterator delegate; + private final AtomicInteger closeCounter; + + private CountingPrimitiveLongIteratorResource( PrimitiveLongIterator delegate, AtomicInteger closeCounter ) + { + this.delegate = delegate; + this.closeCounter = closeCounter; + } + + @Override + public void close() + { + closeCounter.incrementAndGet(); + } + + @Override + public boolean hasNext() + { + return delegate.hasNext(); + } + + @Override + public long next() + { + return delegate.next(); + } + } + + @Test + void singleWithDefaultMustAutoCloseIterator() + { + AtomicInteger counter = new AtomicInteger(); + CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource( + PrimitiveLongCollections.iterator( 13 ), counter ); + assertEquals( PrimitiveLongCollections.single( itr, 2 ), 13 ); + assertEquals( 1, counter.get() ); + } + + @Test + void singleWithDefaultMustAutoCloseEmptyIterator() + { + AtomicInteger counter = new AtomicInteger(); + CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource( + PrimitiveLongCollections.emptyIterator(), counter ); + assertEquals( PrimitiveLongCollections.single( itr, 2 ), 2 ); + assertEquals( 1, counter.get() ); + } + + @Test + void indexOf() + { + // GIVEN + PrimitiveLongIterable items = () -> PrimitiveLongCollections.iterator( 10, 20, 30 ); + + // THEN + assertEquals( -1, PrimitiveLongCollections.indexOf( items.iterator(), 55 ) ); + assertEquals( 0, PrimitiveLongCollections.indexOf( items.iterator(), 10 ) ); + assertEquals( 1, PrimitiveLongCollections.indexOf( items.iterator(), 20 ) ); + assertEquals( 2, PrimitiveLongCollections.indexOf( items.iterator(), 30 ) ); + } + + @Test + void iteratorAsSet() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + PrimitiveLongSet set = PrimitiveLongCollections.asSet( items ); + + // THEN + assertTrue( set.contains( 1 ) ); + assertTrue( set.contains( 2 ) ); + assertTrue( set.contains( 3 ) ); + assertFalse( set.contains( 4 ) ); + } + + @Test + void count() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + int count = PrimitiveLongCollections.count( items ); + + // THEN + assertEquals( 3, count ); + } + + @Test + void asArray() + { + // GIVEN + PrimitiveLongIterator items = PrimitiveLongCollections.iterator( 1, 2, 3 ); + + // WHEN + long[] array = PrimitiveLongCollections.asArray( items ); + + // THEN + assertTrue( Arrays.equals( new long[]{1, 2, 3}, array ) ); + } + + @Test + void shouldDeduplicate() + { + // GIVEN + long[] array = new long[]{1L, 1L, 2L, 5L, 6L, 6L}; + + // WHEN + long[] deduped = PrimitiveLongCollections.deduplicate( array ); + + // THEN + assertArrayEquals( new long[]{1L, 2L, 5L, 6L}, deduped ); + } + + @Test + void shouldNotContinueToCallNextOnHasNextFalse() + { + // GIVEN + AtomicLong count = new AtomicLong( 2 ); + PrimitiveLongIterator iterator = new PrimitiveLongBaseIterator() + { + @Override + protected boolean fetchNext() + { + return count.decrementAndGet() >= 0 && next( count.get() ); + } + }; + + // WHEN/THEN + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 1L, iterator.next() ); + assertTrue( iterator.hasNext() ); + assertTrue( iterator.hasNext() ); + assertEquals( 0L, iterator.next() ); + assertFalse( iterator.hasNext() ); + assertFalse( iterator.hasNext() ); + assertEquals( -1L, count.get() ); + } + + @Test + void copyPrimitiveSet() + { + PrimitiveLongSet longSet = PrimitiveLongCollections.setOf( 1L, 3L, 5L ); + PrimitiveLongSet copySet = PrimitiveLongCollections.asSet( longSet ); + assertNotSame( copySet, longSet ); + + assertTrue( copySet.contains( 1L ) ); + assertTrue( copySet.contains( 3L ) ); + assertTrue( copySet.contains( 5L ) ); + assertEquals( 3, copySet.size() ); + } + + @Test + void convertJavaCollectionToSetOfPrimitives() + { + List longs = asList( 1L, 4L, 7L ); + PrimitiveLongSet longSet = PrimitiveLongCollections.asSet( longs ); + assertTrue( longSet.contains( 1L ) ); + assertTrue( longSet.contains( 4L ) ); + assertTrue( longSet.contains( 7L ) ); + assertEquals( 3, longSet.size() ); + } + + @Test + void convertPrimitiveSetToJavaSet() + { + PrimitiveLongSet longSet = PrimitiveLongCollections.setOf( 1L, 3L, 5L ); + Set longs = PrimitiveLongCollections.toSet( longSet ); + assertThat( longs, containsInAnyOrder( 1L, 3L, 5L ) ); + } + + @Test + void copyMap() + { + PrimitiveLongObjectMap originalMap = Primitive.longObjectMap(); + originalMap.put( 1L, "a" ); + originalMap.put( 2L, "b" ); + originalMap.put( 3L, "c" ); + PrimitiveLongObjectMap copyMap = PrimitiveLongCollections.copy( originalMap ); + assertNotSame( originalMap, copyMap ); + assertEquals( 3, copyMap.size() ); + assertEquals( "a", copyMap.get( 1L ) ); + assertEquals( "b", copyMap.get( 2L ) ); + assertEquals( "c", copyMap.get( 3L ) ); + } + + private static void assertNoMoreItems( PrimitiveLongIterator iterator ) + { + assertFalse( iterator.hasNext(), iterator + " should have no more items" ); + assertThrows( NoSuchElementException.class, iterator::next ); + } + + private static void assertNextEquals( long expected, PrimitiveLongIterator iterator ) + { + assertTrue( iterator.hasNext(), iterator + " should have had more items" ); + assertEquals( expected, iterator.next() ); + } + + private static void assertItems( PrimitiveLongIterator iterator, long... expectedItems ) + { + for ( long expectedItem: expectedItems ) + { + assertNextEquals( expectedItem, iterator ); + } + assertNoMoreItems( iterator ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java new file mode 100644 index 0000000000..56a87741d8 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongIntKeyValueArrayTest.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; + +class PrimitiveLongIntKeyValueArrayTest +{ + private static final int DEFAULT_VALUE = -1; + + @Test + void testEnsureCapacity() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.capacity(), equalTo( PrimitiveLongIntKeyValueArray.DEFAULT_INITIAL_CAPACITY ) ); + + map.ensureCapacity( 10 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 10 ) ); + + map.ensureCapacity( 100 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 100 ) ); + + map.ensureCapacity( 1000 ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + } + + @Test + void testSize() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + assertThat( map.size(), equalTo( 0 ) ); + + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + assertThat( map.size(), equalTo( 3 ) ); + } + + @Test + void testGetOrDefault() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + assertThat( map.getOrDefault( 1, DEFAULT_VALUE ), equalTo( 100 ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( DEFAULT_VALUE ) ); + } + + @Test + void testPutIfAbsent() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + + assertThat( map.putIfAbsent( 1, 100 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 2, 200 ), equalTo( true ) ); + assertThat( map.putIfAbsent( 3, 300 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 3 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3} ) ); + + assertThat( map.putIfAbsent( 2, 2000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 3, 3000 ), equalTo( false ) ); + assertThat( map.putIfAbsent( 4, 4000 ), equalTo( true ) ); + assertThat( map.size(), equalTo( 4 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 4} ) ); + assertThat( map.getOrDefault( 2, DEFAULT_VALUE ), equalTo( 200 ) ); + assertThat( map.getOrDefault( 3, DEFAULT_VALUE ), equalTo( 300 ) ); + assertThat( map.getOrDefault( 4, DEFAULT_VALUE ), equalTo( 4000 ) ); + } + + @Test + void testReset() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + + map.reset( 1000 ); + assertThat( map.size(), equalTo( 0 ) ); + assertThat( map.capacity(), greaterThanOrEqualTo( 1000 ) ); + } + + @Test + void testKeys() + { + PrimitiveLongIntKeyValueArray map = new PrimitiveLongIntKeyValueArray(); + map.putIfAbsent( 1, 100 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 2, 200 ); + map.putIfAbsent( 3, 300 ); + map.putIfAbsent( 8, 800 ); + map.putIfAbsent( 7, 700 ); + map.putIfAbsent( 6, 600 ); + map.putIfAbsent( 5, 500 ); + + assertThat( map.size(), equalTo( 7 ) ); + assertThat( map.keys(), equalTo( new long[]{1, 2, 3, 8, 7, 6, 5} ) ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java new file mode 100644 index 0000000000..305a785e86 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongListTest.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveLongListTest +{ + + @Test + void newListIsEmpty() + { + assertTrue( new PrimitiveLongList().isEmpty() ); + assertTrue( new PrimitiveLongList( 12 ).isEmpty() ); + } + + @Test + void newListHasZeroSize() + { + assertEquals( 0, new PrimitiveLongList().size() ); + assertEquals( 0, new PrimitiveLongList( 12 ).size() ); + } + + @Test + void addingElementsChangeSize() + { + PrimitiveLongList longList = new PrimitiveLongList(); + longList.add( 1L ); + + assertFalse( longList.isEmpty() ); + assertEquals( 1, longList.size() ); + + longList.add( 2L ); + assertFalse( longList.isEmpty() ); + assertEquals( 2, longList.size() ); + + longList.add( 3L ); + + assertFalse( longList.isEmpty() ); + assertEquals( 3, longList.size() ); + } + + @Test + void accessAddedElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + for ( long i = 1; i < 6L; i++ ) + { + longList.add( i ); + } + + assertEquals( 5L, longList.get( 4 ) ); + assertEquals( 1L, longList.get( 0 ) ); + } + + @Test + void throwExceptionOnAccessingNonExistentElement() + { + PrimitiveLongList longList = new PrimitiveLongList(); + assertThrows( IndexOutOfBoundsException.class, () -> longList.get( 0 ) ); + } + + @Test + void iterateOverListElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + for ( long i = 0; i < 10L; i++ ) + { + longList.add( i ); + } + + int iteratorElements = 0; + long value = 0; + PrimitiveLongIterator iterator = longList.iterator(); + while ( iterator.hasNext() ) + { + iteratorElements++; + assertEquals( value++, iterator.next() ); + } + + assertEquals( iteratorElements, longList.size() ); + } + + @Test + void clearResetListSize() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 10; + for ( long i = 0; i < 10L; i++ ) + { + longList.add( i ); + } + assertEquals( size, longList.size() ); + + longList.clear(); + + assertEquals( 0, longList.size() ); + assertTrue( longList.isEmpty() ); + } + + @Test + void transformListToArray() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 24L; + for ( long i = 0; i < size; i++ ) + { + longList.add( i ); + } + + long[] longs = longList.toArray(); + assertEquals( size, longs.length ); + for ( int i = 0; i < longs.length; i++ ) + { + assertEquals( i, longs[i] ); + } + } + + @Test + void holdLotsOfElements() + { + PrimitiveLongList longList = new PrimitiveLongList(); + long size = 13077L; + for ( long i = 0; i < size; i++ ) + { + longList.add( i ); + } + + assertEquals( size, longList.size() ); + for ( int i = 0; i < size; i++ ) + { + assertEquals( i, longList.get( i ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java new file mode 100644 index 0000000000..6036692496 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongPeekingIteratorTest.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveLongPeekingIteratorTest +{ + @Test + void shouldDetectMultipleValues() + { + // GIVEN + long[] values = new long[]{1, 2, 3}; + PrimitiveLongIterator actual = PrimitiveLongCollections.iterator( values ); + PrimitiveLongPeekingIterator peekingIterator = new PrimitiveLongPeekingIterator( actual ); + + // THEN + assertTrue( peekingIterator.hasMultipleValues() ); + for ( long value: values ) + { + assertEquals( value, peekingIterator.next() ); + } + assertFalse( peekingIterator.hasNext() ); + assertTrue( peekingIterator.hasMultipleValues() ); + } + + @Test + void shouldDetectSingleValue() + { + // GIVEN + long[] values = new long[]{1}; + PrimitiveLongIterator actual = PrimitiveLongCollections.iterator( values ); + PrimitiveLongPeekingIterator peekingIterator = new PrimitiveLongPeekingIterator( actual ); + // THEN + assertFalse( peekingIterator.hasMultipleValues() ); + for ( long value: values ) + { + assertEquals( value, peekingIterator.next() ); + } + assertFalse( peekingIterator.hasNext() ); + assertFalse( peekingIterator.hasMultipleValues() ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java new file mode 100644 index 0000000000..33259c7225 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongResourceCollectionsTest.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.LongPredicate; + +import org.neo4j.graphdb.Resource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PrimitiveLongResourceCollectionsTest +{ + private static final LongPredicate EVEN = value -> value % 2 == 0; + + // ITERATOR + + @Test + void simpleIterator() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator iterator = PrimitiveLongResourceCollections.iterator( resource, 1, 2, 3, 4 ); + + // Then + assertContent( iterator, 1, 2, 3, 4 ); + + // When + iterator.close(); + + // Then + assertEquals( 1, resource.closeCount(), "exactly one call to close" ); + } + + // FILTER + + @Test + void filterItems() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator iterator = PrimitiveLongResourceCollections.iterator( resource, 1, 2, 3, 4 ); + + // When + PrimitiveLongResourceIterator filtered = PrimitiveLongResourceCollections.filter( iterator, EVEN ); + + // Then + assertContent( filtered, 2, 4 ); + + // When + filtered.close(); + + // Then + assertEquals( 1, resource.closeCount(), "exactly one call to close" ); + } + + // CONCAT + + @Test + void concatIterators() + { + // Given + CountingResource resource = new CountingResource(); + PrimitiveLongResourceIterator first = PrimitiveLongResourceCollections.iterator( resource, 1, 2 ); + PrimitiveLongResourceIterator second = PrimitiveLongResourceCollections.iterator( resource, 3, 4 ); + + // When + PrimitiveLongResourceIterator concat = PrimitiveLongResourceCollections.concat( first, second ); + + // Then + assertContent( concat, 1, 2, 3, 4 ); + + // When + concat.close(); + + // Then + assertEquals( 2, resource.closeCount(), "all concatenated iterators are closed" ); + } + + private static void assertContent( PrimitiveLongResourceIterator iterator, long... expected ) + { + int i = 0; + while ( iterator.hasNext() ) + { + assertEquals( expected[i++], iterator.next(), "has expected value" ); + } + assertEquals( expected.length, i, "has all expected values" ); + } + + private static class CountingResource implements Resource + { + private AtomicInteger closed = new AtomicInteger(); + + @Override + public void close() + { + closed.incrementAndGet(); + } + + int closeCount() + { + return closed.get(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java new file mode 100644 index 0000000000..de993ef18e --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/PrimitiveLongStackTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PrimitiveLongStackTest +{ + @Test + void shouldPushAndPollSomeEntities() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 6 ); + + // WHEN/THEN + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + + stack.push( 123 ); + assertFalse( stack.isEmpty() ); + + stack.push( 456 ); + assertFalse( stack.isEmpty() ); + assertEquals( 456, stack.poll() ); + + assertFalse( stack.isEmpty() ); + assertEquals( 123, stack.poll() ); + + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + void shouldGrowArray() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 5 ); + + // WHEN + for ( int i = 0; i <= 7; i++ ) + { + stack.push( i ); + } + + // THEN + for ( int i = 7; i >= 0; i-- ) + { + assertFalse( stack.isEmpty() ); + assertEquals( i, stack.poll() ); + } + assertTrue( stack.isEmpty() ); + assertEquals( -1, stack.poll() ); + } + + @Test + void shouldStoreLongs() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack( 5 ); + long value1 = 10L * Integer.MAX_VALUE; + long value2 = 101L * Integer.MAX_VALUE; + stack.push( value1 ); + stack.push( value2 ); + + // WHEN + long firstPolledValue = stack.poll(); + long secondPolledValue = stack.poll(); + + // THEN + assertEquals( value2, firstPolledValue ); + assertEquals( value1, secondPolledValue ); + assertTrue( stack.isEmpty() ); + } + + @Test + void shouldIterate() + { + // GIVEN + PrimitiveLongStack stack = new PrimitiveLongStack(); + + // WHEN + for ( int i = 0; i < 7; i++ ) + { + stack.push( i ); + } + + // THEN + PrimitiveLongIterator iterator = stack.iterator(); + long i = 0; + while ( iterator.hasNext() ) + { + assertEquals( i++, iterator.next() ); + } + assertEquals( 7L, i ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java new file mode 100644 index 0000000000..5709c18ff2 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/ClosingTablesTest.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +@SuppressWarnings( "unchecked" ) +class ClosingTablesTest +{ + @Test + void intCollectionsMustDelegateCloseToTable() + { + // Given + Table table = mock( Table.class ); + AbstractIntHopScotchCollection coll = new AbstractIntHopScotchCollection( table ) + { + @Override + public boolean equals( Object other ) + { + return false; + } + + @Override + public int hashCode() + { + return 0; + } + }; + + // When + coll.close(); + + // Then + verify( table ).close(); + } + + @Test + void longCollectionsMustDelegateCloseToTable() + { + // Given + Table table = mock( Table.class ); + AbstractLongHopScotchCollection coll = + new AbstractLongHopScotchCollection( table ) + { + @Override + public boolean equals( Object other ) + { + return false; + } + + @Override + public int hashCode() + { + return 0; + } + }; + + // When + coll.close(); + + // Then + verify( table ).close(); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java new file mode 100644 index 0000000000..85616959a3 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/HopScotchHashingAlgorithmTest.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.neo4j.collection.primitive.PrimitiveLongIterator; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.Monitor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.neo4j.collection.primitive.Primitive.VALUE_MARKER; +import static org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.DEFAULT_H; + +class HopScotchHashingAlgorithmTest +{ + @Test + void shouldSupportIteratingThroughResize() + { + // GIVEN + int threshold = figureOutGrowthThreshold(); + TableGrowthAwareMonitor monitor = new TableGrowthAwareMonitor(); + PrimitiveLongSet set = new PrimitiveLongHashSet( + new LongKeyTable<>( DEFAULT_H, VALUE_MARKER ), VALUE_MARKER, monitor ); + Set added = new HashSet<>(); + for ( long i = 0; i < threshold - 1; i++ ) + { + long value = i * 3; + set.add( value ); + added.add( value ); + } + + // WHEN + PrimitiveLongIterator iterator = set.iterator(); + Set iterated = new HashSet<>(); + for ( int i = 0; i < threshold / 2; i++ ) + { + iterated.add( iterator.next() ); + } + assertFalse( monitor.checkAndReset() ); + // will push it over the edge, to grow the table + set.add( (threshold - 1) * 3 ); + assertTrue( monitor.checkAndReset() ); + while ( iterator.hasNext() ) + { + iterated.add( iterator.next() ); + } + + // THEN + assertEquals( added, iterated ); + } + + private static class TableGrowthAwareMonitor extends Monitor.Adapter + { + private boolean grew; + + @Override + public boolean tableGrew( int fromCapacity, int toCapacity, int currentSize ) + { + return grew = true; + } + + boolean checkAndReset() + { + try + { + return grew; + } + finally + { + grew = false; + } + } + } + + private static int figureOutGrowthThreshold() + { + final AtomicBoolean grew = new AtomicBoolean(); + Monitor monitor = new Monitor.Adapter() + { + @Override + public boolean tableGrew( int fromCapacity, int toCapacity, int currentSize ) + { + grew.set( true ); + return true; + } + }; + try ( PrimitiveLongSet set = new PrimitiveLongHashSet( + new LongKeyTable<>( DEFAULT_H, VALUE_MARKER ), VALUE_MARKER, monitor ) ) + { + int i = 0; + for ( i = 0; !grew.get(); i++ ) + { + set.add( i * 3 ); + } + return i; + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java new file mode 100644 index 0000000000..1365841f32 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/JumpingSequencePutTest.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicLong; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongSet; + +class JumpingSequencePutTest +{ + @Test + void shouldHandlePathologicalSequenceCase() + { + // Given + PrimitiveLongSet set = Primitive.longSet(); + Sequence seqGen = new Sequence(); + + // When + for ( int i = 0; i < 10000; i++ ) + { + set.add( seqGen.next() ); + } + } + + /** + * To be frank, I don't understand the intricacies of how this works, but + * this is a cut-out version of the sequence generator that triggered the original bug. + * The gist is that it generates sequences of ids that "jump" to a much higher number + * every one hundred ids or so. + */ + private class Sequence + { + private static final int sizePerJump = 100; + private final AtomicLong nextId = new AtomicLong(); + private int leftToNextJump = sizePerJump / 2; + private long highBits; + + public long next() + { + long result = tryNextId(); + if ( --leftToNextJump == 0 ) + { + leftToNextJump = sizePerJump; + nextId.set( (0xFFFFFFFFL | (highBits++ << 32)) - sizePerJump / 2 + 1 ); + } + return result; + } + + private long tryNextId() + { + long result = nextId.getAndIncrement(); + if ( result == 0xFFFFFFFFL ) // 4294967295L + { + result = nextId.getAndIncrement(); + leftToNextJump--; + } + return result; + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java new file mode 100644 index 0000000000..d693a02dce --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveCollectionEqualityTest.java @@ -0,0 +1,532 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.experimental.theories.DataPoint; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveCollection; +import org.neo4j.collection.primitive.PrimitiveIntLongMap; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; +import org.neo4j.collection.primitive.PrimitiveIntSet; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.collection.primitive.PrimitiveLongLongMap; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.function.Factory; +import org.neo4j.memory.GlobalMemoryTracker; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isOneOf; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assume.assumeTrue; + +@SuppressWarnings( "unchecked" ) +@RunWith( Theories.class ) +public class PrimitiveCollectionEqualityTest +{ + private interface Value + { + void add( T coll ); + + /** + * @return 'true' if what was removed was exactly the value that was put in. + */ + boolean remove( T coll ); + } + + private abstract static class ValueProducer + { + private final Class applicableType; + + ValueProducer( Class applicableType ) + { + this.applicableType = applicableType; + } + + public boolean isApplicable( Factory factory ) + { + try ( PrimitiveCollection coll = factory.newInstance() ) + { + return applicableType.isInstance( coll ); + } + } + + public abstract Value randomValue(); + } + + // ==== Test Value Producers ==== + + @DataPoint + public static ValueProducer intV = new ValueProducer( PrimitiveIntSet.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + return new Value() + { + @Override + public void add( PrimitiveIntSet coll ) + { + coll.add( x ); + } + + @Override + public boolean remove( PrimitiveIntSet coll ) + { + return coll.remove( x ); + } + }; + } + }; + + @DataPoint + public static ValueProducer longV = + new ValueProducer( PrimitiveLongSet.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveLongSet coll ) + { + coll.add( x ); + } + + @Override + public boolean remove( PrimitiveLongSet coll ) + { + return coll.remove( x ); + } + }; + } + }; + + @DataPoint + public static ValueProducer intLongV = new ValueProducer( + PrimitiveIntLongMap.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + final long y = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveIntLongMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveIntLongMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longIntV = new ValueProducer( + PrimitiveLongIntMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final int y = randomInt(); + return new Value() + { + @Override + public void add( PrimitiveLongIntMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongIntMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longLongV = new ValueProducer( + PrimitiveLongLongMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final long y = randomLong(); + return new Value() + { + @Override + public void add( PrimitiveLongLongMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongLongMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer intObjV = + new ValueProducer( PrimitiveIntObjectMap.class ) + { + @Override + public Value randomValue() + { + final int x = randomInt(); + final Object y = new Object(); + return new Value() + { + @Override + public void add( PrimitiveIntObjectMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveIntObjectMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + @DataPoint + public static ValueProducer longObjV = + new ValueProducer( PrimitiveLongObjectMap.class ) + { + @Override + public Value randomValue() + { + final long x = randomLong(); + final Object y = new Object(); + return new Value() + { + @Override + public void add( PrimitiveLongObjectMap coll ) + { + coll.put( x, y ); + } + + @Override + public boolean remove( PrimitiveLongObjectMap coll ) + { + return coll.remove( x ) == y; + } + }; + } + }; + + // ==== Primitive Collection Implementations ==== + + @DataPoint + public static Factory intSet = Primitive::intSet; + + @DataPoint + public static Factory intSetWithCapacity = () -> Primitive.intSet( randomCapacity() ); + + @DataPoint + public static Factory offheapIntSet = + () -> Primitive.offHeapIntSet( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapIntSetWithCapacity = + () -> Primitive.offHeapIntSet( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory longSet = Primitive::longSet; + + @DataPoint + public static Factory longSetWithCapacity = () -> Primitive.longSet( randomCapacity() ); + + @DataPoint + public static Factory offheapLongSet = + () -> Primitive.offHeapLongSet( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapLongSetWithCapacity = + () -> Primitive.offHeapLongSet( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory intLongMap = Primitive::intLongMap; + + @DataPoint + public static Factory intLongMapWithCapacity = () -> Primitive.intLongMap( randomCapacity() ); + + @DataPoint + public static Factory longIntMap = Primitive::longIntMap; + + @DataPoint + public static Factory longIntMapWithCapacity = () -> Primitive.longIntMap( randomCapacity() ); + + @DataPoint + public static Factory longLongMap = Primitive::longLongMap; + + @DataPoint + public static Factory longLongMapWithCapacity = + () -> Primitive.longLongMap( randomCapacity() ); + + @DataPoint + public static Factory offheapLongLongMap = + () -> Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory offheapLongLongMapWithCapacity = + () -> Primitive.offHeapLongLongMap( randomCapacity(), GlobalMemoryTracker.INSTANCE ); + + @DataPoint + public static Factory intObjMap = Primitive::intObjectMap; + + @DataPoint + public static Factory intObjMapWithCapacity = + () -> Primitive.intObjectMap( randomCapacity() ); + + @DataPoint + public static Factory longObjectMap = Primitive::longObjectMap; + + @DataPoint + public static Factory longObjectMapWithCapacity = + () -> Primitive.longObjectMap( randomCapacity() ); + + private static final PrimitiveIntSet observedRandomInts = Primitive.intSet(); + private static final PrimitiveLongSet observedRandomLongs = Primitive.longSet(); + + /** + * Produce a random int that hasn't been seen before by any test. + */ + private static int randomInt() + { + int n; + do + { + n = ThreadLocalRandom.current().nextInt(); + } + while ( n == -1 || !observedRandomInts.add( n ) ); + return n; + } + + /** + * Produce a random long that hasn't been seen before by any test. + */ + private static long randomLong() + { + long n; + do + { + n = ThreadLocalRandom.current().nextLong(); + } + while ( n == -1 || !observedRandomLongs.add( n ) ); + return n; + } + + private static int randomCapacity() + { + return ThreadLocalRandom.current().nextInt( 30, 1200 ); + } + + private static void assertEquals( PrimitiveCollection a, PrimitiveCollection b ) + { + assertThat( a, is( equalTo( b ) ) ); + assertThat( b, is( equalTo( a ) ) ); + assertThat( a.hashCode(), is( equalTo( b.hashCode() ) ) ); + } + + @Theory + public void collectionsAreNotEqualToObjectsOfOtherTypes( Factory factory ) + { + try ( PrimitiveCollection coll = factory.newInstance() ) + { + assertNotEquals( coll, new Object() ); + } + } + + @Theory + public void emptyCollectionsAreEqual( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + assertEquals( a, b ); + } + } + + @Theory + public void addingTheSameValuesMustProduceEqualCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + Value value = values.randomValue(); + value.add( a ); + value.add( b ); + assertEquals( a, b ); + } + } + + @Theory + public void addingDifferentValuesMustProduceUnequalCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + values.randomValue().add( a ); + values.randomValue().add( b ); + assertNotEquals( a, b ); + } + } + + @Theory + public void differentButEquivalentMutationsShouldProduceEqualCollections( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + // Note that this test, cute as it is, also verifies that the hashCode implementation is order-invariant :) + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + Value x = values.randomValue(); + Value y = values.randomValue(); + Value z = values.randomValue(); + + x.add( a ); + z.add( a ); + + z.add( b ); + y.add( b ); + x.add( b ); + y.remove( b ); + + assertEquals( a, b ); + } + } + + @Theory + public void capacityDifferencesMustNotInfluenceEquality( + ValueProducer values, Factory factoryA, Factory factoryB ) + { + assumeTrue( values.isApplicable( factoryA ) ); + assumeTrue( values.isApplicable( factoryB ) ); + try ( PrimitiveCollection a = factoryA.newInstance(); + PrimitiveCollection b = factoryB.newInstance() ) + { + List tmps = new ArrayList<>(); + for ( int i = 0; i < 5000; i++ ) + { + Value value = values.randomValue(); + value.add( b ); + tmps.add( value ); + } + + Value specificValue = values.randomValue(); + specificValue.add( a ); + specificValue.add( b ); + + for ( int i = 0; i < 5000; i++ ) + { + Value value = values.randomValue(); + value.add( b ); + tmps.add( value ); + } + + Collections.shuffle( tmps ); + for ( Value value: tmps ) + { + value.remove( b ); + } + + assertEquals( a, b ); + } + } + + @Theory + public void hashCodeMustFollowValues( + ValueProducer values, Factory factory ) + { + assumeTrue( values.isApplicable( factory ) ); + try ( PrimitiveCollection a = factory.newInstance() ) + { + Value x = values.randomValue(); + Value y = values.randomValue(); + Value z = values.randomValue(); + + int i = a.hashCode(); + x.add( a ); + int j = a.hashCode(); + y.add( a ); + int k = a.hashCode(); + z.add( a ); + int l = a.hashCode(); + z.remove( a ); + int m = a.hashCode(); + y.remove( a ); + int n = a.hashCode(); + x.remove( a ); + int o = a.hashCode(); + + assertThat( "0 elm hashcode equal", o, is( i ) ); + assertThat( "1 elm hashcode equal", n, is( j ) ); + assertThat( "2 elm hashcode equal", m, is( k ) ); + assertThat( "3 elm hashcode distinct", l, not( isOneOf( i, j, k, m, n, o ) ) ); + assertThat( "2 elm hashcode distinct", k, not( isOneOf( i, j, l, n, o ) ) ); + assertThat( "1 elm hashcode distinct", n, not( isOneOf( i, k, l, m, o ) ) ); + assertThat( "0 elm hashcode distinct", i, not( isOneOf( j, k, l, m, n ) ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java new file mode 100644 index 0000000000..4cb5af0eca --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveIntObjectHashMapTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PrimitiveIntObjectHashMapTest +{ + + @Test + void doNotComputeValueIfPresent() + { + PrimitiveIntObjectMap intObjectMap = Primitive.intObjectMap(); + intObjectMap.put( 1, "a" ); + assertEquals( "a", intObjectMap.computeIfAbsent( 1, value -> "b" ) ); + } + + @Test + void computeValueIfAbsent() + { + PrimitiveIntObjectMap intObjectMap = Primitive.intObjectMap(); + intObjectMap.put( 1, "a" ); + assertEquals( "b", intObjectMap.computeIfAbsent( 2, value -> "b" ) ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java new file mode 100644 index 0000000000..088c595e47 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongIntMapRIT.java @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class PrimitiveLongIntMapRIT +{ + @Test + void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( mapFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + + fullVerification( result.getTarget(), random ); + } + } + + private static void fullVerification( Maps target, Random random ) + { + for ( Map.Entry entry: target.normalMap.entrySet() ) + { + assertTrue( target.map.containsKey( entry.getKey() ) ); + assertEquals( entry.getValue().intValue(), target.map.get( entry.getKey() ) ); + } + + for ( int i = 0; i < target.normalMap.size(); i++ ) + { + assertFalse( target.map.containsKey( randomNonExisting( random, target.normalMap ) ) ); + } + } + + private static Printable given() + { + return out -> out.println( PrimitiveLongIntMap.class.getSimpleName() + " map = " + + Primitive.class.getSimpleName() + ".longIntMap();" ); + } + + private static ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private static TargetFactory mapFactory() + { + return Maps::new; + } + + private static Action generateAction( Random random, Maps from ) + { + boolean anExisting = !from.normalMap.isEmpty() && random.nextInt( 3 ) == 0; + long key = anExisting ? + randomExisting( random, from.normalMap ) : + randomNonExisting( random, from.normalMap ); + int value = random.nextInt( 100 ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( key ); + } + + // add + return new AddAction( key, value ); + } + + private static long randomNonExisting( Random random, Map existing ) + { + while ( true ) + { + long key = Math.abs( random.nextLong() ); + if ( !existing.containsKey( key ) ) + { + return key; + } + } + } + + private static long randomExisting( Random random, Map existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.keySet().iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long key; + private final int value; + + AddAction( long key, int value ) + { + this.key = key; + this.value = value; + } + + @Override + public String apply( Maps target ) + { + boolean existing = target.normalMap.containsKey( key ); + int existingValue = existing ? target.normalMap.get( key ) : -1; + int actualSizeBefore = target.normalMap.size(); + + int sizeBefore = target.map.size(); + boolean existedBefore = target.map.containsKey( key ); + int valueBefore = target.map.get( key ); + int previous = target.map.put( key, value ); + boolean existsAfter = target.map.containsKey( key ); + int valueAfter = target.map.get( key ); + target.normalMap.put( key, value ); + int sizeAfter = target.map.size(); + + int actualSizeAfter = target.normalMap.size(); + boolean ok = + (sizeBefore == actualSizeBefore) & + (existedBefore == existing) & + (existingValue == valueBefore) & + (existingValue == previous) & + (valueAfter == value) & + existsAfter & + (sizeAfter == actualSizeAfter); + return ok ? null : "" + key + ":" + value + "," + existingValue + "," + existedBefore + + "," + previous + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + String addition = "map.put( " + key + ", " + value + " );"; + if ( includeChecks ) + { + boolean existing = source.normalMap.containsKey( key ); + int existingValue = existing ? source.normalMap.get( key ) : -1; + out.println( "int sizeBefore = map.size();" ); + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "int valueBefore = map.get( %d );", key ) ); + out.println( format( "int previous = %s", addition ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "int valueAfter = map.get( %d );", key ) ); + out.println( "int sizeAfter = map.size();" ); + + int actualSizeBefore = source.normalMap.size(); + out.println( format( "assertEquals( \"%s\", %d, sizeBefore );", + "Size before put should have been " + actualSizeBefore, actualSizeBefore ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", %d, previous );", + "value returned from put should be " + existingValue, existingValue ) ); + out.println( format( "assertTrue( \"%s\", existsAfter );", + key + " should exist" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueAfter );", + "value after putting should be " + value, value ) ); + int actualSizeAfter = existing ? actualSizeBefore : actualSizeBefore + 1; + out.println( format( "assertEquals( \"%s\", %d, sizeAfter );", + "Size after put should have been " + actualSizeAfter, actualSizeAfter ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long key; + + RemoveAction( long key ) + { + this.key = key; + } + + @Override + public String apply( Maps target ) + { + boolean existing = target.normalMap.containsKey( key ); + int existingValue = existing ? target.normalMap.get( key ) : -1; + + boolean existedBefore = target.map.containsKey( key ); + int valueBefore = target.map.get( key ); + int removed = target.map.remove( key ); + boolean existsAfter = target.map.containsKey( key ); + int valueAfter = target.map.get( key ); + target.normalMap.remove( key ); + + boolean ok = + (existedBefore == existing) & + (existingValue == valueBefore) & + (existingValue == removed) & + (valueAfter == -1) & + !existsAfter; + return ok ? null : "" + key + "," + existingValue + "," + existedBefore + + "," + removed + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + String removal = "map.remove( " + key + " );"; + if ( includeChecks ) + { + boolean existing = source.normalMap.containsKey( key ); + int existingValue = existing ? source.normalMap.get( key ) : -1; + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "int valueBefore = map.get( %d );", key ) ); + out.println( format( "int removed = %s", removal ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "int valueAfter = map.get( %d );", key ) ); + + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before removing here" ) ); + out.println( format( "assertEquals( \"%s\", %d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", %d, removed );", + "value returned from remove should be " + existingValue, existingValue ) ); + out.println( format( "assertFalse( \"%s\", existsAfter );", + key + " should not exist" ) ); + out.println( format( "assertEquals( \"%s\", -1, valueAfter );", + "value after removing should be -1" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Maps implements TestResource + { + final Map normalMap = new HashMap<>(); + final PrimitiveLongIntMap map = Primitive.longIntMap(); + + @Override + public String toString() + { + return map.toString(); + } + + @Override + public void close() + { + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java new file mode 100644 index 0000000000..e1b8cfa1c1 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongMapTest.java @@ -0,0 +1,1373 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntLongMap; +import org.neo4j.collection.primitive.PrimitiveIntLongVisitor; +import org.neo4j.collection.primitive.PrimitiveIntObjectMap; +import org.neo4j.collection.primitive.PrimitiveIntObjectVisitor; +import org.neo4j.collection.primitive.PrimitiveIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongIntMap; +import org.neo4j.collection.primitive.PrimitiveLongIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongLongMap; +import org.neo4j.collection.primitive.PrimitiveLongLongVisitor; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.collection.primitive.PrimitiveLongObjectVisitor; +import org.neo4j.collection.primitive.PrimitiveLongVisitor; +import org.neo4j.memory.GlobalMemoryTracker; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +class PrimitiveLongMapTest +{ + @Test + void shouldContainAddedValues() + { + // GIVEN + Map expectedEntries = new HashMap<>(); + expectedEntries.put( 1994703545L, 59 ); + expectedEntries.put( 1583732120L, 98 ); + expectedEntries.put( 756530774L, 56 ); + expectedEntries.put( 1433091763L, 22 ); + + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + for ( Map.Entry entry: expectedEntries.entrySet() ) + { + map.put( entry.getKey(), entry.getValue() ); + } + + // WHEN/THEN + boolean existedBefore = map.containsKey( 1433091763 ); + Integer valueBefore = map.get( 1433091763 ); + Integer previous = map.put( 1433091763, 35 ); + boolean existsAfter = map.containsKey( 1433091763 ); + Integer valueAfter = map.get( 1433091763 ); + assertTrue( existedBefore, "1433091763 should exist before putting here" ); + assertEquals( (Integer) 22, valueBefore ); + assertEquals( (Integer) 22, previous ); + assertTrue( existsAfter, "(1433091763, 35) should exist" ); + assertEquals( (Integer) 35, valueAfter ); + expectedEntries.put( 1433091763L, 35 ); + + final Map visitedEntries = new HashMap<>(); + map.visitEntries( ( key, value ) -> + { + visitedEntries.put( key, value ); + return false; + } ); + assertEquals( expectedEntries, visitedEntries ); + } + + @Test + void shouldContainAddedValues_2() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1950736976, 4 ); + map.put( 1054824202, 58 ); + map.put( 348690619, 54 ); + map.put( 1224909480, 79 ); + map.put( 1508493474, 82 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 1508493474 ); + Integer valueBefore = map.get( 1508493474 ); + Integer previous = map.put( 1508493474, 62 ); + boolean existsAfter = map.containsKey( 1508493474 ); + Integer valueAfter = map.get( 1508493474 ); + assertTrue( existedBefore, "1508493474 should exist before putting here" ); + assertEquals( (Integer) 82, valueBefore, "value before should be 82" ); + assertEquals( (Integer) 82, previous, "value returned from put should be 82" ); + assertTrue( existsAfter, "1508493474 should exist" ); + assertEquals( (Integer) 62, valueAfter, "value after putting should be 62" ); + } + + @Test + void shouldContainAddedValues_3() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.remove( 1338037218 ); + map.put( 680125236, 83 ); + map.put( 680125236, 76 ); + map.put( 680125236, 47 ); + map.put( 680125236, 30 ); + map.put( 2080483597, 52 ); + map.put( 867107519, 80 ); + map.remove( 710100384 ); + map.put( 671477921, 88 ); + map.put( 1163609643, 17 ); + map.put( 680125236, 57 ); + map.put( 1163609643, 70 ); + map.put( 2080483597, 89 ); + map.put( 1472451898, 62 ); + map.put( 1379499183, 93 ); + map.put( 680125236, 17 ); + map.put( 567842571, 43 ); + map.put( 2045599221, 60 ); + map.remove( 641295711 ); + map.remove( 867107519 ); + map.put( 2045599221, 30 ); + map.remove( 2094689486 ); + map.put( 1572965945, 79 ); + map.remove( 1329473388 ); + map.put( 1572965945, 39 ); + map.put( 264067586, 60 ); + map.put( 1751846500, 5 ); + map.put( 1163609643, 25 ); + map.put( 1379499183, 54 ); + map.remove( 671477921 ); + map.put( 1572965945, 59 ); + map.put( 880140639, 87 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 468007595 ); + Integer valueBefore = map.get( 468007595 ); + Integer previous = map.put( 468007595, 67 ); + boolean existsAfter = map.containsKey( 468007595 ); + Integer valueAfter = map.get( 468007595 ); + assertFalse( existedBefore, "468007595 should not exist before putting here" ); + assertNull( valueBefore, "value before putting should be null" ); + assertNull( previous, "value returned from putting should be null" ); + assertTrue( existsAfter, "468007595 should exist" ); + assertEquals( (Integer) 67, valueAfter, "value after putting should be 67" ); + } + + @Test + void shouldHaveCorrectSize() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 152407843, 17 ); + map.put( 435803197, 29 ); + map.put( 2063473573, 75 ); + map.put( 162922679, 36 ); + map.put( 923042422, 47 ); + map.put( 204556993, 28 ); + map.put( 109670524, 80 ); + map.put( 214127443, 88 ); + map.put( 297958695, 97 ); + map.put( 873122371, 73 ); + map.put( 398704786, 25 ); + map.put( 376378917, 62 ); + map.put( 1948985185, 3 ); + map.put( 918339266, 4 ); + map.put( 1126937431, 48 ); + map.put( 568627750, 6 ); + map.put( 887668742, 1 ); + map.put( 888089153, 88 ); + map.put( 1671871078, 26 ); + map.put( 479217936, 11 ); + map.put( 1874408328, 56 ); + map.put( 1517450283, 83 ); + map.put( 1352952211, 57 ); + map.put( 686066722, 92 ); + map.put( 1593196310, 71 ); + map.put( 1535351391, 62 ); + map.put( 296560052, 59 ); + map.put( 1513542622, 49 ); + map.put( 1899330306, 57 ); + map.put( 746190595, 31 ); + map.put( 1216091366, 90 ); + map.put( 353922939, 16 ); + map.put( 680935464, 16 ); + map.put( 235368309, 8 ); + map.put( 1988133681, 32 ); + map.put( 330747855, 81 ); + map.put( 492627887, 74 ); + map.put( 1005495348, 8 ); + map.put( 2107419277, 82 ); + map.put( 1421265494, 15 ); + map.put( 1669915469, 92 ); + map.put( 2008247215, 9 ); + map.put( 2010142383, 77 ); + map.put( 829081830, 25 ); + map.put( 1349259272, 38 ); + map.put( 1987482877, 8 ); + map.put( 974334859, 83 ); + map.put( 1376908873, 10 ); + map.put( 2120105656, 22 ); + map.put( 1634193445, 8 ); + map.put( 1160987255, 34 ); + map.put( 2030156381, 16 ); + map.put( 2012943328, 22 ); + map.put( 75749275, 54 ); + map.put( 1415817090, 35 ); + map.put( 562352348, 43 ); + map.put( 658501173, 96 ); + map.put( 441278652, 24 ); + map.put( 633855945, 82 ); + map.put( 579807215, 31 ); + map.put( 1125922962, 33 ); + map.put( 1995076951, 91 ); + map.put( 322776761, 4 ); + map.put( 1011369342, 36 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 679686325 ); + Integer valueBefore = map.get( 679686325 ); + Integer previous = map.put( 679686325, 63 ); + boolean existsAfter = map.containsKey( 679686325 ); + Integer valueAfter = map.get( 679686325 ); + int sizeAfter = map.size(); + assertEquals( 64, sizeBefore, "Size before put should have been 64" ); + assertFalse( existedBefore, "679686325 should not exist before putting here" ); + assertNull( valueBefore, "value before putting should be null" ); + assertNull( previous, "value returned from putting should be null" ); + assertTrue( existsAfter, "679686325 should exist" ); + assertEquals( (Integer) 63, valueAfter, "value after putting should be 63" ); + assertEquals( 65, sizeAfter, "Size after put should have been 65" ); + } + + @Test + void shouldMoveValuesWhenMovingEntriesAround() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 206243105, 47 ); + map.put( 2083304695, 63 ); + map.put( 689837337, 7 ); + map.remove( 206243105 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 689837337 ); + Integer valueBefore = map.get( 689837337 ); + Integer previous = map.put( 689837337, 20 ); + boolean existsAfter = map.containsKey( 689837337 ); + Integer valueAfter = map.get( 689837337 ); + int sizeAfter = map.size(); + assertEquals( 2, sizeBefore, "Size before put should have been 2" ); + assertTrue( existedBefore, "689837337 should exist before putting here" ); + assertEquals( (Integer) 7, valueBefore, "value before should be 7" ); + assertEquals( (Integer) 7, previous, "value returned from put should be 7" ); + assertTrue( existsAfter, "689837337 should exist" ); + assertEquals( (Integer) 20, valueAfter, "value after putting should be 20" ); + assertEquals( 2, sizeAfter, "Size after put should have been 2" ); + } + + @Test + void shouldReturnCorrectPreviousValue() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.remove( 2050585513 ); + map.put( 429170228, 99 ); + map.put( 1356282827, 24 ); + map.remove( 1341095873 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 429170228 ); + int valueBefore = map.get( 429170228 ); + int previous = map.put( 429170228, 1 ); + boolean existsAfter = map.containsKey( 429170228 ); + int valueAfter = map.get( 429170228 ); + int sizeAfter = map.size(); + assertEquals( 2, sizeBefore, "Size before put should have been 2" ); + assertTrue( existedBefore, "429170228 should exist before putting here" ); + assertEquals( 99, valueBefore, "value before should be 99" ); + assertEquals( 99, previous, "value returned from put should be 99" ); + assertTrue( existsAfter, "429170228 should exist" ); + assertEquals( 1, valueAfter, "value after putting should be 1" ); + assertEquals( 2, sizeAfter, "Size after put should have been 2" ); + } + + @Test + void shouldOnlyContainAddedValues() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1179059774, 54 ); + map.put( 612612792, 91 ); + map.put( 853030395, 81 ); + map.put( 1821941016, 69 ); + map.put( 815540261, 54 ); + map.put( 2120470777, 63 ); + map.put( 866144206, 41 ); + map.put( 905659306, 86 ); + map.put( 602586792, 24 ); + map.put( 1033857549, 61 ); + map.put( 1570231638, 69 ); + map.put( 30675820, 53 ); + map.put( 433666923, 14 ); + map.put( 1668952952, 52 ); + map.put( 1733960171, 14 ); + map.put( 1240027317, 64 ); + map.put( 250830995, 71 ); + map.put( 1446519846, 17 ); + map.put( 1857052106, 78 ); + map.put( 37351838, 26 ); + map.put( 1523695604, 78 ); + map.put( 1024540180, 12 ); + map.put( 603632507, 81 ); + map.put( 483087335, 37 ); + map.put( 216300592, 55 ); + map.put( 1729046213, 72 ); + map.put( 1397559084, 78 ); + map.put( 802042428, 34 ); + map.put( 1127990805, 6 ); + map.put( 2081866795, 53 ); + map.put( 1528122026, 39 ); + map.put( 642547543, 78 ); + map.put( 1909701557, 35 ); + map.put( 2070740876, 40 ); + map.put( 316027755, 18 ); + map.put( 824089651, 63 ); + map.put( 1082682044, 85 ); + map.put( 154864377, 44 ); + map.put( 26918244, 73 ); + map.put( 808069768, 20 ); + map.put( 38089155, 17 ); + map.put( 1772700678, 35 ); + map.put( 1790535392, 82 ); + map.put( 159186757, 10 ); + map.put( 73305650, 52 ); + map.put( 2025019209, 38 ); + map.put( 922996536, 53 ); + map.put( 1852424925, 34 ); + map.put( 1181179273, 9 ); + map.put( 107520967, 11 ); + map.put( 1702904247, 55 ); + map.put( 1819417390, 50 ); + map.put( 1163114165, 57 ); + map.put( 2036796587, 40 ); + map.put( 2130510197, 26 ); + map.put( 1710533919, 70 ); + map.put( 497498438, 48 ); + map.put( 147722732, 8 ); + map.remove( 802042428 ); + map.put( 1355114893, 90 ); + map.put( 419675404, 62 ); + map.put( 1722846265, 41 ); + map.put( 1287254514, 61 ); + map.put( 1925017947, 8 ); + map.put( 1290391303, 59 ); + map.put( 1938779966, 27 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 1452811669 ); + int valueBefore = map.get( 1452811669 ); + int previous = map.put( 1452811669, 16 ); + boolean existsAfter = map.containsKey( 1452811669 ); + int valueAfter = map.get( 1452811669 ); + int sizeAfter = map.size(); + assertEquals( 64, sizeBefore, "Size before put should have been 64" ); + assertFalse( existedBefore, "1452811669 should not exist before putting here" ); + assertEquals( -1, valueBefore, "value before should be -1" ); + assertEquals( -1, previous, "value returned from put should be -1" ); + assertTrue( existsAfter, "1452811669 should exist" ); + assertEquals( 16, valueAfter, "value after putting should be 16" ); + assertEquals( 65, sizeAfter, "Size after put should have been 65" ); + } + + @Test + void shouldOnlyContainAddedValues_2() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 913910231, 25 ); + map.put( 102310782, 40 ); + map.put( 634960377, 32 ); + map.put( 947168147, 96 ); + map.put( 947430652, 26 ); + map.put( 1391472521, 72 ); + map.put( 7905512, 10 ); + map.put( 7905512, 2 ); + map.put( 1391472521, 66 ); + map.put( 824376092, 79 ); + map.remove( 750639810 ); + map.put( 947168147, 61 ); + map.put( 831409018, 57 ); + map.put( 241941283, 76 ); + map.put( 824376092, 45 ); + map.remove( 2125994926 ); + map.put( 824376092, 47 ); + map.put( 1477982280, 1 ); + map.remove( 2129508263 ); + map.put( 1477982280, 41 ); + map.put( 642178985, 69 ); + map.put( 1447441709, 85 ); + map.put( 642178985, 27 ); + map.put( 875840384, 72 ); + map.put( 1967716733, 55 ); + map.put( 1965379174, 5 ); + map.put( 913910231, 40 ); + // WHEN/THEN + boolean existedBefore = map.containsKey( 947430652 ); + int valueBefore = map.get( 947430652 ); + int removed = map.remove( 947430652 ); + boolean existsAfter = map.containsKey( 947430652 ); + int valueAfter = map.get( 947430652 ); + assertTrue( existedBefore, "947430652 should exist before removing here" ); + assertEquals( 26, valueBefore, "value before should be 26" ); + assertEquals( 26, removed, "value returned from remove should be 26" ); + assertFalse( existsAfter, "947430652 should not exist" ); + assertEquals( -1, valueAfter, "value after removing should be -1" ); + } + + @Test + void shouldOnlyContainAddedValues_3() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 2083704227957337692L, 50 ); + map.put( 1039748383662879297L, 12 ); + map.put( 6296247210943123044L, 45 ); + map.put( 8004677065031068097L, 5 ); + map.put( 1039748383662879297L, 70 ); + map.put( 5386804704064477958L, 97 ); + map.remove( 1506507783133586973L ); + map.put( 4287434858289406631L, 29 ); + map.put( 8004677065031068097L, 17 ); + map.put( 986286772325632801L, 14 ); + map.put( 7880139640446289959L, 68 ); + map.put( 8004677065031068097L, 23 ); + map.put( 5386804704064477958L, 72 ); + map.put( 5386804704064477958L, 71 ); + map.put( 2300381985575721987L, 0 ); + map.put( 6144230340727188436L, 31 ); + map.put( 425423457410117293L, 88 ); + map.put( 2083704227957337692L, 65 ); + map.put( 7805027477403310582L, 72 ); + map.put( 2254081933055750443L, 66 ); + map.put( 5386804704064477958L, 46 ); + map.put( 5787098127909281443L, 45 ); + map.put( 5508645210651400664L, 45 ); + map.put( 6092264867460428040L, 65 ); + map.put( 4551026293109220157L, 52 ); + map.put( 4669163071261559807L, 33 ); + map.put( 5790325306669462860L, 96 ); + map.put( 4337317298737908324L, 78 ); + map.put( 986286772325632801L, 71 ); + map.put( 4287434858289406631L, 47 ); + map.put( 1827085004206892313L, 30 ); + map.put( 6070945099342863711L, 88 ); + map.remove( 6300957726732252611L ); + map.put( 2300381985575721987L, 22 ); + map.put( 2083704227957337692L, 2 ); + map.put( 2885272279767063039L, 71 ); + map.put( 3627867780921264529L, 5 ); + map.remove( 5330274310754559602L ); + map.put( 8902857048431919030L, 23 ); + map.remove( 4287434858289406631L ); + map.put( 5459968256561120197L, 8 ); + map.put( 5790325306669462860L, 17 ); + map.put( 9003964541346458616L, 45 ); + map.put( 3832091967762842783L, 79 ); + map.put( 1332274446340546922L, 62 ); + map.put( 6610784890222945257L, 20 ); + map.put( 3627867780921264529L, 65 ); + map.put( 7988336790991560848L, 89 ); + map.put( 5386804704064477958L, 15 ); + map.put( 6296247210943123044L, 19 ); + map.put( 7776019112299874624L, 67 ); + map.put( 5827611175622537127L, 18 ); + map.remove( 8004677065031068097L ); + map.put( 2451971987846333787L, 48 ); + map.put( 3627867780921264529L, 16 ); + map.put( 2506727685914893570L, 61 ); + map.put( 6629089416451699826L, 89 ); + map.put( 875078333857781813L, 38 ); + map.put( 439984342972777679L, 51 ); + map.put( 9077428346047966819L, 19 ); + map.put( 7045299269724516542L, 73 ); + map.put( 8055487013098459354L, 24 ); + map.put( 6610784890222945257L, 65 ); + map.put( 986286772325632801L, 29 ); + map.put( 133928815519522465L, 81 ); + map.put( 5780114596098993316L, 15 ); + map.put( 3790785290324207363L, 91 ); + map.put( 2795040354588080479L, 48 ); + map.put( 4218658174275197144L, 59 ); + map.put( 6610784890222945257L, 70 ); + map.remove( 3722940212039795685L ); + map.put( 1817899559164238906L, 30 ); + map.put( 4551026293109220157L, 35 ); + map.put( 986286772325632801L, 57 ); + map.put( 3811462607668925015L, 57 ); + map.put( 2795040354588080479L, 85 ); + map.put( 8460476221939231932L, 86 ); + map.remove( 8957537157979159052L ); + map.put( 2032224502814063026L, 57 ); + map.remove( 8924941903092284834L ); + map.put( 5386804704064477958L, 2 ); + map.put( 6629089416451699826L, 18 ); + map.put( 425423457410117293L, 31 ); + map.put( 4337317298737908324L, 35 ); + map.remove( 5337770067730257989L ); + map.put( 6150561851033498431L, 49 ); + map.put( 5067121328094576685L, 46 ); + map.remove( 3742103310924563011L ); + map.put( 1327614778938791146L, 49 ); + map.put( 255729841510922319L, 16 ); + map.put( 8785988080128503533L, 69 ); + map.put( 4218658174275197144L, 20 ); + map.put( 1265271287408386915L, 43 ); + map.put( 255729841510922319L, 5 ); + map.put( 8651736753344997668L, 41 ); + map.put( 4363375305508283265L, 4 ); + map.put( 4185381066643227500L, 29 ); + map.put( 3790785290324207363L, 58 ); + map.put( 3058911485922749695L, 1 ); + map.put( 8629268898854377850L, 66 ); + map.put( 1762013345156514959L, 5 ); + map.remove( 4354754593499656793L ); + map.put( 1332274446340546922L, 16 ); + map.put( 4953501292937412915L, 87 ); + map.put( 2330841365833073849L, 83 ); + map.put( 8096564328797694553L, 44 ); + map.put( 8935185623148330821L, 7 ); + map.put( 6150561851033498431L, 48 ); + map.remove( 5827611175622537127L ); + map.put( 8048363335369773749L, 25 ); + map.put( 3627867780921264529L, 48 ); + map.put( 4806848030248674690L, 14 ); + map.put( 5430628648110105698L, 30 ); + map.remove( 7261476188677343032L ); + map.put( 1265271287408386915L, 61 ); + map.put( 9077428346047966819L, 32 ); + map.put( 1827085004206892313L, 95 ); + map.put( 6377023652046870199L, 8 ); + map.remove( 8096564328797694553L ); + map.put( 458594253548258561L, 37 ); + map.put( 4418108647578170347L, 60 ); + map.put( 4363375305508283265L, 50 ); + map.remove( 3220719966247388754L ); + map.put( 5067121328094576685L, 86 ); + map.put( 8030171618634928529L, 9 ); + map.remove( 5790325306669462860L ); + map.remove( 1693435088303118108L ); + map.put( 1817899559164238906L, 48 ); + map.put( 2823063986711596775L, 58 ); + map.put( 5065867711051034527L, 1 ); + map.put( 6144553725832876585L, 16 ); + map.put( 6066303112518690730L, 96 ); + map.put( 1627429134135319103L, 64 ); + map.put( 2083704227957337692L, 48 ); + map.put( 5074984076240598083L, 46 ); + map.put( 273737562207470342L, 60 ); + map.put( 5065867711051034527L, 7 ); + map.put( 1425720210238734727L, 23 ); + map.put( 8840483239403421070L, 42 ); + map.put( 622393419539870960L, 66 ); + map.put( 4649317581471627693L, 84 ); + map.put( 6344284253098418581L, 10 ); + map.put( 6066303112518690730L, 14 ); + map.put( 2032224502814063026L, 72 ); + map.put( 3860451022347437817L, 26 ); + map.put( 1931469116507191845L, 30 ); + map.put( 7264376865632246862L, 81 ); + map.put( 875078333857781813L, 41 ); + map.put( 6066303112518690730L, 65 ); + map.put( 357446231240164192L, 80 ); + map.put( 90138258774469874L, 73 ); + map.put( 2550828149718879762L, 72 ); + map.put( 357446231240164192L, 17 ); + map.put( 4233359298058523722L, 83 ); + map.put( 7879882017779927485L, 33 ); + map.put( 4554977248866184403L, 64 ); + map.put( 2032224502814063026L, 11 ); + map.put( 8460476221939231932L, 65 ); + map.put( 4404294840535520232L, 58 ); + map.put( 439984342972777679L, 83 ); + map.put( 143440583901416159L, 59 ); + map.put( 6980461179076170770L, 9 ); + map.put( 4253079906814783119L, 93 ); + map.put( 6377023652046870199L, 20 ); + map.put( 2885272279767063039L, 5 ); + map.put( 1115850061381524772L, 37 ); + map.put( 4288489609244987651L, 22 ); + map.put( 1869499448099043543L, 73 ); + map.put( 2233583342469238733L, 84 ); + map.put( 8785988080128503533L, 61 ); + map.put( 7396264003126204068L, 81 ); + map.put( 6553509363155186775L, 96 ); + map.put( 1265663249510580286L, 89 ); + map.put( 8824139147632000339L, 49 ); + map.put( 8629268898854377850L, 10 ); + map.put( 6463027127151126151L, 57 ); + map.put( 2577561266405706623L, 46 ); + map.put( 2942302849662258387L, 40 ); + map.put( 2233583342469238733L, 56 ); + map.put( 7971826071187872579L, 53 ); + map.put( 1425720210238734727L, 27 ); + map.remove( 7194434791627009043L ); + map.put( 1429250394105883546L, 82 ); + map.put( 8048363335369773749L, 19 ); + map.put( 425423457410117293L, 51 ); + map.remove( 3570674569632664356L ); + map.remove( 5925614419318569326L ); + map.put( 245367449754197583L, 27 ); + map.put( 8724491045048677021L, 55 ); + map.put( 1037934857236019066L, 66 ); + map.put( 8902857048431919030L, 61 ); + map.put( 4806848030248674690L, 17 ); + map.put( 8840483239403421070L, 95 ); + map.put( 2931578375554111170L, 54 ); + map.put( 5352224688502007093L, 36 ); + map.put( 6675404627060358866L, 64 ); + map.put( 5011448804620449550L, 48 ); + map.put( 9003964541346458616L, 44 ); + map.put( 8614830761978541860L, 70 ); + map.put( 3790785290324207363L, 95 ); + map.put( 3524676886726253569L, 54 ); + map.put( 6858076293577130289L, 60 ); + map.put( 6721253107702965701L, 41 ); + map.put( 655525227420977141L, 94 ); + map.put( 2344362186561469072L, 29 ); + map.put( 6144230340727188436L, 76 ); + map.put( 6751209943070153529L, 22 ); + map.put( 5528119873376392874L, 44 ); + map.put( 6675404627060358866L, 20 ); + map.put( 6167523814676644161L, 50 ); + map.put( 4288489609244987651L, 82 ); + map.remove( 3362704467864439992L ); + map.put( 8629268898854377850L, 50 ); + map.remove( 8824139147632000339L ); + map.remove( 8563575034946766108L ); + map.put( 4391871381220263726L, 20 ); + map.remove( 6143313773038364355L ); + map.remove( 3225044803974988142L ); + map.remove( 8048363335369773749L ); + map.remove( 439984342972777679L ); + map.put( 7776019112299874624L, 8 ); + map.put( 5414055783993307402L, 13 ); + map.put( 425423457410117293L, 91 ); + map.put( 8407567928758710341L, 30 ); + map.put( 6070945099342863711L, 14 ); + map.put( 5644323748441073606L, 91 ); + map.put( 5297141920581728538L, 61 ); + map.put( 7880139640446289959L, 1 ); + map.put( 2300381985575721987L, 92 ); + map.put( 8253246663621301435L, 26 ); + map.remove( 2074764355175726009L ); + map.remove( 3823843425563676964L ); + map.put( 8314906688468605292L, 91 ); + map.put( 6864119235983684905L, 56 ); + map.put( 6610784890222945257L, 85 ); + map.put( 3790785290324207363L, 7 ); + map.put( 9077428346047966819L, 20 ); + map.put( 5594781060356781714L, 76 ); + map.put( 4288489609244987651L, 24 ); + map.put( 5427718399315377322L, 93 ); + map.put( 6858076293577130289L, 41 ); + map.put( 4233359298058523722L, 43 ); + map.put( 3058911485922749695L, 88 ); + map.remove( 1327614778938791146L ); + map.put( 4665341449948530032L, 26 ); + map.remove( 2860868006143077426L ); + map.put( 6167523814676644161L, 70 ); + map.remove( 8314906688468605292L ); + map.put( 6396314739926743170L, 25 ); + map.put( 8924527320597926970L, 40 ); + map.put( 1817899559164238906L, 84 ); + map.remove( 4391871381220263726L ); + map.put( 8850817829384121639L, 50 ); + map.put( 6513548978704592547L, 52 ); + map.remove( 6066303112518690730L ); + map.remove( 3946964103425920940L ); + map.put( 7971826071187872579L, 71 ); + map.put( 90138258774469874L, 78 ); + map.put( 8309039683334256753L, 44 ); + map.put( 327300646665050265L, 52 ); + map.put( 4239841777571533415L, 22 ); + map.put( 7391753878925882699L, 46 ); + map.put( 5987501380005333533L, 31 ); + map.put( 6734545541042861356L, 45 ); + map.remove( 6566682167801344029L ); + map.put( 4218658174275197144L, 16 ); + map.put( 4363586488886891680L, 88 ); + map.put( 8030171618634928529L, 19 ); + map.put( 6513548978704592547L, 95 ); + map.put( 6721253107702965701L, 55 ); + map.put( 2153470608693815785L, 9 ); + map.put( 5807454155419905847L, 7 ); + map.remove( 4528425347504500078L ); + map.put( 339083533777732657L, 72 ); + map.put( 5162811261582626928L, 68 ); + map.put( 5459968256561120197L, 89 ); + map.put( 946125626260258615L, 97 ); + map.put( 986286772325632801L, 26 ); + map.put( 8309039683334256753L, 74 ); + map.put( 1609193622622537433L, 84 ); + map.put( 2506727685914893570L, 9 ); + map.put( 143440583901416159L, 33 ); + map.put( 7716482408003289208L, 30 ); + map.put( 7880139640446289959L, 74 ); + map.put( 5472992709007694577L, 27 ); + map.put( 3367972495572249232L, 8 ); + map.put( 6002824320296423294L, 71 ); + map.put( 5162811261582626928L, 10 ); + map.remove( 8309039683334256753L ); + map.put( 3103455156394998975L, 1 ); + map.put( 4943074037151902792L, 38 ); + map.put( 1455801901314190156L, 98 ); + map.put( 3502583509759951230L, 22 ); + map.remove( 8464127935014315372L ); + map.put( 6858076293577130289L, 35 ); + map.put( 8487179770790306175L, 5 ); + map.put( 946125626260258615L, 85 ); + map.put( 722144778357869055L, 1 ); + map.remove( 6832604792388788147L ); + map.remove( 7879882017779927485L ); + map.put( 4636443662717865247L, 98 ); + map.put( 6950926592851406543L, 12 ); + map.put( 8536120340569832116L, 73 ); + map.put( 86730768989854734L, 66 ); + map.put( 4558683789229895837L, 26 ); + map.put( 4806848030248674690L, 11 ); + map.put( 425423457410117293L, 38 ); + map.put( 8713875164075871710L, 97 ); + map.put( 3790785290324207363L, 77 ); + map.put( 4632006356221328093L, 21 ); + map.put( 7628512490650429100L, 28 ); + map.remove( 4651124484202085669L ); + map.put( 4320012891688937760L, 22 ); + map.put( 6092264867460428040L, 86 ); + map.put( 6610784890222945257L, 71 ); + map.remove( 3515175120945606156L ); + map.put( 5787098127909281443L, 10 ); + map.put( 5057609667342409825L, 50 ); + map.put( 5903362554916539560L, 75 ); + map.remove( 5339209082212961633L ); + map.put( 3502583509759951230L, 36 ); + map.put( 4198420341072443663L, 75 ); + map.put( 5037754181090593008L, 34 ); + map.put( 39606137866137388L, 19 ); + map.remove( 622393419539870960L ); + map.put( 2783004740411041924L, 79 ); + map.put( 6232331175163415825L, 72 ); + map.put( 4367206208262757151L, 33 ); + map.remove( 5879159150292946046L ); + map.put( 722144778357869055L, 80 ); + map.put( 9006426844471489361L, 92 ); + map.put( 550025535839604778L, 32 ); + map.remove( 5855895659233120621L ); + map.put( 1455801901314190156L, 24 ); + map.put( 3860451022347437817L, 81 ); + map.put( 2672104991948169160L, 57 ); + map.remove( 3860451022347437817L ); + map.remove( 655525227420977141L ); + map.put( 2413633498546493443L, 68 ); + map.put( 4185381066643227500L, 54 ); + map.put( 1280345971255663584L, 39 ); + map.put( 5796123963544961504L, 76 ); + map.put( 1892786158672061630L, 55 ); + map.remove( 5352224688502007093L ); + map.put( 3711105805930144213L, 47 ); + map.put( 4608237982157900285L, 41 ); + map.put( 4175794211341763944L, 31 ); + map.put( 2315250912582233395L, 81 ); + map.put( 357446231240164192L, 87 ); + map.put( 4110861648946406824L, 75 ); + map.put( 6912381889380280106L, 22 ); + map.put( 6721253107702965701L, 43 ); + map.put( 8536120340569832116L, 87 ); + map.put( 9134483648483594929L, 77 ); + map.put( 9132976039160654816L, 69 ); + map.remove( 7698175804504341415L ); + map.remove( 9134483648483594929L ); + map.put( 215721718639621876L, 11 ); + map.put( 8367455298026304238L, 78 ); + map.put( 215721718639621876L, 13 ); + map.put( 1398628381776162625L, 12 ); + map.put( 3818698536247649025L, 91 ); + map.put( 146020861698406718L, 41 ); + map.put( 39606137866137388L, 93 ); + map.put( 2032224502814063026L, 29 ); + map.remove( 6363504799104250810L ); + map.put( 7198198302699040275L, 75 ); + map.put( 1659665859871881503L, 35 ); + map.put( 2032224502814063026L, 25 ); + map.put( 7006780191094382053L, 2 ); + map.put( 2626850727701928459L, 97 ); + map.put( 5371963064889126677L, 49 ); + map.put( 2777831232791546183L, 35 ); + map.remove( 1265271287408386915L ); + map.remove( 1078791602714388223L ); + map.put( 7355915493826998767L, 39 ); + map.remove( 1557741259882614531L ); + map.put( 318456745029053198L, 18 ); + map.put( 5731549637584761783L, 77 ); + map.put( 875078333857781813L, 80 ); + map.remove( 4288489609244987651L ); + map.put( 6296247210943123044L, 67 ); + map.put( 6513548978704592547L, 60 ); + map.put( 7484688824700837146L, 79 ); + map.put( 4551026293109220157L, 77 ); + map.put( 2961669147182343860L, 80 ); + map.put( 4481942776688563562L, 28 ); + map.put( 5879809531485088687L, 63 ); + map.put( 5799223884087101214L, 94 ); + map.put( 8394473765965282856L, 59 ); + map.remove( 7273585073251585620L ); + map.remove( 5518575735665118270L ); + map.put( 1946691597339845823L, 64 ); + map.put( 1191724556568067952L, 33 ); + map.remove( 1803989601564179749L ); + map.put( 7909563548070411816L, 98 ); + // WHEN/THEN + int sizeBefore = map.size(); + boolean existedBefore = map.containsKey( 5826258075197365143L ); + Integer valueBefore = map.get( 5826258075197365143L ); + Integer previous = map.put( 5826258075197365143L, 6 ); + boolean existsAfter = map.containsKey( 5826258075197365143L ); + Integer valueAfter = map.get( 5826258075197365143L ); + int sizeAfter = map.size(); + assertEquals( 199, sizeBefore, "Size before put should have been 199" ); + assertFalse( existedBefore, "5826258075197365143 should not exist before putting here" ); + assertNull( valueBefore, "value before putting should be null" ); + assertNull( previous, "value returned from putting should be null" ); + assertTrue( existsAfter, "5826258075197365143 should exist" ); + assertEquals( (Integer) 6, valueAfter, "value after putting should be 6" ); + assertEquals( 200, sizeAfter, "Size after put should have been 200" ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longIntEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongIntVisitor visitor = mock( PrimitiveLongIntVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longIntEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void intLongEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntLongMap map = Primitive.intLongMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntLongVisitor visitor = mock( PrimitiveIntLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void intLongEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntLongMap map = Primitive.intLongMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longLongEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongLongVisitor visitor; + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + visitor = mock( PrimitiveLongLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + } + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longLongEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longLongOffHeapEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongLongVisitor visitor; + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + visitor = mock( PrimitiveLongLongVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + } + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longLongOffHeapEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longObjectEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongObjectVisitor visitor = mock( PrimitiveLongObjectVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longObjectEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void intObjectEntryVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntObjectVisitor visitor = mock( PrimitiveIntObjectVisitor.class ); + + // WHEN + map.visitEntries( visitor ); + + // THEN + verify( visitor ).visited( 1, 100 ); + verify( visitor ).visited( 2, 200 ); + verify( visitor ).visited( 3, 300 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void intObjectEntryVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitEntries( ( key, value ) -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longIntKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longIntKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongIntMap map = Primitive.longIntMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longLongKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + + // WHEN + map.visitKeys( visitor ); + } + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longLongKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.longLongMap() ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longLongOffHeapKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + + // WHEN + map.visitKeys( visitor ); + } + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longLongOffHeapKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + AtomicInteger counter = new AtomicInteger(); + try ( PrimitiveLongLongMap map = Primitive.offHeapLongLongMap( GlobalMemoryTracker.INSTANCE ) ) + { + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + } + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longObjectKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longObjectKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void intObjectKeyVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + PrimitiveIntVisitor visitor = mock( PrimitiveIntVisitor.class ); + + // WHEN + map.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void intObjectKeyVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntObjectMap map = Primitive.intObjectMap(); + map.put( 1, 100 ); + map.put( 2, 200 ); + map.put( 3, 300 ); + map.put( 4, 400 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @Test + void longObjectMapValuesContainsAllValues() + { + PrimitiveLongObjectMap map = Primitive.longObjectMap(); + map.put( 1, "a" ); + map.put( 2, "b" ); + map.put( 3, "c" ); + + assertThat( map.values(), containsInAnyOrder( "a", "b", "c" ) ); + } + + @Test + void recursivePutGrowInterleavingShouldNotDropOriginalValues() + { + // List of values which causes calls to put() call grow(), which will call put() which calls grow() again + List lst = Arrays.asList( + 44988L, 44868L, 44271L, 44399L, 44502L, 44655L, 44348L, 44843L, + 44254L, 44774L, 44476L, 44664L, 44485L, 44237L, 44953L, 44468L, + 44970L, 44808L, 44527L, 44987L, 44672L, 44647L, 44467L, 44825L, + 44740L, 44220L, 44851L, 44902L, 44791L, 44416L, 44365L, 44382L, + 44885L, 44510L, 44553L, 44894L, 44288L, 44306L, 44450L, 44689L, + 44305L, 44374L, 44323L, 44493L, 44706L, 44681L, 44578L, 44723L, + 44331L, 44936L, 44289L, 44919L, 44433L, 44826L, 44757L, 44561L, + 44595L, 44612L, 44996L, 44646L, 44834L, 44314L, 44544L, 44629L, + 44357L // <-- this value will cause a grow, which during new table population will cause another grow. + ); + + verifyMapRetainsAllEntries( lst ); + } + + @Test + void recursivePutGrowInterleavingShouldNotDropOriginalValuesEvenWhenFirstGrowAddsMoreValuesAfterSecondGrow() + { + // List of values that cause recursive growth like above, but this time the first grow wants to add more values + // to the table *after* the second grow has occurred. + List lst = Arrays.asList( + 85380L, 85124L, 85252L, 85259L, 85005L, 85260L, 85132L, 85141L, + 85397L, 85013L, 85269L, 85277L, 85149L, 85404L, 85022L, 85150L, + 85029L, 85414L, 85158L, 85286L, 85421L, 85039L, 85167L, 85294L, + 85166L, 85431L, 85303L, 85046L, 85311L, 85439L, 85438L, 85184L, + 85056L, 85063L, 85320L, 85448L, 85201L, 85073L, 85329L, 85456L, + 85328L, 85337L, 85081L, 85465L, 85080L, 85208L, 85473L, 85218L, + 85346L, 85090L, 85097L, 85225L, 85354L, 85098L, 85482L, 85235L, + 85363L, 85107L, 85490L, 85115L, 85499L, 85242L, 85175L, 85371L, + 85192L // <-- this value will cause a grow, which during new table population will cause another grow. + ); + + verifyMapRetainsAllEntries( lst ); + } + + private static void verifyMapRetainsAllEntries( List lst ) + { + PrimitiveLongIntMap map = Primitive.longIntMap(); + Set set = new HashSet<>(); + for ( Long value: lst ) + { + assertThat( map.put( value, 1 ), is( -1 ) ); + assertTrue( set.add( value ) ); + } + + assertThat( map.size(), is( set.size() ) ); + for ( Long aLong: set ) + { + assertThat( map.get( aLong ), is( 1 ) ); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java new file mode 100644 index 0000000000..0da505d69c --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongObjectMapRIT.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Random; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongObjectMap; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class PrimitiveLongObjectMapRIT +{ + @Test + void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( mapFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + + fullVerification( result.getTarget(), random ); + } + } + + private static void fullVerification( Maps target, Random random ) + { + for ( Map.Entry entry: target.normalMap.entrySet() ) + { + assertTrue( target.map.containsKey( entry.getKey() ) ); + assertEquals( entry.getValue(), target.map.get( entry.getKey() ) ); + } + + for ( int i = 0; i < target.normalMap.size(); i++ ) + { + assertFalse( target.map.containsKey( randomNonExisting( random, target.normalMap ) ) ); + } + } + + private static Printable given() + { + return out -> out.println( PrimitiveLongObjectMap.class.getSimpleName() + " map = " + + Primitive.class.getSimpleName() + ".longObjectMap();" ); + } + + private static ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private static TargetFactory mapFactory() + { + return Maps::new; + } + + private static Action generateAction( Random random, Maps from ) + { + boolean anExisting = !from.normalMap.isEmpty() && random.nextInt( 3 ) == 0; + long key = anExisting ? + randomExisting( random, from.normalMap ) : + randomNonExisting( random, from.normalMap ); + Integer value = random.nextInt( 100 ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( key ); + } + + // add + return new AddAction( key, value ); + } + + private static long randomNonExisting( Random random, Map existing ) + { + while ( true ) + { + long key = Math.abs( random.nextLong() ); + if ( !existing.containsKey( key ) ) + { + return key; + } + } + } + + private static long randomExisting( Random random, Map existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.keySet().iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long key; + private final Integer value; + + AddAction( long key, Integer value ) + { + this.key = key; + this.value = value; + } + + @Override + public String apply( Maps target ) + { + Integer existingValue = target.normalMap.get( key ); + int actualSizeBefore = target.normalMap.size(); + + int sizeBefore = target.map.size(); + boolean existedBefore = target.map.containsKey( key ); + Integer valueBefore = target.map.get( key ); + Integer previous = target.map.put( key, value ); + boolean existsAfter = target.map.containsKey( key ); + Integer valueAfter = target.map.get( key ); + target.normalMap.put( key, value ); + int sizeAfter = target.map.size(); + + int actualSizeAfter = target.normalMap.size(); + boolean existing = existingValue != null; + boolean ok = + (sizeBefore == actualSizeBefore) & + (existedBefore == existing) & + (existing ? existingValue.equals( valueBefore ) : valueBefore == null) & + (existing ? previous.equals( existingValue ) : previous == null) & + (valueAfter != null && valueAfter.equals( value )) & + existsAfter & + (sizeAfter == actualSizeAfter); + return ok ? null : "" + key + ":" + value + "," + existingValue + "," + existedBefore + + "," + previous + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + Integer existingValue = source.normalMap.get( key ); + + String addition = "map.put( " + key + ", " + value + " );"; + if ( includeChecks ) + { + boolean existing = existingValue != null; + out.println( "int sizeBefore = map.size();" ); + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueBefore = map.get( %d );", key ) ); + out.println( format( "Integer previous = %s", addition ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueAfter = map.get( %d );", key ) ); + out.println( "int sizeAfter = map.size();" ); + + int actualSizeBefore = source.normalMap.size(); + out.println( format( "assertEquals( \"%s\", %d, sizeBefore );", + "Size before put should have been " + actualSizeBefore, actualSizeBefore ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + if ( existing ) + { + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, previous );", + "value returned from put should be " + existingValue, existingValue ) ); + } + else + { + out.println( format( "assertNull( \"%s\", valueBefore );", + "value before putting should be null" ) ); + out.println( format( "assertNull( \"%s\", previous );", + "value returned from putting should be null" ) ); + } + out.println( format( "assertTrue( \"%s\", existsAfter );", + key + " should exist" ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueAfter );", + "value after putting should be " + value, value ) ); + int actualSizeAfter = existing ? actualSizeBefore : actualSizeBefore + 1; + out.println( format( "assertEquals( \"%s\", %d, sizeAfter );", + "Size after put should have been " + actualSizeAfter, actualSizeAfter ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long key; + + RemoveAction( long key ) + { + this.key = key; + } + + @Override + public String apply( Maps target ) + { + Integer existingValue = target.normalMap.get( key ); + + boolean existedBefore = target.map.containsKey( key ); + Integer valueBefore = target.map.get( key ); + Integer removed = target.map.remove( key ); + boolean existsAfter = target.map.containsKey( key ); + Integer valueAfter = target.map.get( key ); + target.normalMap.remove( key ); + + boolean existing = existingValue != null; + boolean ok = + (existedBefore == existing) & + (existing ? valueBefore.equals( existingValue ) : valueBefore == null) & + (existing ? removed.equals( existingValue ) : removed == null) & + (valueAfter == null) & !existsAfter; + return ok ? null : "" + key + "," + existingValue + "," + existedBefore + + "," + removed + "," + existsAfter; + } + + @Override + public void printAsCode( Maps source, LinePrinter out, boolean includeChecks ) + { + Integer existingValue = source.normalMap.get( key ); + + String removal = "map.remove( " + key + " );"; + if ( includeChecks ) + { + boolean existing = existingValue != null; + out.println( format( "boolean existedBefore = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueBefore = map.get( %d );", key ) ); + out.println( format( "Integer removed = %s", removal ) ); + out.println( format( "boolean existsAfter = map.containsKey( %d );", key ) ); + out.println( format( "Integer valueAfter = map.get( %d );", key ) ); + + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( existing ), + key + " should " + (existing ? "" : "not ") + "exist before putting here" ) ); + if ( existing ) + { + out.println( format( "assertEquals( \"%s\", (Integer)%d, valueBefore );", + "value before should be " + existingValue, existingValue ) ); + out.println( format( "assertEquals( \"%s\", (Integer)%d, removed );", + "value returned from put should be " + existingValue, existingValue ) ); + } + else + { + out.println( format( "assertNull( \"%s\", valueBefore );", + "value before putting should be null" ) ); + out.println( format( "assertNull( \"%s\", removed );", + "value returned from putting should be null" ) ); + } + out.println( format( "assertFalse( \"%s\", existsAfter );", + key + " should not exist" ) ); + out.println( format( "assertNull( \"%s\", valueAfter );", + "value after removing should be null" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Maps implements TestResource + { + final Map normalMap = new HashMap<>(); + final PrimitiveLongObjectMap map = Primitive.longObjectMap(); + + @Override + public String toString() + { + return map.toString(); + } + + @Override + public void close() + { + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java new file mode 100644 index 0000000000..6fd3a62ecb --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetRIT.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Random; +import java.util.Set; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.test.randomized.Action; +import org.neo4j.test.randomized.LinePrinter; +import org.neo4j.test.randomized.Printable; +import org.neo4j.test.randomized.RandomizedTester; +import org.neo4j.test.randomized.RandomizedTester.ActionFactory; +import org.neo4j.test.randomized.RandomizedTester.TargetFactory; +import org.neo4j.test.randomized.Result; +import org.neo4j.test.randomized.TestResource; + +import static java.lang.String.format; +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +class PrimitiveLongSetRIT +{ + @Test + void thoroughlyTestIt() + { + long endTime = currentTimeMillis() + SECONDS.toMillis( 5 ); + while ( currentTimeMillis() < endTime ) + { + long seed = currentTimeMillis(); + final Random random = new Random( seed ); + int max = random.nextInt( 10_000 ) + 100; + RandomizedTester actions = + new RandomizedTester<>( setFactory(), actionFactory( random ) ); + + Result result = actions.run( max ); + if ( result.isFailure() ) + { + System.out.println( "Found failure at " + result ); + actions.testCaseWriter( "shouldOnlyContainAddedValues", given() ).print( System.out ); + System.out.println( "Actually, minimal reproducible test of that is..." ); + actions.findMinimalReproducible().testCaseWriter( "shouldOnlyContainAddedValues", + given() ).print( System.out ); + fail( "Failed, see printed test case for how to reproduce. Seed:" + seed ); + } + fullVerification( result.getTarget(), random ); + } + } + + private static void fullVerification( Sets target, Random random ) + { + for ( Long value: target.normalSet ) + { + assertTrue( target.set.contains( value ) ); + } + + for ( int i = 0; i < target.normalSet.size(); i++ ) + { + assertFalse( target.set.contains( randomNonExisting( random, target.normalSet ) ) ); + } + } + + private static Printable given() + { + return out -> out.println( PrimitiveLongSet.class.getSimpleName() + " set = " + + Primitive.class.getSimpleName() + ".longSet();" ); + } + + private static ActionFactory actionFactory( final Random random ) + { + return from -> generateAction( random, from ); + } + + private static TargetFactory setFactory() + { + return Sets::new; + } + + private static Action generateAction( Random random, Sets from ) + { + boolean anExisting = !from.normalSet.isEmpty() && random.nextInt( 3 ) == 0; + long value = anExisting ? + randomExisting( random, from.normalSet ) : + randomNonExisting( random, from.normalSet ); + + int typeOfAction = random.nextInt( 5 ); + if ( typeOfAction == 0 ) + { // remove + return new RemoveAction( value ); + } + + // add + return new AddAction( value ); + } + + private static long randomNonExisting( Random random, Set existing ) + { + while ( true ) + { + long value = Math.abs( random.nextLong() ); + if ( !existing.contains( value ) ) + { + return value; + } + } + } + + private static long randomExisting( Random random, Set existing ) + { + int index = random.nextInt( existing.size() ) + 1; + Iterator iterator = existing.iterator(); + long value = 0; + for ( int i = 0; i < index; i++ ) + { + value = iterator.next(); + } + return value; + } + + private static class AddAction implements Action + { + private final long value; + + AddAction( long value ) + { + this.value = value; + } + + @Override + public String apply( Sets target ) + { + try + { + boolean alreadyExisting = target.normalSet.contains( value ); + + PrimitiveLongSet set = target.set; + boolean existedBefore = set.contains( value ); + boolean added = set.add( value ); + boolean existsAfter = set.contains( value ); + target.normalSet.add( value ); + + boolean ok = (existedBefore == alreadyExisting) & (added == !alreadyExisting) & existsAfter; + return ok ? null : "" + value + alreadyExisting + "," + existedBefore + "," + added + "," + existsAfter; + } + catch ( Exception e ) + { + return "exception:" + e.getMessage(); + } + } + + @Override + public void printAsCode( Sets source, LinePrinter out, boolean includeChecks ) + { + boolean alreadyExisting = source.normalSet.contains( value ); + String addition = "set.add( " + value + "L );"; + if ( includeChecks ) + { + out.println( format( "boolean existedBefore = set.contains( %dL );", value ) ); + out.println( format( "boolean added = %s", addition ) ); + out.println( format( "boolean existsAfter = set.contains( %dL );", value ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "exist before adding here" ) ); + out.println( format( "assert%s( \"%s\", added );", capitilize( !alreadyExisting ), + value + " should " + (!alreadyExisting ? "" : "not ") + "be reported as added here" ) ); + out.println( format( "assertTrue( \"%s\", existsAfter );", value + " should exist" ) ); + } + else + { + out.println( addition ); + } + } + } + + private static class RemoveAction implements Action + { + private final long value; + + RemoveAction( long value ) + { + this.value = value; + } + + @Override + public String apply( Sets target ) + { + try + { + boolean alreadyExisting = target.normalSet.contains( value ); + PrimitiveLongSet set = target.set; + boolean existedBefore = set.contains( value ); + boolean removed = set.remove( value ); + boolean existsAfter = set.contains( value ); + target.normalSet.remove( value ); + + boolean ok = (existedBefore == alreadyExisting) & (removed == alreadyExisting) & !existsAfter; + return ok ? null : "" + value + alreadyExisting + "," + existedBefore + "," + removed + "," + existsAfter; + } + catch ( Exception e ) + { + return "exception: " + e.getMessage(); + } + } + + @Override + public void printAsCode( Sets source, LinePrinter out, boolean includeChecks ) + { + boolean alreadyExisting = source.normalSet.contains( value ); + String removal = "set.remove( " + value + "L );"; + if ( includeChecks ) + { + out.println( format( "boolean existedBefore = set.contains( %dL );", value ) ); + out.println( format( "boolean removed = %s", removal ) ); + out.println( format( "boolean existsAfter = set.contains( %dL );", value ) ); + out.println( format( "assert%s( \"%s\", existedBefore );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "exist before removing here" ) ); + out.println( format( "assert%s( \"%s\", removed );", capitilize( alreadyExisting ), + value + " should " + (alreadyExisting ? "" : "not ") + "be reported as removed here" ) ); + out.println( format( "assertFalse( \"%s\", existsAfter );", + value + " should not exist" ) ); + } + else + { + out.println( removal ); + } + } + } + + private static String capitilize( boolean bool ) + { + String string = Boolean.valueOf( bool ).toString(); + return string.substring( 0, 1 ).toUpperCase() + string.substring( 1 ).toLowerCase(); + } + + private static class Sets implements TestResource + { + final Set normalSet = new HashSet<>(); + final PrimitiveLongSet set = Primitive.longSet(); + + @Override + public void close() + { + set.close(); + } + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java new file mode 100644 index 0000000000..7ea0691588 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/collection/primitive/hopscotch/PrimitiveLongSetTest.java @@ -0,0 +1,441 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.collection.primitive.hopscotch; + +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.neo4j.collection.primitive.Primitive; +import org.neo4j.collection.primitive.PrimitiveIntSet; +import org.neo4j.collection.primitive.PrimitiveIntVisitor; +import org.neo4j.collection.primitive.PrimitiveLongSet; +import org.neo4j.collection.primitive.PrimitiveLongVisitor; +import org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.Monitor; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.neo4j.collection.primitive.Primitive.VALUE_MARKER; +import static org.neo4j.collection.primitive.hopscotch.HopScotchHashingAlgorithm.NO_MONITOR; + +class PrimitiveLongSetTest +{ + @Test + void shouldContainAddedValues_generated_1() + { + // GIVEN + PrimitiveLongSet set = newSet( 15 ); + Set expectedValues = new HashSet<>(); + long[] valuesToAdd = new long[]{ + 1207043189, + 380713862, + 1902858197, + 1996873101, + 1357024628, + 1044248801, + 1558157493, + 2040311008, + 2017660098, + 1332670047, + 663662790, + 2063747422, + 1554358949, + 1761477445, + 1141526838, + 1698679618, + 1279767067, + 508574, + 2071755904 + }; + for ( long key: valuesToAdd ) + { + set.add( key ); + expectedValues.add( key ); + } + + // WHEN/THEN + boolean existedBefore = set.contains( 679990875 ); + boolean added = set.add( 679990875 ); + boolean existsAfter = set.contains( 679990875 ); + assertFalse( existedBefore, "679990875 should not exist before adding here" ); + assertTrue( added, "679990875 should be reported as added here" ); + assertTrue( existsAfter, "679990875 should exist" ); + expectedValues.add( 679990875L ); + + final Set visitedKeys = new HashSet<>(); + set.visitKeys( value -> + { + assertTrue( visitedKeys.add( value ) ); + return false; + } ); + assertEquals( expectedValues, visitedKeys ); + } + + @Test + void shouldContainAddedValues_generated_6() + { + // GIVEN + PrimitiveLongSet set = newSet( 11 ); + set.add( 492321488 ); + set.add( 877087251 ); + set.add( 1809668113 ); + set.add( 1766034186 ); + set.add( 1879253467 ); + set.add( 669295491 ); + set.add( 176011165 ); + set.add( 1638959981 ); + set.add( 1093132636 ); + set.add( 6133241 ); + set.add( 486112773 ); + set.add( 205218385 ); + set.add( 1756491867 ); + set.add( 90390732 ); + set.add( 937266036 ); + set.add( 1269020584 ); + set.add( 521469166 ); + set.add( 1314928747 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 2095121629 ); + boolean added = set.add( 2095121629 ); + boolean existsAfter = set.contains( 2095121629 ); + assertFalse( existedBefore, "2095121629 should not exist before adding here" ); + assertTrue( added, "2095121629 should be reported as added here" ); + assertTrue( existsAfter, "2095121629 should exist" ); + } + + @Test + void shouldContainAddedValues_generated_4() + { + // GIVEN + PrimitiveLongSet set = newSet( 9 ); + set.add( 1934106304 ); + set.add( 783754072 ); + set.remove( 1934106304 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 783754072 ); + boolean added = set.add( 783754072 ); + boolean existsAfter = set.contains( 783754072 ); + assertTrue( existedBefore, "783754072 should exist before adding here" ); + assertFalse( added, "783754072 should not be reported as added here" ); + assertTrue( existsAfter, "783754072 should exist" ); + } + + @Test + void shouldOnlyContainAddedValues_generated_8() + { + // GIVEN + PrimitiveLongSet set = newSet( 7 ); + set.add( 375712513 ); + set.remove( 1507941820 ); + set.add( 671750317 ); + set.remove( 1054641019 ); + set.add( 671750317 ); + set.add( 1768202223 ); + set.add( 1768202223 ); + set.add( 1927780165 ); + set.add( 2139399764 ); + set.remove( 1243370828 ); + set.add( 1768202223 ); + set.add( 1335041891 ); + set.remove( 1578984313 ); + set.add( 1227954408 ); + set.remove( 946917826 ); + set.add( 1768202223 ); + set.add( 375712513 ); + set.add( 1668515054 ); + set.add( 401047579 ); + set.add( 33226244 ); + set.add( 126791689 ); + set.add( 401047579 ); + set.add( 1963437853 ); + set.add( 1739617766 ); + set.add( 671750317 ); + set.add( 401047579 ); + set.add( 789094467 ); + set.add( 1291421506 ); + set.add( 1694968582 ); + set.add( 1508353936 ); + + // WHEN/THEN + boolean existedBefore = set.contains( 1739617766 ); + boolean added = set.add( 1739617766 ); + boolean existsAfter = set.contains( 1739617766 ); + assertTrue( existedBefore, "1739617766 should exist before adding here" ); + assertFalse( added, "1739617766 should not be reported as added here" ); + assertTrue( existsAfter, "1739617766 should exist" ); + } + + @Test + void shouldContainReallyBigLongValue() + { + // GIVEN + PrimitiveLongSet set = newSet( 10 ); + set.add( 7416509207113022571L ); + + // WHEN/THEN + boolean existedBefore = set.contains( 7620037383187366331L ); + boolean added = set.add( 7620037383187366331L ); + boolean existsAfter = set.contains( 7620037383187366331L ); + assertFalse( existedBefore, "7620037383187366331 should not exist before adding here" ); + assertTrue( added, "7620037383187366331 should be reported as added here" ); + assertTrue( existsAfter, "7620037383187366331 should exist" ); + } + + @Test + void shouldOnlyContainAddedValues() + { + // GIVEN + PrimitiveLongSet set = newSet( 13 ); + set.add( 52450040186687566L ); + set.add( 52450040186687566L ); + set.add( 5165002753277288833L ); + set.add( 4276883133717080762L ); + set.add( 5547940863757133161L ); + set.add( 8933830774911919116L ); + set.add( 3298254474623565974L ); + set.add( 3366017425691021883L ); + set.add( 8933830774911919116L ); + set.add( 2962608069916354604L ); + set.add( 3366017425691021883L ); + set.remove( 4008464697042048519L ); + set.add( 5547940863757133161L ); + set.add( 52450040186687566L ); + set.add( 4276883133717080762L ); + set.remove( 3298254474623565974L ); + set.remove( 180852386934131061L ); + set.add( 4835176885665539239L ); + set.add( 52450040186687566L ); + set.add( 4591251124405056753L ); + set.add( 5165002753277288833L ); + set.add( 8933830774911919116L ); + set.remove( 3458250832356869483L ); + set.add( 3038543946711308923L ); + set.add( 8743060827282266460L ); + set.add( 5771902951077476377L ); + set.add( 4591251124405056753L ); + set.add( 4835176885665539239L ); + set.remove( 4827343064671369647L ); + set.add( 1533535091190658734L ); + set.remove( 7125666881901305989L ); + set.add( 1533535091190658734L ); + set.add( 52450040186687566L ); + set.remove( 1333521853804287175L ); + set.add( 2962608069916354604L ); + set.add( 5914630622072544054L ); + set.add( 52450040186687566L ); + set.add( 8933830774911919116L ); + set.add( 6198968672674664718L ); + set.add( 6239021001199390909L ); + set.add( 6563452500080365738L ); + set.add( 6128819131542184648L ); + set.add( 5914630622072544054L ); + set.add( 7024933384543504364L ); + set.remove( 3949644814017615281L ); + set.add( 3459376060749741528L ); + set.add( 3201250389951283395L ); + set.add( 4463681497523421181L ); + set.add( 4304197328678536531L ); + set.remove( 4559066538220393098L ); + set.add( 2870119173652414003L ); + set.add( 4048902329274369372L ); + set.add( 3366017425691021883L ); + set.remove( 1092409052848583664L ); + set.add( 7024933384543504364L ); + set.add( 4276883133717080762L ); + set.add( 5914630622072544054L ); + set.add( 4048902329274369372L ); + set.add( 4304197328678536531L ); + set.add( 4151178923662618318L ); + set.remove( 51389524801735953L ); + set.add( 5371788772386487501L ); + set.remove( 8933830774911919116L ); + set.add( 4928410670964886834L ); + set.add( 8306393274966855450L ); + set.add( 2870119173652414003L ); + set.add( 8281622709908651825L ); + set.remove( 9194058056102544672L ); + set.remove( 5547940863757133161L ); + set.add( 9184590238993521817L ); + set.add( 5085293141623130492L ); + set.add( 5633993155928642090L ); + set.remove( 8794875254017117580L ); + set.add( 5894404415376700909L ); + set.add( 4835176885665539239L ); + set.remove( 8743060827282266460L ); + set.remove( 3460096065015553722L ); + set.remove( 3296380689310185627L ); + set.add( 337242488691685550L ); + set.add( 6239021001199390909L ); + set.add( 9104240733803011297L ); + set.add( 807326424150812437L ); + set.add( 3336115330297894183L ); + set.add( 1788796898879121715L ); + set.add( 5756965080438171769L ); + set.remove( 4366313798399763194L ); + set.add( 6198968672674664718L ); + set.add( 486897301084183614L ); + set.add( 2870119173652414003L ); + set.add( 5085293141623130492L ); + set.add( 5771902951077476377L ); + set.remove( 6563452500080365738L ); + set.add( 5347453991851285676L ); + set.add( 7437999035528158926L ); + set.add( 3223908005448803428L ); + set.add( 4300856565210203390L ); + set.remove( 4732570527126410147L ); + set.add( 2180591071166584277L ); + set.add( 5160374384234262648L ); + set.remove( 5165002753277288833L ); + set.add( 4463681497523421181L ); + set.add( 7360196143740041480L ); + set.add( 4928410670964886834L ); + set.add( 807326424150812437L ); + set.remove( 4069279832998820447L ); + set.remove( 337242488691685550L ); + set.add( 3201250389951283395L ); + set.add( 4012293068834101219L ); + set.add( 2333643358471038273L ); + set.add( 1158824602601458449L ); + set.remove( 3906518453155830597L ); + set.add( 7402912598585277900L ); + set.add( 6556025329057634951L ); + set.add( 6684709657047103197L ); + set.remove( 3448774195820272496L ); + set.add( 715736913341007544L ); + set.add( 9104240733803011297L ); + + // WHEN/THEN + boolean existedBefore = set.contains( 1103190229303827372L ); + boolean added = set.add( 1103190229303827372L ); + boolean existsAfter = set.contains( 1103190229303827372L ); + assertFalse( existedBefore, "1103190229303827372 should not exist before adding here" ); + assertTrue( added, "1103190229303827372 should be reported as added here" ); + assertTrue( existsAfter, "1103190229303827372 should exist" ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void longVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveLongSet set = Primitive.longSet(); + set.add( 1 ); + set.add( 2 ); + set.add( 3 ); + PrimitiveLongVisitor visitor = mock( PrimitiveLongVisitor.class ); + + // WHEN + set.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void longVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntSet map = Primitive.intSet(); + map.add( 1 ); + map.add( 2 ); + map.add( 3 ); + map.add( 4 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @SuppressWarnings( "unchecked" ) + @Test + void intVisitorShouldSeeAllEntriesIfItDoesNotBreakOut() + { + // GIVEN + PrimitiveIntSet set = Primitive.intSet(); + set.add( 1 ); + set.add( 2 ); + set.add( 3 ); + PrimitiveIntVisitor visitor = mock( PrimitiveIntVisitor.class ); + + // WHEN + set.visitKeys( visitor ); + + // THEN + verify( visitor ).visited( 1 ); + verify( visitor ).visited( 2 ); + verify( visitor ).visited( 3 ); + verifyNoMoreInteractions( visitor ); + } + + @Test + void intVisitorShouldNotSeeEntriesAfterRequestingBreakOut() + { + // GIVEN + PrimitiveIntSet map = Primitive.intSet(); + map.add( 1 ); + map.add( 2 ); + map.add( 3 ); + map.add( 4 ); + final AtomicInteger counter = new AtomicInteger(); + + // WHEN + map.visitKeys( value -> counter.incrementAndGet() > 2 ); + + // THEN + assertThat( counter.get(), is( 3 ) ); + } + + @Test + void shouldHandleEmptySet() + { + // GIVEN + PrimitiveLongSet set = Primitive.longSet( 0 ); + + // THEN + assertFalse( set.contains( 564 ) ); + } + + private static PrimitiveLongHashSet newSet( int h ) + { + return newSet( h, NO_MONITOR ); + } + + private static PrimitiveLongHashSet newSet( int h, Monitor monitor ) + { + return new PrimitiveLongHashSet( + new LongKeyTable<>( h, VALUE_MARKER ), VALUE_MARKER, monitor ); + } +} diff --git a/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java new file mode 100644 index 0000000000..ee8ee68053 --- /dev/null +++ b/src/test/resources/oracle/commits/neo4j-b44c62bcdd6f7218bc97dae183ea0f6587bacd29/community/legacy/src/test/java/org/neo4j/test/randomized/PrintStreamLinePrinter.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2002-2018 "Neo4j," + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Neo4j is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package org.neo4j.test.randomized; + +import java.io.PrintStream; + +public class PrintStreamLinePrinter implements LinePrinter +{ + private final PrintStream out; + private final int indentation; + + PrintStreamLinePrinter( PrintStream out, int indentation ) + { + this.out = out; + this.indentation = indentation; + } + + @Override + public void println( String line ) + { + for ( int i = 0; i < indentation; i++ ) + { + out.print( " " ); + } + out.println( line ); + } + + @Override + public LinePrinter indent() + { + return new PrintStreamLinePrinter( out, indentation + 1 ); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java new file mode 100644 index 0000000000..3004d2f2d1 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java @@ -0,0 +1,57 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +public class TestAnnotationPOJO { + private String terms = + "" + + "" + + "" + + "" + + "" + + " " + + " " + + "Terms describing monetary amounts and measured quantities " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" + + ""; + + @Test + public void TestSimpleXMLConverted() throws JsonParseException, JsonMappingException, IOException { + JacksonXmlModule module = new JacksonXmlModule(); + module.setDefaultUseWrapper(false); + XmlMapper xmlMapper = new XmlMapper(module); + + Edmx act = xmlMapper.readValue(terms, Edmx.class); + assertNotNull(act.getDataService()); + + Schema[] actSchemas = act.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + + List actTerms = actSchemas[0].getTerms(); + assertEquals(3, actTerms.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java new file mode 100644 index 0000000000..c443b098aa --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class TestSchemaReader { + private SchemaReader cut; + + @Before + public void setup() { + cut = new SchemaReader(); + } + + @Test + public void TestGetNamespaceFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals("Org.OData.Core.V1", schema.getNamespace()); + } + + @Test + public void TestGetAliasFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals("Core", schema.getAlias()); + } + + @Test + public void TestGetTermsFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(15, schema.getTerms().size()); + } + + @Test + public void TestGetTypeDefinitionFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(1, schema.getTypeDefinitions().size()); + assertNotNull(schema.getTypeDefinition("Tag")); + assertEquals("Edm.Boolean", schema.getTypeDefinition("Tag").getUnderlyingType()); + } + + @Test + public void TestGetEnumSchemaFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(1, schema.getEnumTypes().size()); + assertNotNull(schema.getEnumType("Permission")); + assertEquals(3, schema.getEnumType("Permission").getMembers().size()); + assertEquals("3", schema.getEnumType("Permission").getMember("ReadWrite").getValue()); + } + + @Test(expected = ODataJPAModelException.class) + public void TestThrowsExceptionOnUnknownPath() throws IOException, ODataJPAModelException { + + cut.getSchemas("annotations/Org.OData.Core.V2.xml"); + } + + @Test(expected = IOException.class) + public void TestThrowsExceptionOnEmptyXML() throws IOException, ODataJPAModelException { + + cut.getSchemas("annotations/empty.xml"); + } + +// csdlSchema.setEnumTypes(asEnumTypes()); +// csdlSchema.setComplexTypes(asComplexTypes()); +// csdlSchema.setTypeDefinitions(asTypeDefinitions()); +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java new file mode 100644 index 0000000000..af1d2f9ad9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java @@ -0,0 +1,95 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.provider.CsdlTerm; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + +public class TestTermReader { + private TermReader cut; + + @Before + public void setup() { + cut = new TermReader(); + } + + @Test + public void TestReadFromResource() throws JsonParseException, JsonMappingException, IOException { + Edmx actEdmx = cut.readFromResource("annotations/Org.OData.Measures.V1.xml"); + assertNotNull(actEdmx); + assertNotNull(actEdmx.getDataService()); + + Schema[] actSchemas = actEdmx.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + assertEquals("Org.OData.Measures.V1", actSchemas[0].getNamespace()); + } + + @Test + public void TestGetTermsOneSchemaFromPath() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + Map terms = act.get("Org.OData.Core.V1"); + assertEquals(15, terms.size()); + } + + @Test + public void TestGetAppliesTo() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + Map terms = act.get("Org.OData.Core.V1"); + CsdlTerm term = terms.get("IsLanguageDependent"); + assertEquals(2, term.getAppliesTo().size()); + assertTrue("Term".equals(term.getAppliesTo().get(0)) || "Term".equals(term.getAppliesTo().get(1))); + assertTrue("Property".equals(term.getAppliesTo().get(0)) || "Property".equals(term.getAppliesTo().get(1))); + } + + @Test + public void TestGetTermsTwoSchemaFromPath() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.Olingo.Test.V1.xml"); + assertNotNull(act.get("Org.OData.Measures.V1")); + assertNotNull(act.get("Org.OData.Capabilities.V1")); + } + + // TODO This test may not run because of proxy setting problems!! -> find alternative for Integration tests + @Ignore + @Test + public void TestReadFromURI() throws URISyntaxException, JsonParseException, JsonMappingException, + MalformedURLException, IOException { + URI uri = new URI("http://docs.oasis-open.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"); + Edmx actEdmx = cut.readFromURI(uri); + assertNotNull(actEdmx); + assertNotNull(actEdmx.getDataService()); + + Schema[] actSchemas = actEdmx.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + assertEquals("Org.OData.Core.V1", actSchemas[0].getNamespace()); + } + + // TODO This test may not run because of proxy setting problems!! -> find alternative for Integration tests + @Ignore + @Test + public void TestGetTermsOneSchemaFromURI() throws URISyntaxException, JsonParseException, JsonMappingException, + MalformedURLException, IOException { + URI uri = new URI("http://docs.oasis-open.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"); + Map> act; + act = cut.getTerms(uri); + assertNotNull(act.get("Org.OData.Core.V1")); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java new file mode 100644 index 0000000000..8a50f0f2a7 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java @@ -0,0 +1,128 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.exception; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Locale; + +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration; + +public class TestODataJPAMessageTextBuffer { + private static String BUNDLE_NAME = "test-i18n"; + private ODataJPAMessageTextBuffer cut; + + @Before + public void setup() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME); + } + + @Test + public void checkDefaultLocale() { + assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage()); + } + + @Test + public void checkSetLocaleGerman() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY); + assertEquals("de", cut.getLocale().getLanguage()); + } + + @Test + public void checkSetLocaleReset() { + // Set first to German + checkSetLocaleGerman(); + // Then reset to default + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME); + assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage()); + } + + @Test + public void checkGetDefaultLocaleText() { + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkGetGermanText() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + // %1$s + @Test + public void checkGetTextWithParameter() { + String act = cut.getText(this, "SECOND_MESSAGE", "Hugo", "Willi"); + assertEquals("Hugo looks for Willi", act); + } + + @Test + public void checkSetLocalesNull() { + Enumeration locales = null; + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesRestDefaultWithNull() { + // First set to German + checkSetLocaleGerman(); + // Then reset default + Enumeration locales = null; + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesRestDefaultWithEmpty() { + // First set to German + checkSetLocaleGerman(); + // Then reset default + Enumeration locales = new LocaleEnumeration(new ArrayList()); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesFirstMatches() { + + ArrayList localesList = new ArrayList(); + localesList.add(Locale.GERMAN); + localesList.add(Locale.CANADA_FRENCH); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + @Test + public void checkSetLocalesSecondMatches() { + + ArrayList localesList = new ArrayList(); + localesList.add(Locale.CANADA_FRENCH); + localesList.add(Locale.GERMAN); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + @Test + public void checkSetLocalesNonMatches() { + + ArrayList localesList = new ArrayList(); + localesList.add(Locale.CANADA_FRENCH); + localesList.add(Locale.SIMPLIFIED_CHINESE); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java new file mode 100644 index 0000000000..73d92da76a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java @@ -0,0 +1,163 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Locale; + +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAException; +import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration; + +public class TestODataJPAModelException { + private static String BUNDLE_NAME = "test-i18n"; + + @Test + public void checkTextInDefaultLocale() { + try { + RaiseExeption(); + } catch (ODataJPAException e) { + assertEquals("An English message", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextInGerman() { + try { + ArrayList localesList = new ArrayList(); + localesList.add(Locale.GERMAN); + Enumeration locales = new LocaleEnumeration(localesList); + TestException.setLocales(locales); + RaiseExeption(); + } catch (ODataJPAException e) { + assertEquals("Ein deutscher Text", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextInDefaultLocaleWithParameter() { + try { + RaiseExeptionParam(); + } catch (ODataJPAException e) { + assertEquals("Willi looks for Hugo", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextOnlyCause() { + try { + RaiseExeptionCause(); + } catch (ODataJPAException e) { + assertEquals("Test text from cause", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextIdAndCause() { + try { + RaiseExeptionIDCause(); + } catch (ODataJPAException e) { + assertEquals("An English message", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextIdAndCauseAndParameter() { + try { + RaiseExeptionIDCause("Willi", "Hugo"); + } catch (ODataJPAException e) { + assertEquals("Willi looks for Hugo", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextNullId() { + try { + RaiseEmptyIDExeption(); + } catch (ODataJPAException e) { + assertEquals("No message text found", e.getMessage()); + return; + } + fail(); + } + + private void RaiseExeptionIDCause(String... params) throws TestException { + try { + raiseNullPointer(); + } catch (NullPointerException e) { + if (params.length == 0) + throw new TestException("FIRST_MESSAGE", e); + else + throw new TestException("SECOND_MESSAGE", e, params); + } + } + + private void RaiseExeptionCause() throws ODataJPAException { + try { + raiseNullPointer(); + } catch (NullPointerException e) { + throw new TestException(e); + } + } + + private void raiseNullPointer() throws NullPointerException { + throw new NullPointerException("Test text from cause"); + } + + private void RaiseExeptionParam() throws ODataJPAException { + throw new TestException("SECOND_MESSAGE", "Willi", "Hugo"); + } + + private void RaiseExeption() throws ODataJPAException { + throw new TestException("FIRST_MESSAGE"); + } + + private void RaiseEmptyIDExeption() throws ODataJPAException { + throw new TestException(""); + } + + private class TestException extends ODataJPAException { + + private static final long serialVersionUID = 1L; + + public TestException(String id) { + super(id); + } + + public TestException(String id, String... params) { + super(id, params); + } + + public TestException(Throwable e) { + super(e); + } + + public TestException(String id, Throwable e) { + super(id, e); + } + + public TestException(String id, Throwable e, String[] params) { + super(id, e, params); + } + + @Override + protected String getBundleName() { + return BUNDLE_NAME; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java new file mode 100644 index 0000000000..09cda2a483 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java @@ -0,0 +1,74 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoActions; + +public class TestIntermediateActionFactory extends TestMappingRoot { + private TestHelper helper; + + private Reflections reflections; + private IntermediateActionFactory cut; + private Set> javaActions; + + @Before + public void setUp() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + + reflections = mock(Reflections.class); + cut = new IntermediateActionFactory(); + javaActions = new HashSet>(); + when(reflections.getSubTypesOf(ODataAction.class)).thenReturn(javaActions); + } + + @Test + public void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException { + Reflections r = null; + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), r, helper.schema)); + } + + @Test + public void checkReturnEmptyMapIfNoJavaFunctionsFound() throws ODataJPAModelException { + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), reflections, helper.schema)); + } + + @Test + public void checkReturnMapWithOneIfOneJavaFunctionsFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaOneAction.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(1, act.size()); + } + + @Test + public void checkReturnMapWithTwoIfTwoJavaFunctionsFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaTwoActions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(2, act.size()); + } + + @Test + public void checkReturnMapWithWithJavaFunctionsFromTwoClassesFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaOneAction.class); + javaActions.add(ExampleJavaTwoActions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(3, act.size()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java new file mode 100644 index 0000000000..426b92a720 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java @@ -0,0 +1,160 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import javax.persistence.metamodel.ManagedType; +import javax.persistence.metamodel.PluralAttribute; +import javax.persistence.metamodel.Type.PersistenceType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateCollectionProperty extends TestMappingRoot { + private IntermediateCollectionProperty cut; + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + private JPAEdmNameBuilder nameBuilder; + private PluralAttribute jpaAttribute; + private ManagedType managedType; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + jpaAttribute = mock(PluralAttribute.class); + managedType = mock(ManagedType.class); + } + + @SuppressWarnings("unchecked") + @Test + public void checkSimpleCollectionPropertyType() throws ODataJPAModelException { + when(jpaAttribute.getName()).thenReturn("Text"); + @SuppressWarnings("rawtypes") + javax.persistence.metamodel.Type type = mock(javax.persistence.metamodel.Type.class); + when(type.getPersistenceType()).thenReturn(PersistenceType.BASIC); + when(type.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + when(jpaAttribute.getElementType()).thenReturn(type); + when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer>() { + @Override + public ManagedType answer(InvocationOnMock invocation) throws Throwable { + return managedType; + } + }); + when(managedType.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Person.class; + } + }); + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return List.class; + } + }); + cut = new IntermediateCollectionProperty(nameBuilder, jpaAttribute, helper.schema, helper.schema.getEntityType( + Organization.class)); + assertEquals("Edm.String", cut.getEdmItem().getType()); + assertEquals(String.class, cut.getType()); + } + + @Test + public void checkGetProptertyComplexType() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + assertEquals(PUNIT_NAME + ".InhouseAddress", property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyDBFieldName() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Organization.class), "comment"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class)); + assertEquals("\"Text\"", property.getDBFieldName()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + + IntermediateSimpleProperty.setPostProcessor(processor); + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Organization.class), "comment"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class)); + property.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(property, ORG_CANONICAL_NAME); + } + + @Test + public void checkGetPropertyReturnsAnnotation() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + + List annotations = property.getEdmItem().getAnnotations(); + assertEquals(1, property.getEdmItem().getAnnotations().size()); + assertTrue(annotations.get(0).getExpression().isConstant()); + } + + @Test + public void checkGetDeepComplexPropertyReturnsExternalName() throws ODataJPAModelException { + + final IntermediateStructuredType st = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getComplexType("CollectionSecondLevelComplex"), helper.schema); + for (final JPACollectionAttribute collection : st.getDeclaredCollectionAttributes()) { + if (collection.getInternalName().equals("comment")) { + assertEquals("Comment", collection.asAssociation().getAlias()); + } + } + + final IntermediateStructuredType stst = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getComplexType("CollectionFirstLevelComplex"), helper.schema); + for (final JPAPath collection : stst.getCollectionAttributesPath()) { + if (collection.getLeaf().getInternalName().equals("comment")) { + assertEquals("SecondLevel/Comment", collection.getAlias()); + } + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java new file mode 100644 index 0000000000..745fc29e79 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java @@ -0,0 +1,265 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EmbeddableType; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; + +public class TestIntermediateComplexType extends TestMappingRoot { + private Set> etList; + private IntermediateSchema schema; + + @Before + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + etList = emf.getMetamodel().getEmbeddables(); + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), mock(Reflections.class)); + + } + + @Test + public void checkComplexTypeCanBeCreated() throws ODataJPAModelException { + + new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType("CommunicationData"), schema); + } + + private EmbeddableType getEmbeddedableType(String typeName) { + for (EmbeddableType embeddableType : etList) { + if (embeddableType.getJavaType().getSimpleName().equals(typeName)) { + return embeddableType; + } + } + return null; + } + + @Test + public void checkGetAllProperties() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals("Wrong number of entities", 4, ct.getEdmItem().getProperties().size()); + } + + @Test + public void checkGetPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertNotNull(ct.getEdmItem().getProperty("LandlinePhoneNumber")); + } + + @Test + public void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals("LandlinePhoneNumber", ct.getEdmItem().getProperty("LandlinePhoneNumber").getName()); + } + + @Test + public void checkGetPropertyIsNullable() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + // In case nullable = true, nullable is not past to $metadata, as this is the default + assertTrue(ct.getEdmItem().getProperty("POBox").isNullable()); + } + + @Test + public void checkGetAllNaviProperties() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals("Wrong number of entities", 1, ct.getEdmItem().getNavigationProperties().size()); + } + + @Test + public void checkGetNaviPropertyByNameNotNull() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName()); + } + + @Test + public void checkGetNaviPropertyByNameRightEntity() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals("AdministrativeDivision", ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName()); + } + + @Test + public void checkGetPropertiesSkipIgnored() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals("Wrong number of entities", 3, ct.getEdmItem().getProperties().size()); + } + + @Test + public void checkGetDescriptionPropertyManyToOne() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getProperty("CountryName")); + } + + @Test + public void checkGetDescriptionPropertyManyToMany() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getProperty("RegionName")); + } + + @Test + public void checkDescriptionPropertyType() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + ct.getEdmItem(); + assertTrue(ct.getProperty("countryName") instanceof IntermediateDescriptionProperty); + } + + @Test + public void checkGetPropertyOfNestedComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotNull(ct.getPath("Created/By")); + } + + @Test + public void checkGetPropertyDBName() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals("\"Address.PostOfficeBox\"", ct.getPath("POBox").getDBFieldName()); + } + + @Test + public void checkGetPropertyDBNameOfNestedComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertEquals("\"CreatedBy\"", ct.getPath("Created/By").getDBFieldName()); + } + + @Test + public void checkGetPropertyWithComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotNull(ct.getEdmItem().getProperty("Created")); + } + + @Test + public void checkGetPropertiesWithSameComplexTypeNotEqual() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotEquals(ct.getEdmItem().getProperty("Created"), ct.getEdmItem().getProperty("Updated")); + assertNotEquals(ct.getProperty("created"), ct.getProperty("updated")); + } + + @Ignore + @Test + public void checkGetPropertyWithEnumerationType() { + + } + + @Test + public void checkGetProptertyIgnoreTrue() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "DummyEmbeddedToIgnore"), schema); + assertTrue(ct.ignore()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "ChangeInformation"), schema); + assertFalse(ct.ignore()); + } + + @Test + public void checkOneSimpleProtectedProperty() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "InhouseAddressWithProtection"), schema); + List act = ct.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Building", act.get(0).getAttribute().getExternalName()); + assertEquals("BuildingNumber", act.get(0).getClaimName()); + } + + @Test + public void checkOneComplexProtectedPropertyDeep() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AddressDeepProtected"), schema); + List act = ct.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Building", act.get(0).getAttribute().getExternalName()); + assertEquals("BuildingNumber", act.get(0).getClaimName()); + assertEquals(2, act.get(0).getPath().getPath().size()); + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(COMM_CANONICAL_NAME)) { + if (property.getInternalName().equals("landlinePhoneNumber")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)) { + if (property.getInternalName().equals("countryName")) { + property.setIgnore(false); + } + } + } + + @Override + public void provideReferences(IntermediateReferenceList references) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java new file mode 100644 index 0000000000..c612c5c9c7 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java @@ -0,0 +1,308 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; +import org.apache.olingo.commons.api.edm.provider.CsdlFunctionImport; +import org.apache.olingo.commons.api.edm.provider.CsdlNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; +import org.reflections.util.ConfigurationBuilder; +import org.reflections.util.FilterBuilder; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityContainerAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateContainer extends TestMappingRoot { + private static final String PACKAGE1 = "com.sap.olingo.jpa.metadata.core.edm.mapper.impl"; + private static final String PACKAGE2 = "com.sap.olingo.jpa.processor.core.testmodel"; + private HashMap schemas = new HashMap<>(); + private Set> etList; + private IntermediateSchema schema; + + @Before + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + Reflections r = + new Reflections( + new ConfigurationBuilder() + .forPackages(PACKAGE1, PACKAGE2) + .filterInputsBy(new FilterBuilder().includePackage(PACKAGE1, PACKAGE2)) + .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())); + + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + etList = emf.getMetamodel().getEntities(); + schemas.put(PUNIT_NAME, schema); + } + + @Test + public void checkContainerCanBeCreated() throws ODataJPAModelException { + + new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + } + + @Test + public void checkGetName() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + assertEquals("ComSapOlingoJpaContainer", container.getExternalName()); + } + + @Test + public void checkGetNoEntitySets() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + assertEquals(TestDataConstants.NO_ENTITY_SETS, container.getEdmItem().getEntitySets().size()); + } + + @Test + public void checkGetEntitySetName() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) return; + } + fail(); + } + + @Test + public void checkGetEntitySetType() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + assertEquals(new JPAEdmNameBuilder(PUNIT_NAME).buildFQN("BusinessPartner"), entitySet.getTypeFQN()); + return; + } + } + fail(); + } + + @Test + public void checkGetNoNavigationPropertyBindings() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + assertEquals(4, entitySet.getNavigationPropertyBindings().size()); + return; + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPath() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Roles".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsTarget() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Roles".equals(binding.getPath())) { + assertEquals("BusinessPartnerRoles", binding.getTarget()); + return; + } + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPathComplexType() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Address/AdministrativeDivision".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPathComplexTypeNested() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("AdministrativeInformation/Created/User".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNoFunctionImportIfBound() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("CountRoles")) { + fail("Bound function must not generate a function import"); + } + } + } + + @Test + public void checkGetNoFunctionImportIfUnBoundHasImportFalse() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("max")) { + fail("UnBound function must not generate a function import is not annotated"); + } + } + } + + @Test + public void checkGetNoFunctionImportForJavaBasedFunction() throws ODataJPAModelException { + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if ("Sum".equals(funcImport.getName())) + return; + System.out.println(funcImport.getName()); + } + fail("Import not found"); + } + + @Test + public void checkGetFunctionImportIfUnBoundHasImportTrue() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("Olingo V4 ")) { + fail("UnBound function must be generate a function import is annotated"); + } + } + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore()); + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List act = container.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Capabilities.AsynchronousRequestsSupported", act.get(0).getTerm()); + } + + @Test + public void checkReturnEntitySetBasedOnInternalEntityType() throws ODataJPAModelException { + + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + JPAElement act = container.getEntitySet(et); + assertNotNull(act); + assertEquals("BestOrganizations", act.getExternalName()); + + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntityContainer(IntermediateEntityContainerAccess container) { + + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false"); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(mimeType); + annotation.setTerm("Capabilities.AsynchronousRequestsSupported"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + container.addAnnotations(annotations); + } + } + + private EntityType getEntityType(String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java new file mode 100644 index 0000000000..b795afaa6b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java @@ -0,0 +1,252 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlParameter; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AssertCollection; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.ChangeInformation; +import com.sap.olingo.jpa.processor.core.testmodel.DateConverter; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateDataBaseFunction extends TestMappingRoot { + private TestHelper helper; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkByEntityAnnotationCreate() throws ODataJPAModelException { + new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper.getStoredProcedure(helper.getEntityType( + BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + } + + @Test + public void checkByEntityAnnotationGetName() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + assertEquals("CountRoles", func.getEdmItem().getName()); + } + + @Test + public void checkByEntityAnnotationGetFunctionName() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + assertEquals("COUNT_ROLES", func.getUserDefinedFunction()); + } + + @Test + public void checkByEntityAnnotationInputParameterBound() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Key"); + param.setType(new FullQualifiedName("com.sap.olingo.jpa.BusinessPartner")); + param.setNullable(false); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameterBoundCompoundKey() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(AdministrativeDivision.class), "SiblingsBound"), + AdministrativeDivision.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Key"); + param.setType(new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision")); + param.setNullable(false); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameter2() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Number"); + param.setType(EdmPrimitiveTypeKind.Decimal.getFullQualifiedName()); + param.setNullable(false); + param.setPrecision(32); + param.setScale(0); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameterIsEnumeration() throws ODataJPAModelException { + + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(Person.class), "CheckRights"), BusinessPartner.class, helper.schema); + + assertNotNull(func.getEdmItem().getParameters()); + assertEquals(2, func.getEdmItem().getParameters().size()); + assertEquals(PUNIT_NAME + ".AccessRights", func.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + assertEquals("Edm.Int32", func.getEdmItem().getParameters().get(1).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsEmpty() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationIsBound() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertTrue(func.getEdmItem().isBound()); + assertTrue(func.isBound()); + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkByEntityAnnotationResultParameterSimple() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema); + + assertEquals(EdmPrimitiveTypeKind.Boolean.getFullQualifiedName().getFullQualifiedNameAsString(), func.getEdmItem() + .getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsEntity() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertEquals(PUNIT_NAME + ".Organization", func.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsCollectionFalse() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertTrue(func.getEdmItem().getReturnType().isCollection()); + + func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getEntityType(BusinessPartner.class), helper.schema).get("IsPrime"); + assertFalse(func.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkByEntityAnnotationResultParameterNotGiven() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertTrue(func.getEdmItem().getReturnType().isCollection()); + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getReturnType().getType()); + assertEquals(BusinessPartner.class, func.getResultParameter().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsNullable() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertTrue(func.getEdmItem().getReturnType().isNullable()); + + func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getEntityType(BusinessPartner.class), helper.schema).get("IsPrime"); + assertFalse(func.getEdmItem().getReturnType().isNullable()); + } + + @Test + public void checkByEntityAnnotationResultParameterEnumerationType() throws ODataJPAModelException { + + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(Person.class), "ReturnRights"), BusinessPartner.class, helper.schema); + + assertNotNull(func.getEdmItem().getReturnType()); + assertEquals(PUNIT_NAME + ".AccessRights", func.getEdmItem().getReturnType().getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnTypeEmbedded() throws ODataJPAModelException { + EdmFunction func = mock(EdmFunction.class); + EdmFunction.ReturnType retType = mock(EdmFunction.ReturnType.class); + // EdmFunctionParameter[] params = new EdmFunctionParameter[0]; + when(func.returnType()).thenReturn(retType); + when(func.parameter()).thenReturn(new EdmParameter[0]); + when(retType.type()).thenAnswer(new Answer>() { + + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return ChangeInformation.class; + } + }); + + IntermediateFunction act = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), func, + BusinessPartner.class, helper.schema); + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnTypeUnknown() throws ODataJPAModelException { + EdmFunction func = mock(EdmFunction.class); + EdmFunction.ReturnType retType = mock(EdmFunction.ReturnType.class); + // EdmFunctionParameter[] params = new EdmFunctionParameter[0]; + when(func.returnType()).thenReturn(retType); + when(func.parameter()).thenReturn(new EdmParameter[0]); + when(retType.type()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return DateConverter.class; + } + }); + IntermediateFunction act; + try { + act = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), func, BusinessPartner.class, + helper.schema); + act.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(ODataJPAModelException.MessageKeys.FUNC_RETURN_TYPE_UNKNOWN.getKey(), e.getId()); + return; + } + fail(); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java new file mode 100644 index 0000000000..dce04daf0a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java @@ -0,0 +1,259 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Member; +import java.util.List; + +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.ManagedType; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmDescriptionAssoziation; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; + +public class TestIntermediateDescriptionProperty extends TestMappingRoot { + private TestHelper helper; + private IntermediateDescriptionProperty cut; + private JPAEdmMetadataPostProcessor processor; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + } + + @Test + public void checkProptertyCanBeCreated() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("PostalAddressData"); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "countryName"); + new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema); + } + + @Test + public void checkGetProptertyNameOneToMany() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals("Wrong name", "CountryName", cut.getEdmItem().getName()); + } + + @Test + public void checkGetProptertyNameManyToMany() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "regionName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals("Wrong name", "RegionName", cut.getEdmItem().getName()); + } + + @Test + public void checkGetProptertyType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals("Wrong type", EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(), + cut.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + IntermediatePropertyAccess property = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertTrue(cut.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyMaxLength() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals(new Integer(100), cut.getEdmItem().getMaxLength()); + } + + @Test + public void checkWrongPathElementThrowsEcxeption() { + + Attribute jpaAttribute = mock(Attribute.class); + EdmDescriptionAssoziation assoziation = prepareCheckPath(jpaAttribute); + + EdmDescriptionAssoziation.valueAssignment[] valueAssignments = new EdmDescriptionAssoziation.valueAssignment[1]; + EdmDescriptionAssoziation.valueAssignment valueAssignment = mock(EdmDescriptionAssoziation.valueAssignment.class); + valueAssignments[0] = valueAssignment; + when(valueAssignment.attribute()).thenReturn("communicationData/dummy"); + when(assoziation.valueAssignments()).thenReturn(valueAssignments); + + try { + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + cut.getEdmItem(); + } catch (ODataJPAModelException e) { + return; + } + fail(); + } + + @Test + public void checkWrongPathStartThrowsEcxeption() { + + Attribute jpaAttribute = mock(Attribute.class); + EdmDescriptionAssoziation assoziation = prepareCheckPath(jpaAttribute); + + EdmDescriptionAssoziation.valueAssignment[] valueAssignments = new EdmDescriptionAssoziation.valueAssignment[1]; + EdmDescriptionAssoziation.valueAssignment valueAssignment = mock(EdmDescriptionAssoziation.valueAssignment.class); + valueAssignments[0] = valueAssignment; + when(valueAssignment.attribute()).thenReturn("communicationDummy/dummy"); + when(assoziation.valueAssignments()).thenReturn(valueAssignments); + + try { + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + cut.getEdmItem(); + } catch (ODataJPAModelException e) { + return; + } + fail(); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private EdmDescriptionAssoziation prepareCheckPath(Attribute jpaAttribute) { + AnnotatedMember jpaField = mock(AnnotatedMember.class); + ManagedType jpaManagedType = mock(ManagedType.class); + EdmDescriptionAssoziation assoziation = mock(EdmDescriptionAssoziation.class); + + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BusinessPartner.class; + } + }); + when(jpaAttribute.getJavaMember()).thenReturn(jpaField); + when(jpaAttribute.getName()).thenReturn("dummy"); + when(jpaAttribute.getDeclaringType()).thenReturn(jpaManagedType); + when(jpaManagedType.getJavaType()).thenReturn(BusinessPartner.class); + + when(jpaField.getAnnotation(EdmDescriptionAssoziation.class)).thenReturn(assoziation); + + when(assoziation.descriptionAttribute()).thenReturn("country"); + when(assoziation.languageAttribute()).thenReturn("language"); + when(assoziation.localeAttribute()).thenReturn(""); + return assoziation; + } + + @Test + public void checkAnnotations() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), + "locationName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + List annotations = cut.getEdmItem().getAnnotations(); + assertEquals(1, annotations.size()); + assertEquals("Core.IsLanguageDependent", annotations.get(0).getTerm()); + assertEquals(ConstantExpressionType.Bool, annotations.get(0).getExpression().asConstant().getType()); + assertEquals("true", annotations.get(0).getExpression().asConstant().getValue()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + // PostProcessorSpy spy = new PostProcessorSpy(); + IntermediateModelElement.setPostProcessor(processor); + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + + cut.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(cut, ADDR_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + + assertEquals("Wrong name", "CountryDescription", cut.getEdmItem().getName()); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("Wrong name", "CountryDescription", property.getExternalName()); + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)) { + if (property.getInternalName().equals("countryName")) { + property.setExternalName("CountryDescription"); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private interface AnnotatedMember extends Member, AnnotatedElement { + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java new file mode 100644 index 0000000000..f49768c72a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java @@ -0,0 +1,148 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntitySetAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; + +public class TestIntermediateEntitySet extends TestMappingRoot { + private IntermediateSchema schema; + private Set> etList; + private JPAEdmNameBuilder namebuilder; + + @Before + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + etList = emf.getMetamodel().getEntities(); + namebuilder = new JPAEdmNameBuilder(PUNIT_NAME); + schema = new IntermediateSchema(namebuilder, emf.getMetamodel(), r); + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessor()); + IntermediateEntityType et = new IntermediateEntityType(namebuilder, getEntityType( + "AdministrativeDivisionDescription"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + List act = set.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Capabilities.TopSupported", act.get(0).getTerm()); + } + + @Test + public void checkODataEntityTypeDiffers() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + + JPAEntityType odataEt = set.getODataEntityType(); + assertEquals("BusinessPartner", odataEt.getExternalName()); + } + + @Test + public void checkODataEntityTypeSame() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + + JPAEntityType odataEt = set.getODataEntityType(); + assertEquals("Organization", odataEt.getExternalName()); + } + + @Test + public void checkEdmItemContainsODataEntityType() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + CsdlEntitySet act = set.getEdmItem(); + assertEquals(namebuilder.buildFQN("BusinessPartner").getFullQualifiedNameAsString(), act.getType()); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessor()); + IntermediateEntityType et = new IntermediateEntityType(namebuilder, getEntityType("BusinessPartner"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + set.getEdmItem(); // Trigger build of EdmEntitySet + + assertEquals("Wrong name", "BusinessPartnerList", set.getExternalName()); + } + + private class PostProcessor extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(final IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(final IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(final IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntitySet(final IntermediateEntitySetAccess entitySet) { + + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false"); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(mimeType); + annotation.setTerm("Capabilities.TopSupported"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + entitySet.addAnnotations(annotations); + + if ("BusinessPartners".equals(entitySet.getExternalName())) { + entitySet.setExternalName("BusinessPartnerList"); + } + } + } + + private EntityType getEntityType(final String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java new file mode 100644 index 0000000000..d3a4bfd523 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java @@ -0,0 +1,586 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression; +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateEntityType extends TestMappingRoot { + private Set> etList; + private IntermediateSchema schema; + + @Before + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + etList = emf.getMetamodel().getEntities(); + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + } + + @Test + public void checkEntityTypeCanBeCreated() throws ODataJPAModelException { + + new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType("BusinessPartner"), schema); + } + + @Test + public void checkEntityTypeIgnoreSet() throws ODataJPAModelException { + + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "DummyToBeIgnored"), schema); + et.getEdmItem(); + assertTrue(et.ignore()); + } + + @Test + public void checkGetAllProperties() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Wrong number of entities", TestDataConstants.NO_DEC_ATTRIBUTES_BUISNESS_PARTNER, et.getEdmItem() + .getProperties() + .size()); + } + + @Test + public void checkGetPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNotNull(et.getEdmItem().getProperty("Type")); + } + + @Test + public void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Type", et.getEdmItem().getProperty("Type").getName()); + } + + @Test + public void checkGetPropertyByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("ID", et.getEdmItem().getProperty("ID").getName()); + } + + @Test + public void checkGetPathByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("ID", et.getPath("ID").getLeaf().getExternalName()); + } + + @Test + public void checkGetPathByNameIgnore() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNull(et.getPath("CustomString2")); + } + + @Test + public void checkGetPathByNameIgnoreCompexType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNull(et.getPath("Address/RegionCodePublisher")); + } + + @Test + public void checkGetInheritedAttributeByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Person"), schema); + assertEquals("ID", et.getPath("ID").getLeaf().getExternalName()); + } + + @Test + public void checkGetAllNaviProperties() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Wrong number of entities", 1, et.getEdmItem().getNavigationProperties().size()); + } + + @Test + public void checkGetNaviPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNotNull(et.getEdmItem().getNavigationProperty("Roles")); + } + + @Test + public void checkGetNaviPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Roles", et.getEdmItem().getNavigationProperty("Roles").getName()); + } + + @Test + public void checkGetAssoziationOfComplexTypeByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Address/AdministrativeDivision", et.getAssociationPath("Address/AdministrativeDivision").getAlias()); + } + + @Test + public void checkGetAssoziationOfComplexTypeByNameJoinColumns() throws ODataJPAModelException { + int actCount = 0; + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + for (JPAOnConditionItem item : et.getAssociationPath("Address/AdministrativeDivision").getJoinColumnsList()) { + if (item.getLeftPath().getAlias().equals("Address/Region")) { + assertTrue(item.getRightPath().getAlias().equals("DivisionCode")); + actCount++; + } + if (item.getLeftPath().getAlias().equals("Address/RegionCodeID")) { + assertTrue(item.getRightPath().getAlias().equals("CodeID")); + actCount++; + } + if (item.getLeftPath().getAlias().equals("Address/RegionCodePublisher")) { + assertTrue(item.getRightPath().getAlias().equals("CodePublisher")); + actCount++; + } + } + assertEquals("Not all join columns found", 3, actCount); + } + + @Test + public void checkGetPropertiesSkipIgnored() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Wrong number of entities", TestDataConstants.NO_DEC_ATTRIBUTES_BUISNESS_PARTNER - 1, et.getEdmItem() + .getProperties().size()); + } + + @Test + public void checkGetIsAbstract() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertTrue(et.getEdmItem().isAbstract()); + } + + @Test + public void checkGetIsNotAbstract() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertFalse(et.getEdmItem().isAbstract()); + } + + @Test + public void checkGetHasBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals(PUNIT_NAME + ".BusinessPartner", et.getEdmItem().getBaseType()); + } + + @Test + public void checkGetKeyProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerRole"), schema); + assertEquals("Wrong number of key propeties", 2, et.getEdmItem().getKey().size()); + } + + @Test + public void checkGetAllAttributes() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerRole"), schema); + assertEquals("Wrong number of entities", 2, et.getPathList().size()); + } + + @Test + public void checkGetAllAttributesWithBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + int exp = TestDataConstants.NO_ATTRIBUTES_BUISNESS_PARTNER + + TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + + TestDataConstants.NO_ATTRIBUTES_COMMUNICATION_DATA + + 2 * TestDataConstants.NO_ATTRIBUTES_CHANGE_INFO + + TestDataConstants.NO_ATTRIBUTES_ORGANIZATION; + assertEquals("Wrong number of entities", exp, et.getPathList().size()); + } + + @Test + public void checkGetAllAttributesWithBaseTypeFields() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + + assertNotNull(et.getPath("Type")); + assertNotNull(et.getPath("Name1")); + assertNotNull(et.getPath("Address" + JPAPath.PATH_SEPERATOR + "Region")); + assertNotNull(et.getPath("AdministrativeInformation" + JPAPath.PATH_SEPERATOR + + "Created" + JPAPath.PATH_SEPERATOR + "By")); + } + + @Test + public void checkGetAllAttributeIDWithBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals("ID", et.getPath("ID").getAlias()); + } + + @Test + public void checkGetKeyAttributeFromEmbeddedId() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + + assertNotNull(et.getAttribute("codePublisher")); + assertEquals("CodePublisher", et.getAttribute("codePublisher").getExternalName()); + } + + @Test + public void checkGetKeyWithBaseType() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals(1, et.getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(5, et.getEdmItem().getProperties().size()); + } + + @Test + public void checkEmbeddedIdResovedKey() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(4, et.getEdmItem().getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedKeyInternal() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(4, et.getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedPath() throws ODataJPAModelException { + JPAStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(5, et.getPathList().size()); + } + + @Test + public void checkEmbeddedIdResovedPathCodeId() throws ODataJPAModelException { + JPAStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(2, et.getPath("CodeID").getPath().size()); + } + + @Test + public void checkHasStreamNoProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + assertEquals(2, et.getEdmItem().getProperties().size()); + } + + @Test + public void checkHasStreamTrue() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + assertTrue(et.getEdmItem().hasStream()); + } + + @Test + public void checkHasStreamFalse() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertFalse(et.getEdmItem().hasStream()); + } + + @Test + public void checkHasETagTrue() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertTrue(et.hasEtag()); + } + + @Test + public void checkHasETagTrueIfInherited() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertTrue(et.hasEtag()); + } + + @Test + public void checkHasETagFalse() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivision"), schema); + assertFalse(et.hasEtag()); + } + + @Test + public void checkIgnoreIfAsEntitySet() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + assertTrue(et.ignore()); + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore()); + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + List act = et.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Core.AcceptableMediaTypes", act.get(0).getTerm()); + } + + @Test + public void checkGetProptertyByDBFieldName() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName()); + } + + @Test + public void checkGetProptertyByDBFieldNameFromSuperType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName()); + } + + @Test + public void checkGetProptertyByDBFieldNameFromEmbedded() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals("CodeID", et.getPropertyByDBField("\"CodeID\"").getExternalName()); + } + + @Test + public void checkAllPathContainsComplexCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Collection"), schema); + final List act = et.getPathList(); + + assertEquals(11, act.size()); + assertNotNull(et.getPath("Complex/Address")); + assertTrue(et.getPath("Complex/Address").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "Complex/Address").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(2, actIntermediate.asAssociation().getPath().size()); + + for (JPAPath p : act) { + if (p.getPath().size() > 1 + && p.getPath().get(0).getExternalName().equals("Complex") + && p.getPath().get(1).getExternalName().equals("Address")) { + assertTrue(p.getPath().get(1) instanceof IntermediateCollectionProperty); + final IntermediateCollectionProperty actProperty = (IntermediateCollectionProperty) p.getPath().get(1); + assertNotNull(actProperty.asAssociation()); + assertEquals(et, actProperty.asAssociation().getSourceType()); + break; + } + } + } + + @Test + public void checkAllPathContainsPrimitiveCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Collection"), schema); + final List act = et.getPathList(); + + assertEquals(11, act.size()); + assertNotNull(et.getPath("Complex/Comment")); + assertTrue(et.getPath("Complex/Comment").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "Complex/Comment").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals("Complex/Comment", actIntermediate.asAssociation().getAlias()); + + for (JPAPath p : act) { + if (p.getPath().size() > 1 + && p.getPath().get(0).getExternalName().equals("Complex") + && p.getPath().get(1).getExternalName().equals("Comment")) { + assertTrue(p.getPath().get(1) instanceof IntermediateCollectionProperty); + final IntermediateCollectionProperty actProperty = (IntermediateCollectionProperty) p.getPath().get(1); + assertNotNull(actProperty.asAssociation()); + assertEquals(et, actProperty.asAssociation().getSourceType()); + break; + } + } + } + + @Test + public void checkAllPathContainsDeepComplexWithPrimitiveCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "CollectionDeep"), schema); + final List act = et.getPathList(); + + assertEquals(8, act.size()); + assertNotNull(et.getPath("FirstLevel/SecondLevel/Comment")); + assertTrue(et.getPath("FirstLevel/SecondLevel/Comment").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "FirstLevel/SecondLevel/Comment").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(3, actIntermediate.asAssociation().getPath().size()); + assertEquals("FirstLevel/SecondLevel/Comment", actIntermediate.asAssociation().getAlias()); + } + + @Test + public void checkAllPathContainsDeepComplexWithComplexCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "CollectionDeep"), schema); + + assertNotNull(et.getPath("FirstLevel/SecondLevel/Address")); + assertTrue(et.getPath("FirstLevel/SecondLevel/Address").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "FirstLevel/SecondLevel/Address").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(3, actIntermediate.asAssociation().getPath().size()); + assertEquals("FirstLevel/SecondLevel/Address", actIntermediate.asAssociation().getAlias()); + for (JPAPath path : et.getPathList()) { + String[] pathElements = path.getAlias().split("/"); + assertEquals(pathElements.length, path.getPath().size()); + } + } + + @Test + public void checkOneSimpleProtectedProperty() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerProtected"), schema); + List act = et.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Username", act.get(0).getAttribute().getExternalName()); + assertEquals("UserId", act.get(0).getClaimName()); + } + + @Test + public void checkComplexAndInheritedProtectedProperty() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonDeepProtected"), schema); + + List act = et.getProtections(); + assertNotNull(act); + assertInherited(act); + assertComplexAnnotated(act, "Creator", "Created"); + assertComplexAnnotated(act, "Updator", "Updated"); + assertComplexDeep(act); + assertEquals(4, act.size()); + } + + private void assertComplexDeep(List act) { + for (final JPAProtectionInfo info : act) { + if (info.getClaimName().equals("BuildingNumber")) { + assertEquals("Building", info.getAttribute().getExternalName()); + assertEquals(3, info.getPath().getPath().size()); + assertEquals("InhouseAddress/InhouseAddress/Building", info.getPath().getAlias()); + return; + } + } + fail("Deep protected complex attribute not found"); + + } + + private void assertComplexAnnotated(List act, final String expClaimName, + final String pathElement) { + for (final JPAProtectionInfo info : act) { + if (info.getClaimName().equals(expClaimName)) { + assertEquals("By", info.getAttribute().getExternalName()); + assertEquals(3, info.getPath().getPath().size()); + assertEquals("ProtectedAdminInfo/" + pathElement + "/By", info.getPath().getAlias()); + return; + } + } + fail("Complex attribute not found for: " + expClaimName); + } + + private void assertInherited(List act) { + for (final JPAProtectionInfo info : act) { + if (info.getAttribute().getExternalName().equals("Username")) { + assertEquals("UserId", info.getClaimName()); + assertEquals(1, info.getPath().getPath().size()); + assertEquals("Username", info.getPath().getAlias()); + return; + } + } + fail("Inherited not found"); + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) { + if (entity.getExternalName().equals("PersonImage")) { + List items = new ArrayList<>(); + CsdlCollection exp = new CsdlCollection(); + exp.setItems(items); + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.String, "ogg"); + items.add(mimeType); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(exp); + annotation.setTerm("Core.AcceptableMediaTypes"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + entity.addAnnotations(annotations); + } + } + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private EntityType getEntityType(String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java new file mode 100644 index 0000000000..7fdc3e04e4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java @@ -0,0 +1,152 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockitoAnnotations; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.DayOfWeek; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.FileAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongMember; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongType; + +public class TestIntermediateEnumerationType extends TestMappingRoot { + + private IntermediateEnumerationType cut; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void checkCsdlEnumTypeAccessable() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertNotNull(cut.getEdmItem()); + } + + @Test + public void checkNameProvided() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("DayOfWeek", cut.getEdmItem().getName()); + } + + @Test + public void checkIsFlagProvidesFalse() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertFalse(cut.getEdmItem().isFlags()); + } + + @Test + public void checkIsFlagProvidesTrue() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertTrue(cut.getEdmItem().isFlags()); + } + + @Test + public void checkUnderlyingTypeIntAsDefault() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals(EdmPrimitiveTypeKind.Int32.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem() + .getUnderlyingType()); + } + + @Test + public void checkUnderlyingTypeFromConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals(EdmPrimitiveTypeKind.Int16.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem() + .getUnderlyingType()); + } + + @Test + public void checkReturnsRightNumberOfMember4() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals(4, cut.getEdmItem().getMembers().size()); + } + + @Test + public void checkReturnsRightNumberOfMember7() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals(7, cut.getEdmItem().getMembers().size()); + } + + @Test + public void checkReturnsRightNameForMembersOfDayOfWeek() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("MONDAY", cut.getEdmItem().getMembers().get(0).getName()); + assertEquals("SUNDAY", cut.getEdmItem().getMembers().get(6).getName()); + } + + @Test + public void checkReturnsRightValueForMembersOfDayOfWeek() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("0", cut.getEdmItem().getMembers().get(0).getValue()); + assertEquals("6", cut.getEdmItem().getMembers().get(6).getValue()); + } + + @Test + public void checkReturnsRightNameForMembersOfFileAccess() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals("Read", cut.getEdmItem().getMembers().get(0).getName()); + assertEquals("Delete", cut.getEdmItem().getMembers().get(3).getName()); + } + + @Test + public void checkReturnsRightValueForMembersOfFileAccess() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals("1", cut.getEdmItem().getMembers().get(0).getValue()); + assertEquals("8", cut.getEdmItem().getMembers().get(3).getValue()); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsErrorOnIsFlagTrueAndNegativeValue() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), WrongMember.class); + cut.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsErrorOnNotSupportedUnderlyingType() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), WrongType.class); + cut.getEdmItem(); + } + + @Test + public void checkOrdinalMemberProvidedFromStringWOConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertEquals(DayOfWeek.SUNDAY, cut.enumOf("SUNDAY")); + } + + @Test + public void checkOrdinalMemberProvidedFromNumberWOConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertEquals(DayOfWeek.TUESDAY, cut.enumOf(1)); + } + + @Test + public void checkOrdinalMemberProvidedFromStringWithConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + assertEquals(FileAccess.Create, cut.enumOf("Create")); + } + + @Test + public void checkOrdinalMemberProvidedFromNumberWithConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + assertEquals(FileAccess.Write, cut.enumOf((short) 2)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java new file mode 100644 index 0000000000..1f80c1e731 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java @@ -0,0 +1,74 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoFunctions; + +public class TestIntermediateFunctionFactory extends TestMappingRoot { + private TestHelper helper; + + private Reflections reflections; + private IntermediateFunctionFactory cut; + private Set> javaFunctions; + + @Before + public void setUp() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + + reflections = mock(Reflections.class); + cut = new IntermediateFunctionFactory(); + javaFunctions = new HashSet>(); + when(reflections.getSubTypesOf(ODataFunction.class)).thenReturn(javaFunctions); + } + + @Test + public void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException { + Reflections r = null; + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), r, helper.schema)); + } + + @Test + public void checkReturnEmptyMapIfNoJavaFunctionsFound() throws ODataJPAModelException { + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), reflections, helper.schema)); + } + + @Test + public void checkReturnMapWithOneIfOneJavaFunctionsFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaOneFunction.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(1, act.size()); + } + + @Test + public void checkReturnMapWithTwoIfTwoJavaFunctionsFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaTwoFunctions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(2, act.size()); + } + + @Test + public void checkReturnMapWithWithJavaFunctionsFromTwoClassesFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaOneFunction.class); + javaFunctions.add(ExampleJavaTwoFunctions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(3, act.size()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java new file mode 100644 index 0000000000..a3221b6b32 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java @@ -0,0 +1,355 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; + +import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaActions; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor; + +public class TestIntermediateJavaAction extends TestMappingRoot { + private TestHelper helper; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkInternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("unboundWithImport", act.getInternalName()); + } + + @Test + public void checkInternalNameGiven() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("unboundWithImport", act.getInternalName()); + } + + @Test + public void checkExternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("UnboundWithImport", act.getExternalName()); + } + + @Test + public void checkReturnsFalseForIsBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertFalse(act.getEdmItem().isBound()); + } + + @Test + public void checkReturnsTrueForIsBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnsEntitySetPathForBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithEntitySetPath"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals("Person/Roles", act.getEdmItem().getEntitySetPath()); + } + + @Test + public void checkReturnsGivenEntitySetTypeIfBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + assertEquals("Edm.Decimal", act.getEdmItem().getParameters().get(1).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnsExternalName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertEquals("BoundNoImport", act.getEdmItem().getName()); + } + + @Test + public void checkReturnsTrueForHasActionImportIfUnbound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsFalseForHasActionImportIfNotSet() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertFalse(act.hasImport()); + } + + @Test + public void checkReturnsReturnTypeConvertedPrimitiveReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getReturnType()); + assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsReturnTypeNullForVoid() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertNull(act.getEdmItem().getReturnType()); + } + + @Test + public void checkReturnsReturnTypeEmbeddableType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddable"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEntity"); + + assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration"); + + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsReturnTypeCollectionOfPrimitive() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnCollection"); + + assertEquals("Edm.String", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsReturnTypeCollectionOfEmbeddable() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddableCollection"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsReturnTypeFacetForNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundReturnFacet"); + assertFalse(act.getEdmItem().getReturnType().isNullable()); + assertEquals(Integer.valueOf(20), act.getEdmItem().getReturnType().getPrecision()); + assertEquals(Integer.valueOf(5), act.getEdmItem().getReturnType().getScale()); + } + + @Test + public void checkReturnsReturnTypeFacetForNonNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNull(act.getEdmItem().getReturnType().getPrecision()); + assertNull(act.getEdmItem().getReturnType().getScale()); + assertNull(act.getEdmItem().getReturnType().getMaxLength()); + } + + @Test + public void checkReturnsReturnTypeFacetForStringsAndGeo() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation"); + + assertEquals(Integer.valueOf(60), act.getEdmItem().getReturnType().getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString()); + } + + @Test + public void checkReturnsParameterConvertPrimitiveTypes() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType()); + assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType()); + } + + @Test + public void checkReturnsParameterFacetForNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getParameter()); + assertEquals(Integer.valueOf(34), act.getParameter().get(1).getPrecision()); + assertEquals(Integer.valueOf(10), act.getParameter().get(1).getScale()); + + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(Integer.valueOf(34), act.getEdmItem().getParameters().get(1).getPrecision()); + assertEquals(Integer.valueOf(10), act.getEdmItem().getParameters().get(1).getScale()); + } + + @Test + public void checkReturnsParameterFacetForNonNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem().getParameters()); + assertNull(act.getEdmItem().getParameters().get(1).getPrecision()); + assertNull(act.getEdmItem().getParameters().get(1).getScale()); + assertNull(act.getEdmItem().getParameters().get(1).getMaxLength()); + } + + @Test + public void checkReturnsParameterFacetForStringsAndGeo() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation"); + + assertNotNull(act.getParameter()); + assertEquals(Integer.valueOf(100), act.getParameter().get(0).getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getParameter().get(0).getSrid().getDimension()); + assertEquals("4326", act.getParameter().get(0).getSrid().toString()); + + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(Integer.valueOf(100), act.getEdmItem().getParameters().get(0).getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getParameters().get(0).getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getParameters().get(0).getSrid().toString()); + } + + @Test + public void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration"); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkProvidesAllParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + List actParams = act.getParameter(); + assertEquals(2, actParams.size()); + } + + @Test + public void checkProvidesParameterByDeclaired() throws ODataJPAModelException, NoSuchMethodException, + SecurityException { + + Method m = ExampleJavaActions.class.getMethod("unboundWithImport", short.class, int.class); + Parameter[] params = m.getParameters(); + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + assertNotNull(act.getParameter(params[0])); + assertEquals("A", act.getParameter(params[0]).getName()); + assertNotNull(act.getParameter(params[1])); + assertEquals("B", act.getParameter(params[1]).getName()); + } + + @Test + public void checkExceptConstructorWithoutParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + act.getEdmItem(); + assertNotNull(act.getConstructor()); + } + + @Test + public void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaEmConstructor.class, "mul"); + + assertNotNull(act.getConstructor()); + assertEquals(1, act.getConstructor().getParameterTypes().length); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionForNonPrimitiveParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorNonPrimitiveParameter"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExceptionIfCollectionAndReturnTypeEmpty() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnCollectionWithoutReturnType"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnPrivateConstructor() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaPrivateConstructor.class, "mul"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnNoConstructorAsSpecified() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaTwoParameterConstructor.class, "mul"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnIsBoundWithoutEntityTypeParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithOutBindingParameter"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnIsBoundWithoutParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithOutParameter"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnIsBoundBindingParameterNotFirst() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundBindingParameterSecondParameter"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnEntitySetGivenUnbound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorUnboundWithEntitySetPath"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnEntitySetGivenNoEntityReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorPrimitiveTypeWithEntitySetPath"); + act.getEdmItem(); + } + + private IntermediateJavaAction createAction(Class clazz, String method) + throws ODataJPAModelException { + for (Method m : Arrays.asList(clazz.getMethods())) { + EdmAction actionDescribtion = m.getAnnotation(EdmAction.class); + if (actionDescribtion != null && method.equals(m.getName())) { + return new IntermediateJavaAction(new JPAEdmNameBuilder(PUNIT_NAME), actionDescribtion, m, helper.schema); + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java new file mode 100644 index 0000000000..197caae231 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java @@ -0,0 +1,244 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.util.Arrays; + +import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaFunctions; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor; + +public class TestIntermediateJavaFunction extends TestMappingRoot { + private TestHelper helper; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkInternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertEquals("sum", act.getInternalName()); + } + + @Test + public void checkExternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertEquals("Sum", act.getExternalName()); + } + + @Test + public void checkReturnsConvertedPrimitiveReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getReturnType()); + assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsConvertedPrimitiveParameterTypes() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType()); + assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType()); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionForNonPrimitiveParameter() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "errorNonPrimitiveParameter"); + act.getEdmItem(); + } + + @Test + public void checkReturnsFalseForIsBound() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertEquals(false, act.getEdmItem().isBound()); + } + + @Test + public void checkReturnsTrueForHasFunctionImport() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsAnnotatedName() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertEquals("Add", act.getExternalName()); + } + + @Test + public void checkIgnoresGivenIsBound() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertFalse(act.getEdmItem().isBound()); + assertFalse(act.isBound()); + } + + @Test + public void checkIgnoresGivenHasFunctionImport() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType"); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getParameter("arg0").getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkIgnoresParameterAsPartFromEdmFunction() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "div"); + + assertNotNull(act.getEdmItem()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExceptionIfAnnotatedReturnTypeNEDeclairedType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "errorReturnType"); + act.getEdmItem(); + } + + @Test + public void checkReturnsFacetForNumbersOfReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "now"); + assertFalse(act.getEdmItem().getReturnType().isNullable()); + assertEquals(Integer.valueOf(9), act.getEdmItem().getReturnType().getPrecision()); + assertEquals(Integer.valueOf(3), act.getEdmItem().getReturnType().getScale()); + } + + @Test + public void checkReturnsFacetForStringsAndGeoOfReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "determineLocation"); + assertEquals(Integer.valueOf(60), act.getEdmItem().getReturnType().getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString()); + } + + @Test + public void checkReturnsIsCollectionIfDefinedReturnTypeIsSubclassOfCollection() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnCollection"); + + assertTrue(act.getEdmItem().getReturnType().isCollection()); + assertEquals("Edm.String", act.getEdmItem().getReturnType().getType()); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExceptionIfCollectionAndReturnTypeEmpty() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnCollectionWithoutReturnType"); + act.getEdmItem(); + } + + @Test + public void checkReturnsEmbeddableTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddable"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEmbeddableCollectionTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddableCollection"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEntity"); + assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException { + + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType"); + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationCollectionTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationCollection"); + + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnNotSupportedReturnType() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "wrongReturnType"); + act.getEdmItem(); + } + + @Test + public void checkExceptConstructorWithoutParameter() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + act.getEdmItem(); + } + + @Test + public void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaEmConstructor.class, "sum"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnPrivateConstructor() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaPrivateConstructor.class, "sum"); + act.getEdmItem(); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsExcpetionOnNoConstructorAsSpecified() throws ODataJPAModelException { + IntermediateJavaFunction act = createFunction(ExampleJavaTwoParameterConstructor.class, "sum"); + act.getEdmItem(); + } + + private IntermediateJavaFunction createFunction(Class clazz, String method) + throws ODataJPAModelException { + for (Method m : Arrays.asList(clazz.getMethods())) { + EdmFunction functionDescribtion = m.getAnnotation(EdmFunction.class); + if (functionDescribtion != null && method.equals(m.getName())) { + return new IntermediateJavaFunction(new JPAEdmNameBuilder(PUNIT_NAME), functionDescribtion, m, helper.schema); + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java new file mode 100644 index 0000000000..0eee2e679d --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java @@ -0,0 +1,469 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlOnDelete; +import org.apache.olingo.commons.api.edm.provider.CsdlOnDeleteAction; +import org.apache.olingo.commons.api.edm.provider.CsdlReferentialConstraint; +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored; +import com.sap.olingo.jpa.processor.core.testmodel.JoinSource; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateNavigationProperty extends TestMappingRoot { + private IntermediateSchema schema; + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + @Before + public void setup() throws ODataJPAModelException { + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + } + + @Test + public void checkNaviProptertyCanBeCreated() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), schema.getStructuredType(jpaAttribute), + jpaAttribute, schema); + } + + @Test + public void checkGetName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("Wrong name", "Roles", property.getEdmItem().getName()); + } + + @Test + public void checkGetType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("Wrong name", PUNIT_NAME + ".BusinessPartnerRole", property.getEdmItem().getType()); + } + + @Test + public void checkGetIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetIgnoreTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(DummyToBeIgnored.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + assertTrue(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetPropertyOnDelete() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals(CsdlOnDeleteAction.Cascade, property.getEdmItem().getOnDelete().getAction()); + } + + @Test + public void checkGetProptertyFacetsNullableFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + + assertFalse(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsCollectionTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsColletionFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + + assertFalse(property.getEdmItem().isCollection()); + } + + @Test + public void checkGetJoinColumnsSize1BP() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals(1, property.getJoinColumns().size()); + } + + @Test + public void checkGetPartnerAdmin_Parent() throws ODataJPAModelException { + EntityType et = helper.getEntityType(AdministrativeDivision.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "parent"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Children", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerAdmin_Children() throws ODataJPAModelException { + EntityType et = helper.getEntityType(AdministrativeDivision.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "children"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Parent", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerBP_Roles() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("BusinessPartner", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerRole_BP() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Roles", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetJoinColumnFilledCompletely() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + + IntermediateJoinColumn act = property.getJoinColumns().get(0); + assertEquals("\"BusinessPartnerID\"", act.getName()); + assertEquals("\"ID\"", act.getReferencedColumnName()); + } + + @Test + public void checkGetJoinColumnFilledCompletelyInvert() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + + IntermediateJoinColumn act = property.getJoinColumns().get(0); + assertEquals("\"BusinessPartnerID\"", act.getName()); + assertEquals("\"ID\"", act.getReferencedColumnName()); + } + + @Test + public void checkGetJoinColumnsSize1Roles() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals(1, property.getJoinColumns().size()); + } + + @Test + public void checkGetJoinColumnsSize2() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("PostalAddressData"); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "administrativeDivision"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getComplexType(et.getJavaType()), jpaAttribute, schema); + List columns = property.getJoinColumns(); + assertEquals(3, columns.size()); + } + + @Test + public void checkGetReferentialConstraintSize() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + assertEquals(1, property.getProperty().getReferentialConstraints().size()); + } + + @Test + public void checkGetReferentialConstraintBuPaRole() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + for (CsdlReferentialConstraint c : constraints) { + assertEquals("ID", c.getProperty()); + assertEquals("BusinessPartnerID", c.getReferencedProperty()); + } + } + + @Test + public void checkGetReferentialConstraintRoleBuPa() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + for (CsdlReferentialConstraint c : constraints) { + assertEquals("BusinessPartnerID", c.getProperty()); + assertEquals("ID", c.getReferencedProperty()); + } + } + + @Test + public void checkGetReferentialConstraintViaEmbeddedId() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "allDescriptions"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + assertEquals(3, constraints.size()); + for (CsdlReferentialConstraint c : constraints) { + assertEquals(c.getReferencedProperty(), c.getProperty()); + } + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(processor); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType( + BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + property.getEdmItem(); + verify(processor, atLeastOnce()).processNavigationProperty(property, BUPA_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("Wrong name", "RoleAssignment", property.getEdmItem().getName()); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + JPAAssociationAttribute property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + + assertEquals("Wrong name", "RoleAssignment", property.getExternalName()); + } + + @Test + public void checkPostProcessorSetOnDelete() throws ODataJPAModelException { + PostProcessorOneDelete pPDouble = new PostProcessorOneDelete(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "children"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema); + + assertEquals(CsdlOnDeleteAction.None, property.getProperty().getOnDelete().getAction()); + } + + @Test + public void checkGetJoinTable() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNotNull(property.getJoinTable()); + } + + @Test + public void checkGetJoinTableName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("\"SupportRelationship\"", property.getJoinTable().getTableName()); + } + + @Test + public void checkGetNullIfNoJoinTableGiven() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "parent"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNull(property.getJoinTable()); + } + + @Test + public void checkGetJoinTableJoinColumns() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + } + + @Test + public void checkGetJoinTableEntityType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNotNull(property.getJoinTable().getEntityType()); + } + + @Test + public void checkGetJoinTableJoinColumnsNotMapped() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(JoinSource.class), + "oneToMany"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(JoinSource.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + assertNotNull(property.getJoinTable()); + IntermediateJoinTable act = (IntermediateJoinTable) property.getJoinTable(); + for (JPAOnConditionItem item : act.getJoinColumns()) { + assertNotNull(item.getLeftPath()); + assertNotNull(item.getRightPath()); + } + } + + @Test + public void checkGetJoinTableJoinColumnsMapped() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Organization.class), + "supportEngineers"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + BUPA_CANONICAL_NAME)) { + if (property.getInternalName().equals("roles")) { + property.setExternalName("RoleAssignment"); + } + } + } + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + + } + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private class PostProcessorOneDelete extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADMIN_CANONICAL_NAME)) { + if (property.getInternalName().equals("children")) { + CsdlOnDelete oD = new CsdlOnDelete(); + oD.setAction(CsdlOnDeleteAction.None); + property.setOnDelete(oD); + } + } + } + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java new file mode 100644 index 0000000000..d57f455055 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java @@ -0,0 +1,153 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.net.URISyntaxException; +import java.util.List; + +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList.IntermediateReferenceAccess; + +public class TestIntermediateReferences extends TestMappingRoot { + private IntermediateReferences cut; + + @Before + public void setup() throws ODataJPAModelException { + cut = new IntermediateReferences(); + } + + @Test + public void checkAddOnlyURI() throws ODataJPAModelException, URISyntaxException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"; + cut.addReference(uri); + List act = cut.getEdmReferences(); + assertEquals(1, act.size()); + assertEquals(act.get(0).getUri().toString(), uri); + } + + @Test + public void checkAddURIandPath() throws ODataJPAModelException, URISyntaxException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + List act = cut.getEdmReferences(); + assertEquals(1, act.size()); + assertEquals(uri, act.get(0).getUri().toString()); + } + + @Test + public void checkConvertedToEdmx() throws ODataJPAModelException { + JPAServiceDocument serviceDocument; + serviceDocument = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), new PostProcessor(), null); + assertEquals(1, serviceDocument.getReferences().size()); + + EdmxReference ref = serviceDocument.getReferences().get(0); + assertEquals(1, ref.getIncludes().size()); + } + + @Test + public void checkGetOneSchema() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", ""); + + assertEquals(1, cut.getSchemas().size()); + } + + @Test + public void checkGetTwoSchemas() throws ODataJPAModelException { + String uri = "http://org.example/odata/odata/v4.0/os/vocabularies/Org.Olingo.Test.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.Olingo.Test.V1.xml"); + ref.addInclude("Org.Olingo.Test.V1.xml", ""); + + assertEquals(2, cut.getSchemas().size()); + } + + @Test + public void checkGetComplexType() throws ODataJPAModelException { + String uri = "http://org.example/odata/odata/v4.0/os/vocabularies/Org.Olingo.Test.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.Olingo.Test.V1.xml"); + ref.addInclude("Org.Olingo.Test.V1.xml", ""); + + for (CsdlSchema schema : cut.getSchemas()) { + if (schema.getNamespace().equals("Org.OData.Capabilities.V1")) { + assertNotNull(schema.getComplexType("UpdateRestrictionsType")); + return; + } + } + fail(); + } + + @Test + public void checkGetTermByNamespace() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", ""); + FullQualifiedName fqn = new FullQualifiedName("Org.OData.Measures.V1", "ISOCurrency"); + assertNotNull(cut.getTerm(fqn)); + } + + @Test + public void checkGetTermByAlias() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Measures", "ISOCurrency"); + assertNotNull(cut.getTerm(fqn)); + } + + @Test + public void checkReturnNullOnUnknowTerm() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Measures", "Dummy"); + assertNull(cut.getTerm(fqn)); + } + + @Test + public void checkReturnNullOnUnknowNamespace() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Dummy", "ISOCurrency"); + assertNull(cut.getTerm(fqn)); + } + + class PostProcessor extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(final IntermediateNavigationPropertyAccess property, + final String jpaManagedTypeClassName) { + + } + + @Override + public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) { + + } + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess reference = references.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + reference.addInclude("Org.OData.Core.V1", "Core"); + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java new file mode 100644 index 0000000000..80155af230 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java @@ -0,0 +1,80 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashSet; + +import org.junit.Before; +import org.junit.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRights; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateSchema extends TestMappingRoot { + private Reflections r; + + @Before + public void setup() { + r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class, AccessRights.class }))); + } + + @Test + public void checkSchemaCanBeCreated() throws ODataJPAModelException { + + new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + } + + @Test + public void checkSchemaGetAllEntityTypes() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("Wrong number of entities", TestDataConstants.NO_ENTITY_TYPES, schema.getEdmItem().getEntityTypes() + .size()); + } + + @Test + public void checkSchemaGetEntityTypeByNameNotNull() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertNotNull(schema.getEdmItem().getEntityType("BusinessPartner")); + } + + @Test + public void checkSchemaGetEntityTypeByNameRightEntity() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("BusinessPartner", schema.getEdmItem().getEntityType("BusinessPartner").getName()); + } + + @Test + public void checkSchemaGetAllComplexTypes() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + // ChangeInformation,CommunicationData,AdministrativeInformation,PostalAddressData + assertEquals("Wrong number of complex types", 15, schema.getEdmItem().getComplexTypes().size()); + } + + @Test + public void checkSchemaGetComplexTypeByNameNotNull() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertNotNull(schema.getEdmItem().getComplexType("CommunicationData")); + } + + @Test + public void checkSchemaGetComplexTypeByNameRightEntity() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("CommunicationData", schema.getEdmItem().getComplexType("CommunicationData").getName()); + } + + @Test + public void checkSchemaGetAllFunctions() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("Wrong number of entities", 10, schema.getEdmItem().getFunctions().size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java new file mode 100644 index 0000000000..0e17e005cd --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java @@ -0,0 +1,83 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmBindingTarget; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer; +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class TestIntermediateServiceDocument extends TestMappingRoot { + + @Test + public void checkServiceDocumentCanBeCreated() throws ODataJPAModelException { + new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + } + + @Test + public void checkServiceDocumentGetSchemaList() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertEquals("Wrong number of schemas", 1, svc.getEdmSchemas().size()); + } + + @Test + public void checkServiceDocumentGetContainer() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertNotNull("Entity Container not found", svc.getEdmEntityContainer()); + } + + @Test + public void checkServiceDocumentGetContainerFromSchema() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + List schemas = svc.getEdmSchemas(); + CsdlSchema schema = schemas.get(0); + assertNotNull("Entity Container not found", schema.getEntityContainer()); + } + + @Test + public void checkServiceDocumentGetEntitySetsFromContainer() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + CsdlEntityContainer container = svc.getEdmEntityContainer(); + assertNotNull("Entity Container not found", container.getEntitySets()); + } + + @Test + public void checkHasEtagReturnsTrueOnVersion() throws ODataJPAModelException { + EdmBindingTarget target = mock(EdmBindingTarget.class); + EdmEntityType et = mock(EdmEntityType.class); + when(target.getEntityType()).thenReturn(et); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "BusinessPartner")); + + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertTrue(svc.hasETag(target)); + } + + @Test + public void checkHasEtagReturnsFalseWithoutVersion() throws ODataJPAModelException { + EdmBindingTarget target = mock(EdmBindingTarget.class); + EdmEntityType et = mock(EdmEntityType.class); + when(target.getEntityType()).thenReturn(et); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "Country")); + + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, null); + assertFalse(svc.hasETag(target)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java new file mode 100644 index 0000000000..3c978f5df0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java @@ -0,0 +1,583 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Member; +import java.sql.Date; +import java.sql.Timestamp; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.Attribute.PersistentAttributeType; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.ManagedType; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtectedBy; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtections; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.metadata.core.edm.mapper.util.MemberDouble; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected; +import com.sap.olingo.jpa.processor.core.testmodel.Comment; +import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.testmodel.PersonImage; + +public class TestIntermediateSimpleProperty extends TestMappingRoot { + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + } + + @Test + public void checkProptertyCanBeCreated() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("CommunicationData"); + Attribute jpaAttribute = helper.getAttribute(et, "landlinePhoneNumber"); + new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema); + } + + @Test + public void checkGetProptertyName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong name", "Type", property.getEdmItem().getName()); + } + + @Test + public void checkGetProptertyDBFieldName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong name", "\"Type\"", property.getDBFieldName()); + } + + @Test + public void checkGetProptertySimpleType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong type", EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(), + property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyComplexType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), + "communicationData"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong type", PUNIT_NAME + ".CommunicationData", property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyEnumTypeWithoutConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong type", "com.sap.olingo.jpa.ABCClassifiaction", property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyEnumTypeWithoutConverterMustNotHaveMapper() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMapping()); + } + + @Test + public void checkGetProptertyEnumTypeWithConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "accessRights"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Wrong type", "com.sap.olingo.jpa.AccessRights", property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyIgnoreTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsNullableTrueComplex() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEmbeddedableType("PostalAddressData"), "POBox"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsNullableFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyIsETagTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.isEtag()); + } + + @Test + public void checkGetProptertyIsETagFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.isEtag()); + } + + @Test + public void checkGetProptertyMaxLength() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(1), property.getEdmItem().getMaxLength()); + } + + @Test + public void checkGetProptertyMaxLengthNullForClob() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getComplexType("DummyEmbeddedToIgnore"), "command"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMaxLength()); + } + + @Test + public void checkGetProptertyPrecisionDecimal() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(16), property.getEdmItem().getPrecision()); + } + + @Test + public void checkGetProptertyScaleDecimal() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(5), property.getEdmItem().getScale()); + } + + @Test + public void checkGetProptertyPrecisionTime() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(3), property.getEdmItem().getPrecision()); + } + + @Test + public void checkGetProptertyMapper() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNotNull(property.getEdmItem().getMapping()); + assertEquals(Timestamp.class, property.getEdmItem().getMapping().getMappedJavaClass()); + } + + @Test + public void checkGetProptertyMapperWithConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "birthDay"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNotNull(property.getEdmItem().getMapping()); + assertEquals(Date.class, property.getEdmItem().getMapping().getMappedJavaClass()); + } + + @Test + public void checkGetNoProptertyMapperForClob() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Comment.class), "text"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMapping()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + IntermediateSimpleProperty.setPostProcessor(processor); + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + property.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(property, BUPA_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateSimpleProperty.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("Wrong name", "ContactPersonName", property.getEdmItem().getName()); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("Wrong name", "ContactPersonName", property.getExternalName()); + } + + @Test + public void checkConverterGetConverterReturned() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "birthDay"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNotNull(property.getConverter()); + } + + @Test + public void checkConverterGetConverterNotReturned() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNull(property.getConverter()); + } + + @Test + public void checkConverterGetConverterNotReturnedDiffernt() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(DummyToBeIgnored.class), "uuid"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNull(property.getConverter()); + } + + @Test + public void checkGetProptertyDefaultValue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEmbeddedableType("PostalAddressData"), + "regionCodePublisher"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("ISO", property.getEdmItem().getDefaultValue()); + } + + @Test + public void checkGetPropertyIsStream() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(PersonImage.class), + "image"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.isStream()); + } + + @Test + public void checkGetTypeBoxedForPrimitive() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class), + "population"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(Long.class, property.getType()); + } + + @Test + public void checkGetTypeBoxed() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class), + "area"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(Integer.class, property.getType()); + } + + @Test(expected = ODataJPAModelException.class) + public void checkThrowsAnExceptionTimestampWithoutPrecision() throws ODataJPAModelException { + // If Precision missing EdmDateTimeOffset.internalValueToString throws an exception => pre-check + final Attribute jpaAttribute = mock(Attribute.class); + final ManagedType jpaManagedType = mock(ManagedType.class); + when(jpaAttribute.getName()).thenReturn("start"); + when(jpaAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.BASIC); + when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer>() { + @Override + public ManagedType answer(InvocationOnMock invocation) throws Throwable { + return jpaManagedType; + } + }); + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Timestamp.class; + } + }); + when(jpaManagedType.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return DummyToBeIgnored.class; + } + }); + + Column column = mock(Column.class); + AnnotatedElement annotations = mock(AnnotatedElement.class, withSettings().extraInterfaces(Member.class)); + when(annotations.getAnnotation(Column.class)).thenReturn(column); + when(jpaAttribute.getJavaMember()).thenReturn((Member) annotations); + when(column.name()).thenReturn("Test"); + + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + property.getEdmItem(); + } + + @Test + public void checkGetProptertyHasProtectionFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), "eTag"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertFalse(property.hasProtection()); + } + + @Test + public void checkGetProptertyHasProtectionTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "username"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertTrue(property.hasProtection()); + } + + @Test + public void checkGetProptertyProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "username"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("Username", actPath.get(0)); + } + + @Test + public void checkGetProptertyNotProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), "eTag"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertTrue(property.getProtectionClaimNames().isEmpty()); + assertTrue(property.getProtectionPath("Username").isEmpty()); + } + + @Test + public void checkGetComplexProptertyProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtectedBy annotation = Mockito.mock(EdmProtectedBy.class); + when(annotation.name()).thenReturn("UserId"); + when(annotation.path()).thenReturn("created/by"); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtectedBy.class, annotation); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + } + + @Test + public void checkGetComplexProptertyTwoProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtections protections = Mockito.mock(EdmProtections.class); + EdmProtectedBy protectedBy1 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy1.name()).thenReturn("UserId"); + when(protectedBy1.path()).thenReturn("created/by"); + + EdmProtectedBy protectedBy2 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy2.name()).thenReturn("UserId"); + when(protectedBy2.path()).thenReturn("updated/by"); + + when(protections.value()).thenReturn(new EdmProtectedBy[] { protectedBy1, protectedBy2 }); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtections.class, protections); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + + List actPath = property.getProtectionPath("UserId"); + assertEquals(2, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + assertEquals("AdministrativeInformation/Updated/By", actPath.get(1)); + } + + @Test + public void checkGetComplexProptertyTwoProtectedAttributeTwoClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtections protections = Mockito.mock(EdmProtections.class); + EdmProtectedBy protectedBy1 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy1.name()).thenReturn("UserId"); + when(protectedBy1.path()).thenReturn("created/by"); + + EdmProtectedBy protectedBy2 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy2.name()).thenReturn("Date"); + when(protectedBy2.path()).thenReturn("created/at"); + + when(protections.value()).thenReturn(new EdmProtectedBy[] { protectedBy1, protectedBy2 }); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtections.class, protections); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + + assertTrue(property.getProtectionClaimNames().contains("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + + assertTrue(property.getProtectionClaimNames().contains("Date")); + actPath = property.getProtectionPath("Date"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/At", actPath.get(0)); + } + + @Ignore + @Test + public void checkGetSRID() { + // Test for spatial data missing + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("customString1")) { + property.setExternalName("ContactPersonName"); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java new file mode 100644 index 0000000000..1671f06893 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java @@ -0,0 +1,108 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_MISSING_PROTECTION_PATH; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_WRONG_PROTECTION_PATH; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_COLLECTION; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_NAVIGATION; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EntityType; +import javax.persistence.metamodel.PluralAttribute; + +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.errormodel.CollectionAttributeProtected; +import com.sap.olingo.jpa.processor.core.errormodel.ComplextProtectedNoPath; +import com.sap.olingo.jpa.processor.core.errormodel.ComplextProtectedWrongPath; +import com.sap.olingo.jpa.processor.core.errormodel.NavigationAttributeProtected; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestIntermediateWrongAnnotation { + private TestHelper helper; + protected static final String PUNIT_NAME = "error"; + protected static EntityManagerFactory emf; + + @Before + public void setup() throws ODataJPAModelException { + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkErrorOnProtectedCollectionAttribute() { + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + CollectionAttributeProtected.class), "inhouseAddress"); + + try { + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(CollectionAttributeProtected.class)); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(NOT_SUPPORTED_PROTECTED_COLLECTION.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedNavigationAttribute() { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(NavigationAttributeProtected.class), + "teams"); + + try { + IntermediateModelElement property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + helper.schema.getEntityType(NavigationAttributeProtected.class), jpaAttribute, helper.schema); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(NOT_SUPPORTED_PROTECTED_NAVIGATION.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedComplexAttributeMissingPath() { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(ComplextProtectedNoPath.class), + "administrativeInformation"); + + try { + IntermediateModelElement property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(COMPLEX_PROPERTY_MISSING_PROTECTION_PATH.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedComplexAttributeWrongPath() { + // ComplextProtectedWrongPath + final EntityType jpaEt = helper.getEntityType(ComplextProtectedWrongPath.class); + try { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), jpaEt, helper.schema); + et.getEdmItem(); + et.getProtections(); + } catch (ODataJPAModelException e) { + assertEquals(COMPLEX_PROPERTY_WRONG_PROTECTION_PATH.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java new file mode 100644 index 0000000000..6b217067e2 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java @@ -0,0 +1,30 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class TestJPAEdmNameBuilder { + private JPAEdmNameBuilder cut; + + @Before + public void setup() throws ODataJPAModelException { + + } + + @Test + public void CheckBuildContainerNameSimple() { + cut = new JPAEdmNameBuilder("cdw"); + assertEquals("CdwContainer", cut.buildContainerName()); + } + + @Test + public void CheckBuildContainerNameComplex() { + cut = new JPAEdmNameBuilder("org.apache.olingo.jpa"); + assertEquals("OrgApacheOlingoJpaContainer", cut.buildContainerName()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java new file mode 100644 index 0000000000..39a0767365 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java @@ -0,0 +1,89 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.Assert.assertEquals; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAPath extends TestMappingRoot { + private JPAEntityType organization; + // private JPAStructuredType postalAddress; + private TestHelper helper; + + @Before + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + organization = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), helper.getEntityType( + Organization.class), helper.schema); + } + + @Test + public void checkOnePathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals("Name1", cut.getAlias()); + } + + @Test + public void checkOnePathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals(1, cut.getPath().size()); + } + + @Test + public void checkOnePathElementElement() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals("name1", cut.getPath().get(0).getInternalName()); + } + + @Test + public void checkOnePathElementFromSuperTypeAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Type"); + assertEquals("Type", cut.getAlias()); + } + + @Test + public void checkTwoPathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals("Address/Country", cut.getAlias()); + } + + @Test + public void checkTwoPathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals(2, cut.getPath().size()); + } + + @Test + public void checkTwoPathElementPathElements() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals("address", cut.getPath().get(0).getInternalName()); + assertEquals("country", cut.getPath().get(1).getInternalName()); + } + + @Test + public void checkThreePathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals("AdministrativeInformation/Created/By", cut.getAlias()); + } + + @Test + public void checkThreePathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals(3, cut.getPath().size()); + } + + @Test + public void checkThreePathElementPathElements() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals("administrativeInformation", cut.getPath().get(0).getInternalName()); + assertEquals("created", cut.getPath().get(1).getInternalName()); + assertEquals("by", cut.getPath().get(2).getInternalName()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java new file mode 100644 index 0000000000..0373f88ca9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java @@ -0,0 +1,25 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import javax.persistence.EntityManagerFactory; + +import org.junit.BeforeClass; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestMappingRoot { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + public static final String BUPA_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner"; + public static final String ORG_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.Organization"; + public static final String ADDR_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData"; + public static final String COMM_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.CommunicationData"; + public static final String ADMIN_CANONICAL_NAME = + "com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision"; + + @BeforeClass + public static void setupClass() { + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java new file mode 100644 index 0000000000..5f6ee2bb9b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java @@ -0,0 +1,36 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class JPAClaimsPairTest { + + @Test + public void checkCreateIntegerPairOnlyMin() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7); + assertEquals((Integer) 7, cut.min); + } + + @Test + public void checkCreateIntegerPairNoUpperBoundry() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7); + assertFalse(cut.hasUpperBoundary); + } + + @Test + public void checkCreateIntegerPair() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7, 10); + assertEquals((Integer) 7, cut.min); + assertEquals((Integer) 10, cut.max); + } + + @Test + public void checkCreateIntegerPairUpperBoundry() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7, 10); + assertTrue(cut.hasUpperBoundary); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java new file mode 100644 index 0000000000..48e7c2928a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java @@ -0,0 +1,116 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.OptimisticLockException; +import javax.persistence.RollbackException; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.batch.BatchFacade; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; + +@RunWith(MockitoJUnitRunner.class) +public class JPAODataBatchProcessorTest { + private JPAODataBatchProcessor cut; + + @Mock + private EntityManager em; + @Mock + private EntityTransaction transaction; + @Mock + private OData odata; + @Mock + private ServiceMetadata serviceMetadata; + @Mock + private BatchFacade facade; + @Mock + private ODataRequest request; + @Mock + private ODataResponse response; + @Mock + private RollbackException e; + @Mock + private JPAODataSessionContextAccess context; + @Mock + private JPACUDRequestHandler cudHandler; + + private List requests; + + @Before + public void setup() { + cut = new JPAODataBatchProcessor(context, em); + cut.init(odata, serviceMetadata); + requests = new ArrayList<>(); + requests.add(request); + when(context.getDebugger()).thenReturn(new JPAEmptyDebugger()); + when(context.getCUDRequestHandler()).thenReturn(cudHandler); + } + + @Test + public void whenNotOptimisticLockRollBackExceptionThenThrowODataJPAProcessorExceptionWithHttpCode500() + throws ODataApplicationException, ODataLibraryException { + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + doThrow(e).when(transaction).commit(); + + try { + cut.processChangeSet(facade, requests); + Assert.fail("Should have thrown ODataJPAProcessorException!"); + } catch (ODataJPAProcessorException e) { + Assert.assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + } + + } + + @Test + public void whenOptimisticLockRollBackExceptionThenThrowODataJPAProcessorExceptionWithHttpCode412() + throws ODataApplicationException, ODataLibraryException { + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + doThrow(e).when(transaction).commit(); + when(e.getCause()).thenReturn(new OptimisticLockException()); + + try { + cut.processChangeSet(facade, requests); + Assert.fail("Should have thrown ODataJPAProcessorException!"); + } catch (ODataJPAProcessorException e) { + Assert.assertEquals(HttpStatusCode.PRECONDITION_FAILED.getStatusCode(), e.getStatusCode()); + } + } + + @Test + public void whenProcessChangeSetCallValidateChangesOnSccess() throws ODataApplicationException, + ODataLibraryException { + cut = new JPAODataBatchProcessor(context, em); + + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + + cut.processChangeSet(facade, requests); + verify(cudHandler, times(1)).validateChanges(em); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java new file mode 100644 index 0000000000..13712d4e8a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java @@ -0,0 +1,58 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +public class JPAODataClaimsProviderTest { + + private JPAODataClaimsProvider cut; + + @Before + public void setup() { + cut = new JPAODataClaimsProvider(); + } + + @Test + public void checkAddSinglePairReturnsOne() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(1, claims.size()); + } + + @Test + public void checkAddThreeSinglePairsReturnsThree() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + cut.add("Test", new JPAClaimsPair<>("Willi")); + cut.add("Test", new JPAClaimsPair<>("Walter")); + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(3, claims.size()); + } + + @Test + public void checkNotProvidedAttributeReturnsEmptyList() { + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(0, claims.size()); + } + + @Test + public void checkAddTwoAttributesSinglePairs() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + cut.add("Dummy", new JPAClaimsPair<>("Willi")); + + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(1, claims.size()); + + claims = cut.get("Dummy"); + assertNotNull(claims); + assertEquals(1, claims.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java new file mode 100644 index 0000000000..ad2b610fbe --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.Assert.fail; + +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.server.api.debug.DebugSupport; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseProcessorFactory; + +public class JPAODataContextAccessDouble implements JPAODataSessionContextAccess { + private final JPAEdmProvider edmProvider; + private final DataSource ds; + private final JPAODataDatabaseOperations context; + private final String[] packageNames; + private final JPAODataPagingProvider pagingProvider; + + public JPAODataContextAccessDouble(final JPAEdmProvider edmProvider, final DataSource ds, + final JPAODataPagingProvider provider, final String... packages) { + super(); + this.edmProvider = edmProvider; + this.ds = ds; + this.context = new JPADefaultDatabaseProcessor(); + this.packageNames = packages; + this.pagingProvider = provider; + } + + @Override + public List getReferences() { + fail(); + return null; + } + + @Override + public DebugSupport getDebugSupport() { + fail(); + return null; + } + + @Override + public JPAODataDatabaseOperations getOperationConverter() { + return context; + } + + @Override + public JPAEdmProvider getEdmProvider() { + return edmProvider; + } + + @Override + public JPAODataDatabaseProcessor getDatabaseProcessor() { + try { + return new JPAODataDatabaseProcessorFactory().create(ds); + } catch (SQLException e) { + fail(); + } + return null; + } + + @Override + public JPAServiceDebugger getDebugger() { + return new JPAEmptyDebugger(); + } + + @Override + public JPACUDRequestHandler getCUDRequestHandler() { + fail(); + return null; + } + + @Override + public String[] getPackageName() { + return packageNames; + } + + @Override + public JPAODataPagingProvider getPagingProvider() { + return pagingProvider; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java new file mode 100644 index 0000000000..52e7a42eb8 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java @@ -0,0 +1,115 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestBatchRequests extends TestBase { + + @Test + public void testOneGetRequestGetResponce() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + List act = helper.getRawBatchResult(); + assertNotNull(act); + } + + @Test + public void testOneGetRequestCheckStatus() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + assertEquals(200, helper.getBatchResultStatus(1)); + } + + @Test + public void testOneGetRequestCheckValue() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + JsonNode value = helper.getBatchResult(1); + assertEquals("3", value.get("ID").asText()); + } + + @Test + public void testTwoGetRequestSecondFailCheckStatus() throws IOException, ODataException { + StringBuffer requestBody = createBodyTwoGetOneFail(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + assertEquals(404, helper.getBatchResultStatus(2)); + } + + @Test + public void testTwoGetRequestCheckValue() throws IOException, ODataException { + StringBuffer requestBody = createBodyTwoGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + JsonNode value = helper.getBatchResult(2); + assertEquals("5", value.get("ID").asText()); + } + + private StringBuffer createBodyTwoGetOneFail() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET AdministrativeDivision HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } + + private StringBuffer createBodyTwoGet() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('5') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } + + private StringBuffer createBodyOneGet() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java new file mode 100644 index 0000000000..5fdedfe9fd --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java @@ -0,0 +1,298 @@ +package com.sap.olingo.jpa.processor.core.api.example; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.queryoption.OrderByItem; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; +import org.apache.olingo.server.api.uri.queryoption.TopOption; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.api.JPAODataPage; +import com.sap.olingo.jpa.processor.core.query.JPACountQuery; + +public class JPAExamplePagingProviderTest { + private JPACountQuery countQuery; + + @Before + public void setup() throws ODataApplicationException { + countQuery = mock(JPACountQuery.class); + when(countQuery.countResults()).thenReturn(10L); + } + + @Test + public void testReturnDefaultTopSkipPageSize2() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(2, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSize5() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(5, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSizeOther() throws ODataApplicationException { + final UriInfo info = buildUriInfo("AdministrativeDivisions", "AdministrativeDivision"); + final JPAExamplePagingProvider cut = createOrgCut(5); + when(countQuery.countResults()).thenReturn(12L); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(10, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSize5NextPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertEquals(5, act.getSkip()); + assertEquals(5, act.getTop()); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnNullIfEntitySetIsUnknown() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createPersonCut(5); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertNull(act); + } + + @Test + public void testReturnNullIfEntitySetIsUnknownButMaxpagesizeHeader() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createPersonCut(5); + final JPAODataPage act = cut.getFirstPage(info, 3, countQuery, null); + + assertNull(act); + } + + @Test + public void testReturnRespectMaxpagesizeHeader() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + final JPAODataPage act = cut.getFirstPage(info, 3, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(3, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnSkiptokenNullAtLastPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNull(act.getSkiptoken()); + } + + @Test + public void testReturnSkiptokenNullOnlyOnePage() throws ODataApplicationException { + final UriInfo info = buildUriInfo("AdministrativeDivisions", "AdministrativeDivision"); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertNull(act.getSkiptoken()); + } + + @Test + public void testReturnSkiptokenIfNotLastPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNotNull(toODataString((String) act.getSkiptoken())); + } + + @Test + public void testReturnThirdPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNotNull(toODataString((String) act.getSkiptoken())); + } + + @Test + public void testRespectTopSkipOfUriFirstPageLowerMaxSize() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(10); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(2, act.getSkip()); + assertEquals(7, act.getTop()); + } + + @Test + public void testRespectTopSkipOfUriFirstPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(2, act.getSkip()); + assertEquals(5, act.getTop()); + } + + @Test + public void testRespectTopSkipOfUriNextPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertEquals(7, act.getSkip()); + assertEquals(2, act.getTop()); + } + + @Test + public void testBufferFilled() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final Map sizes = new HashMap<>(); + sizes.put("Organizations", 2); + + final JPAExamplePagingProvider cut = new JPAExamplePagingProvider(sizes, 2); + final JPAODataPage first = cut.getFirstPage(info, null, countQuery, null); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + final JPAODataPage second = cut.getNextPage((String) first.getSkiptoken()); + assertNotNull(cut.getNextPage((String) second.getSkiptoken())); + final JPAODataPage third = cut.getNextPage((String) second.getSkiptoken()); + assertNotNull(cut.getNextPage((String) third.getSkiptoken())); + assertNull(cut.getNextPage((String) first.getSkiptoken())); + } + + @Test + public void testBufferNotFilled() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final Map sizes = new HashMap<>(); + sizes.put("Organizations", 2); + + final JPAExamplePagingProvider cut = new JPAExamplePagingProvider(sizes, 10); + final JPAODataPage first = cut.getFirstPage(info, null, countQuery, null); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + final JPAODataPage second = cut.getNextPage((String) first.getSkiptoken()); + assertNotNull(cut.getNextPage((String) second.getSkiptoken())); + final JPAODataPage third = cut.getNextPage((String) second.getSkiptoken()); + assertNotNull(cut.getNextPage((String) third.getSkiptoken())); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + } + + private UriInfo buildUriInfo() { + return buildUriInfo("Organizations", "Organization"); + } + + private UriInfo buildUriInfo(final String esName, final String etName) { + final UriInfo uriInfo = mock(UriInfo.class); + final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class); + final EdmEntitySet es = mock(EdmEntitySet.class); + final EdmType type = mock(EdmType.class); + final OrderByOption order = mock(OrderByOption.class); + final OrderByItem orderItem = mock(OrderByItem.class); + final Member orderExpression = mock(Member.class); + final UriInfoResource orderResourcePath = mock(UriInfoResource.class); + final UriResourcePrimitiveProperty orderResourcePathItem = mock(UriResourcePrimitiveProperty.class); + final EdmProperty orderProperty = mock(EdmProperty.class); + final List orderItems = new ArrayList<>(); + final List orderResourcePathItems = new ArrayList<>(); + + orderItems.add(orderItem); + orderResourcePathItems.add(orderResourcePathItem); + when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet); + when(uriEs.getEntitySet()).thenReturn(es); + when(uriEs.getType()).thenReturn(type); + when(es.getName()).thenReturn(esName); + when(type.getNamespace()).thenReturn("com.sap.olingo.jpa"); + when(type.getName()).thenReturn(etName); + when(order.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY); + when(orderItem.isDescending()).thenReturn(true); + when(orderItem.getExpression()).thenReturn(orderExpression); + when(orderExpression.getResourcePath()).thenReturn(orderResourcePath); + when(orderResourcePath.getUriResourceParts()).thenReturn(orderResourcePathItems); + when(orderResourcePathItem.getProperty()).thenReturn(orderProperty); + when(orderProperty.getName()).thenReturn("ID"); + when(order.getOrders()).thenReturn(orderItems); + final List resourceParts = new ArrayList<>(); + resourceParts.add(uriEs); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriInfo.getOrderByOption()).thenReturn(order); + return uriInfo; + } + + private void addTopSkipToUri(final UriInfo info) { + final SkipOption skipOption = mock(SkipOption.class); + final TopOption topOption = mock(TopOption.class); + + when(skipOption.getValue()).thenReturn(2); + when(topOption.getValue()).thenReturn(7); + when(info.getSkipOption()).thenReturn(skipOption); + when(info.getTopOption()).thenReturn(topOption); + + } + + private JPAExamplePagingProvider createOrgCut(final int size) { + final Map sizes = new HashMap<>(); + sizes.put("Organizations", size); + sizes.put("AdministrativeDivisions", 10); + return new JPAExamplePagingProvider(sizes); + } + + private JPAExamplePagingProvider createPersonCut(final int size) { + final Map sizes = new HashMap<>(); + sizes.put("Persons", size); + return new JPAExamplePagingProvider(sizes); + } + + private String toODataString(final String skiptoken) { + return "'" + skiptoken + "'"; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java new file mode 100644 index 0000000000..03d1c1871c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java @@ -0,0 +1,89 @@ +package com.sap.olingo.jpa.processor.core.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey; + +public class TestODataJPAProcessorException { + // private static String BUNDLE_NAME = "exceptions-i18n"; + + public static enum MessageKeys implements ODataJPAMessageKey { + RESULT_NOT_FOUND; + + @Override + public String getKey() { + return name(); + } + + } + + @Test + public void checkSimpleRaiseExeption() { + try { + RaiseExeption(); + } catch (ODataApplicationException e) { + assertEquals("No result was fond by Serializer", e.getMessage()); + assertEquals(400, e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void checkSimpleViaMessageKeyRaiseExeption() { + try { + RaiseExeptionParam(); + } catch (ODataApplicationException e) { + assertEquals("Unable to convert value 'Willi' of parameter 'Hugo'", e.getMessage()); + assertEquals(500, e.getStatusCode()); + return; + } + fail(); + } + + private void RaiseExeptionParam() throws ODataJPAProcessException { + throw new ODataJPADBAdaptorException(ODataJPADBAdaptorException.MessageKeys.PARAMETER_CONVERSION_ERROR, + HttpStatusCode.INTERNAL_SERVER_ERROR, "Willi", "Hugo"); + } + + private void RaiseExeption() throws ODataJPAProcessException { + throw new ODataJPASerializerException(ODataJPASerializerException.MessageKeys.RESULT_NOT_FOUND, + HttpStatusCode.BAD_REQUEST); + } + +// private class TestException extends ODataJPAProcessException { +// private static final long serialVersionUID = 1L; +// +// public TestException(Throwable e, final HttpStatusCode statusCode) { +// super(e, statusCode); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, +// final Throwable cause, final String... params) { +// super(messageKey.getKey(), statusCode, cause, params); +// } +// +// public TestException(final String id, final HttpStatusCode statusCode) { +// super(id, statusCode); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, +// final String... params) { +// super(messageKey.getKey(), statusCode, params); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) { +// super(messageKey.getKey(), statusCode, e); +// } +// +// @Override +// protected String getBundleName() { +// return BUNDLE_NAME; +// } +// } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java new file mode 100644 index 0000000000..f54b073eba --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java @@ -0,0 +1,211 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigDecimal; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperatorImp; +import com.sap.olingo.jpa.processor.core.filter.JPABooleanOperatorImp; +import com.sap.olingo.jpa.processor.core.filter.JPALiteralOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAMemberOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAOperationConverter; + +public class TestJPAArithmeticOperator { + private CriteriaBuilder cb; + + private JPAOperationConverter converter; + private Path expression; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws Exception { + converter = mock(JPAOperationConverter.class); + cb = mock(CriteriaBuilder.class); + expression = mock(Path.class); + } + + @Test + public void testMemberLiteralGetLeft_Member() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPALiteralOperator right = mock(JPALiteralOperator.class); + + when(right.get()).thenReturn(5); + when(left.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + } + + @Test + public void testLiteralMemberGetLeft_Member() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + + when(left.get()).thenReturn(5); + when(right.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetLeftLiteralLiteral_Left() throws ODataApplicationException { + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + Integer leftValue = new Integer(5); + + final Expression result = mock(Expression.class); + + when(left.get()).thenReturn(leftValue); + when(right.get()).thenReturn(10); + + when(cb.literal(leftValue)).thenAnswer(new Answer>() { + @Override + public Expression answer(InvocationOnMock invocation) throws Throwable { + invocation.getArguments(); + return result; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + Expression act = cut.getLeft(cb); + assertEquals(result, act); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetLeftMemberMember_Left() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPAMemberOperator left = mock(JPAMemberOperator.class); + + final Path expressionRight = mock(Path.class); + + when(right.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expressionRight; + } + }); + when(left.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + + } + + @Test + public void testMemberLiteralGetRightAsNumber_Right() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(right.get(attribute)).thenReturn(new BigDecimal("5.1")); + when(left.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testLiteralMemberGetRightAsNumber_Left() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(left.get(attribute)).thenReturn(new BigDecimal("5.1")); + when(right.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testLiteralLiteralGetRightAsNumber_Right() throws ODataApplicationException { + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + + when(left.get()).thenReturn(new BigDecimal("5.1")); + when(right.get()).thenReturn(new BigDecimal("10.1")); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("10.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testGetMemberMemberGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(left.determineAttribute()).thenReturn(attribute); + when(right.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } + + @Test + public void testGetBooleanMemberGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPABooleanOperatorImp left = mock(JPABooleanOperatorImp.class); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } + + @Test + public void testGetMemberBooleanGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPABooleanOperatorImp right = mock(JPABooleanOperatorImp.class); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java new file mode 100644 index 0000000000..5848699666 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java @@ -0,0 +1,152 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPACustomScalarFunctions { + + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + protected static DataSource ds; + + @BeforeClass + public static void setupClass() throws ODataJPAModelException { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + CreateDenfityFunction(); + } + + @AfterClass + public static void tearDownClass() throws ODataJPAModelException { + DropDenfityFunction(); + } + + @Test + public void testFilterOnFunction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) gt 1"); + helper.assertStatus(200); + } + + @Test + public void testFilterOnFunctionAndProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) mul 1000000 gt 1000 and ParentDivisionCode eq 'BE255'&orderBy=DivisionCode)"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + assertEquals("35002", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterOnFunctionAndMultiply() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area,Population=Population) mul 1000000 gt 100"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(59, orgs.size()); + } + + @Test + public void testFilterOnFunctionWithFixedValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=13079087,Population=$it/Population) mul 1000000 gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(29, orgs.size()); + } + + @Test + public void testFilterOnFunctionComuteValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area div 1000000,Population=Population) gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterOnFunctionMixParamOrder() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Population=Population,Area=Area) mul 1000000 gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + private static void CreateDenfityFunction() { + EntityManager em = emf.createEntityManager(); + EntityTransaction t = em.getTransaction(); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append( + "CREATE FUNCTION \"OLINGO\".\"PopulationDensity\" (UnitArea INT, Population BIGINT ) "); + sqlString.append("RETURNS DOUBLE "); + sqlString.append("BEGIN ATOMIC "); // + sqlString.append(" DECLARE aDouble DOUBLE; "); // + sqlString.append(" DECLARE pDouble DOUBLE; "); + sqlString.append(" SET aDouble = UnitArea; "); + sqlString.append(" SET pDouble = Population; "); + sqlString.append(" IF UnitArea <= 0 THEN RETURN 0; "); + sqlString.append(" ELSE RETURN pDouble / aDouble; "); // * 1000000 + sqlString.append(" END IF; "); // + sqlString.append("END"); + + t.begin(); + Query q = em.createNativeQuery(sqlString.toString()); + q.executeUpdate(); + t.commit(); + } + + private static void DropDenfityFunction() { + EntityManager em = emf.createEntityManager(); + EntityTransaction t = em.getTransaction(); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("DROP FUNCTION \"OLINGO\".\"PopulationDensity\""); + + t.begin(); + Query q = em.createNativeQuery(sqlString.toString()); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java new file mode 100644 index 0000000000..5b1df5e86c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java @@ -0,0 +1,96 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; + +public class TestJPAFunctionOperator { + private CriteriaBuilder cb; + private JPAFunctionOperator cut; + private UriResourceFunction uriFunction; + private JPAVisitor jpaVisitor; + private JPADataBaseFunction jpaFunction; + private JPAOperationResultParameter jpaResultParam; + private List uriParams; + + @Before + public void setUp() throws Exception { + + cb = mock(CriteriaBuilder.class); + jpaVisitor = mock(JPAVisitor.class); + when(jpaVisitor.getCriteriaBuilder()).thenReturn(cb); + uriFunction = mock(UriResourceFunction.class); + jpaFunction = mock(JPADataBaseFunction.class); + jpaResultParam = mock(JPAOperationResultParameter.class); + when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam); + List resources = new ArrayList(); + resources.add(uriFunction); + + uriParams = new ArrayList(); + + cut = new JPAFunctionOperator(jpaVisitor, uriParams, jpaFunction); + } + + @SuppressWarnings("unchecked") + @Test + public void testReturnsExpression() throws ODataApplicationException { + + final Expression[] jpaParameter = new Expression[0]; + + when(jpaFunction.getDBName()).thenReturn("Test"); + doReturn(new Integer(5).getClass()).when(jpaResultParam).getType(); + when(cb.function(jpaFunction.getDBName(), jpaResultParam.getType(), jpaParameter)).thenReturn(mock( + Expression.class)); + when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam); + Expression act = cut.get(); + assertNotNull(act); + } + + @Test + public void testAbortOnNonFunctionReturnsCollection() { + + when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings"); + when(jpaResultParam.isCollection()).thenReturn(true); + + try { + cut.get(); + } catch (ODataApplicationException e) { + return; + } + fail("Function provided not checked"); + } + + @Test + public void testAbortOnNonScalarFunction() { + + when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings"); + when(jpaResultParam.isCollection()).thenReturn(false); + doReturn(AdministrativeDivision.class).when(jpaResultParam).getType(); + + try { + cut.get(); + } catch (ODataApplicationException e) { + return; + } + fail("Function provided not checked"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java new file mode 100644 index 0000000000..bb38f7f370 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java @@ -0,0 +1,180 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; +import com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperatorImp; +import com.sap.olingo.jpa.processor.core.filter.JPALiteralOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAMemberOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAOperationConverter; + +public class TestJPAOperationConverter { + private CriteriaBuilder cb; + + private Expression expressionLeft; + private Expression expressionRight; + private JPAOperationConverter cut; + private JPAODataDatabaseOperations extension; + + @SuppressWarnings("unchecked") + @Before + public void setUp() throws Exception { + cb = mock(CriteriaBuilder.class); + extension = mock(JPAODataDatabaseOperations.class); + cut = new JPAOperationConverter(cb, extension); + expressionLeft = mock(Path.class); + expressionRight = mock(Path.class); + } + + @Test + public void testAddMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.sum(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testAddMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.sum(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testSubMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.diff(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testSubMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.diff(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testDivMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.quot(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testDivMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.quot(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testMulMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.prod(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testMulMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.prod(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testUnknownOperation_CallExtension() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.AND); + when(extension.convert(operator)).thenThrow(new ODataApplicationException(null, HttpStatusCode.NOT_IMPLEMENTED + .getStatusCode(), null)); + + try { + cut.convert(operator); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + return; + } + fail("Exception expecetd"); + } +} + +//case MOD: \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java new file mode 100644 index 0000000000..20ea1aae61 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java @@ -0,0 +1,911 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Ignore; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryWhereClause extends TestBase { + + @Test + public void testFilterOneEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID eq '3'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("3", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneDescriptionEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=LocationName eq 'Deutschland'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("10", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneDescriptionEqualsFieldNotSelected() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=LocationName eq 'Deutschland'&$select=ID"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("10", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEnumEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=ABCClass eq com.sap.olingo.jpa.ABCClassifiaction'A'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("1", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEqualsTwoProperties() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode eq CountryCode"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterOneEqualsInvert() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter='3' eq ID"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("3", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneNotEqual() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID ne '3'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(9, orgs.size()); + } + + @Test + public void testFilterOneEnumNotEqual() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights ne com.sap.olingo.jpa.AccessRights'Write'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("97", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEnumEqualMultipleValues() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights eq com.sap.olingo.jpa.AccessRights'Read,Delete'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("97", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneGreaterEqualsString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID ge '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); // '10' is smaller than '5' when comparing strings! + } + + @Test + public void testFilterOneLowerThanTwoProperties() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode lt CountryCode"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(244, orgs.size()); + } + + @Test + public void testFilterOneGreaterThanString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID gt '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); // '10' is smaller than '5' when comparing strings! + } + + @Test + public void testFilterOneLowerThanString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID lt '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + } + + @Test + public void testFilterOneLowerEqualsString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID le '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(6, orgs.size()); + } + + @Test + public void testFilterOneGreaterEqualsNumber() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "AdministrativeDivisions?$filter=Area ge 119330610"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Ignore // TODO Clarify if GT, LE .. not supported by OData or "only" by Olingo + @Test + public void testFilterOneEnumGreaterThan() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights gt com.sap.olingo.jpa.AccessRights'Read'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("99", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterOneOrEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=ID eq '5' or ID eq '10'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterOneNotLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=not (Area lt 50000000)"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(24, orgs.size()); + } + + @Test + public void testFilterTwoAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2' and DivisionCode eq 'BE25'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("BEL", orgs.get(0).get("CountryCode").asText()); + } + + @Test + public void testFilterAndOrEqualsParenthesis() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and (DivisionCode eq 'BE25' or DivisionCode eq 'BE24')&$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + assertEquals("BE25", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndOrEqualsNoParenthesis() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and DivisionCode eq 'BE25' or CodeID eq '3166-1'&$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + assertEquals("USA", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithFunction1() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(tolower(DivisionCode),tolower('BE1'))&$orderby=DivisionCode asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithFunction2() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(DivisionCode,'BE1')&$orderby=DivisionCode asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithComparisonContainingFunction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and tolower(DivisionCode) eq tolower('BE1')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAddGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area add 7000000 ge 50000000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(31, orgs.size()); + } + + @Test + public void testFilterSubGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area sub 7000000 ge 60000000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(15, orgs.size()); + } + + @Test + public void testFilterDivGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area gt 0 and Area div Population ge 6000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(9, orgs.size()); + } + + @Test + public void testFilterMulGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area mul Population gt 0"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(64, orgs.size()); + } + + @Test + public void testFilterMod() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area gt 0 and Area mod 3578335 eq 0"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterLength() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=length(Name) eq 10"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterNow() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AdministrativeInformation/Created/At lt now()"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testFilterContains() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=contains(CodeID,'166')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(110, orgs.size()); + } + + @Test + public void testFilterEndswith() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=endswith(CodeID,'166-1')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterStartswith() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=startswith(DivisionCode,'DE-')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(16, orgs.size()); + } + + @Test + public void testFilterIndexOf() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=indexof(DivisionCode,'3') eq 4"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterSubstringStartIndex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,6) eq 'Dakota'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterSubstringStartEndIndex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,5) eq 'North'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterSubstringLengthCalculated() throws IOException, ODataException { + // substring(CompanyName, 1 add 4, 2 mul 3) + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,1 add 4) eq 'North'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Ignore // Usage of mult currently creates parser error: The types 'Edm.Double' and '[Int64, Int32, Int16, Byte, + // SByte]' are not compatible. + @Test + public void testFilterSubstringStartCalculated() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,2 mul 3) eq 'Dakota'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterToLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(Name) eq 'brandenburg'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterToUpper() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and toupper(Name) eq 'HESSEN'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterToUpperInvers() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=toupper('nuts1') eq CodeID"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(19, orgs.size()); + } + + @Test + public void testFilterTrim() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and trim(Name) eq 'Sachsen'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterConcat() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=concat(concat(LastName,','),FirstName) eq 'Mustermann,Max'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Roles/any(d:d/RoleCategory eq 'A')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueNotAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=not (Roles/any(d:d/RoleCategory eq 'A'))"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAnyMultiParameter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/any(d:d/RoleCategory eq 'A' and d/BusinessPartnerID eq '1')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAnyNoRestriction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Roles/any()"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAll() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/all(d:d/RoleCategory eq 'A')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterCountNavigationProperty() throws IOException, ODataException { + // https://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301 + // Example 43: return all Categories with less than 10 products + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/$count eq 2"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterCountNavigationPropertyMultipleHops() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=AdministrativeInformation/Created/User/Roles/$count ge 2"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToOneValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToOneValueAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE34'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyToOneValueTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE212'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyToOneValueViaComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LastName eq 'Mustermann'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionViaComplexTypeWOSubselectSelectAll() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Address/RegionName eq 'Kalifornien'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionViaComplexTypeWOSubselectSelectId() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Address/RegionName eq 'Kalifornien'&$select=ID"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect1() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect2() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'&$select=ID"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyAndExandThatNavigationProperty() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/DivisionCode eq 'BE2'&$expand=Parent"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(5, admin.size()); + assertNotNull(admin.get(3).findValue("Parent")); + assertFalse(admin.get(3).findValue("Parent") instanceof NullNode); + assertEquals("BE2", admin.get(3).findValue("Parent").get("DivisionCode").asText()); + }; + + @Test + public void testFilterNavigationPropertyViaJoinTableSubtype() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=SupportedOrganizations/any()"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Ignore // EclipsLinkProblem see https://bugs.eclipse.org/bugs/show_bug.cgi?id=529565 + @Test + public void testFilterNavigationPropertyViaJoinTableCountSubType() throws IOException, // NOSONAR + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=SupportedOrganizations/$count gt 1"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Test + public void testFilterMappedNavigationPropertyViaJoinTableSubtype() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=Name1&$filter=SupportEngineers/any(d:d/LastName eq 'Doe')"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(1, admin.size()); + assertEquals("First Org.", admin.get(0).findValue("Name1").asText()); + + }; + + @Test + public void testFilterNavigationPropertyViaJoinTableCount() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=Teams/$count eq 0&$select=ID"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(1, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Test + public void testFilterMappedNavigationPropertyViaJoinTableFilter() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Teams?$select=Name&$filter=Member/any(d:d/LastName eq 'Mustermann')"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + }; + + @Test + public void testFilterWithAllExpand() throws ODataException, IOException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Name1 eq 'Third Org.'&$expand=Roles"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + assertEquals(3, org.get(0).get("Roles").size()); + } + + @Test + public void testFilterSubstringStartEndIndexToLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(substring(Name,0,5)) eq 'north'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterOneHas() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights has com.sap.olingo.jpa.AccessRights'Read'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationTarget() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode result = (ObjectNode) div.get("value").get(0); + assertNotNull(result); + assertEquals("BE21", result.get("DivisionCode").asText()); + } + + @Test + public void testFilterCollectionSinplePropertyThrowsError() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=contains(Comment, 'just')"); + + helper.assertStatus(400); // Olingo rejects a bunch of functions. + } + + @Test + public void testFilterCollectionPropertyAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Comment/any(s:contains(s, 'just'))"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + } + + @Test + public void testFilterCollectionPropertyDeepSimpleCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 2&$select=ID"); + + helper.assertStatus(200); + ArrayNode deep = helper.getValues(); + assertNotNull(deep); + assertEquals(1, deep.size()); + } + + @Test + public void testFilterCollectionPropertyDeepComplexCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/$count eq 2&$select=ID"); + + helper.assertStatus(200); + ArrayNode deep = helper.getValues(); + assertNotNull(deep); + assertEquals(1, deep.size()); + } + + @Test + public void testFilterCollectionPropertyAsPartOfComplexAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/any(s:s/TaskID eq 'DEV')"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + } + + @Test + public void testFilterCollectionOnPropertyWithNavigation() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')/InhouseAddress?$filter=TaskID eq 'DEV'"); + + helper.assertStatus(200); + ArrayNode addr = helper.getValues(); + assertNotNull(addr); + assertEquals(1, addr.size()); + } + + @Test + public void testFilterCollectionPropertyWithOutNavigationThrowsError() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=InhouseAddress/TaskID eq 'DEV'"); + + helper.assertStatus(400); // The URI is malformed + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java new file mode 100644 index 0000000000..eac6396aff --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java @@ -0,0 +1,82 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; + +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; +import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery; + +public class TestJPAVisitor { + + private JPAFilterComplierAccess compiler; + private JPAAbstractQuery query; + private JPAExpressionVisitor cut; + private JPAODataDatabaseOperations extension; + private JPAOperationConverter converter; + + @Before + public void setUp() { + extension = mock(JPAODataDatabaseOperations.class); + converter = new JPAOperationConverter(mock(CriteriaBuilder.class), extension); + compiler = mock(JPAFilterComplierAccess.class); + query = mock(JPAAbstractQuery.class); + + when(compiler.getConverter()).thenReturn(converter); + when(compiler.getParent()).thenReturn(query); + when(compiler.getDebugger()).thenReturn(mock(JPAServiceDebugger.class)); + when(query.getDebugger()).thenReturn(mock(JPAServiceDebugger.class)); + + cut = new JPAVisitor(compiler); + } + +//return new JPAFunctionOperator(jpaFunction, odataParams, this.jpaComplier.getParent().getRoot(), jpaComplier.getConverter().cb); + + @Test + public void createFunctionOperation() throws ExpressionVisitException, ODataApplicationException { + +// final UriResource resource = member.getResourcePath().getUriResourceParts().get(0); + Member member = mock(Member.class); + UriInfoResource info = mock(UriInfoResource.class); + UriResourceFunction uriFunction = mock(UriResourceFunction.class); + + List resources = new ArrayList<>(); + resources.add(uriFunction); + + when(member.getResourcePath()).thenReturn(info); + when(info.getUriResourceParts()).thenReturn(resources); +// final JPAFunction jpaFunction = this.jpaComplier.getSd().getFunction(((UriResourceFunction) resource).getFunction()); + JPAServiceDocument sd = mock(JPAServiceDocument.class); + JPADataBaseFunction jpaFunction = mock(JPADataBaseFunction.class); + EdmFunction edmFunction = mock(EdmFunction.class); + + when(uriFunction.getFunction()).thenReturn(edmFunction); + when(compiler.getSd()).thenReturn(sd); + when(sd.getFunction(edmFunction)).thenReturn(jpaFunction); + when(uriFunction.getParameters()).thenReturn(new ArrayList()); + + if (!(cut.visitMember(member) instanceof JPAFunctionOperator)) { + fail(); + } + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java new file mode 100644 index 0000000000..6910c02f3a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java @@ -0,0 +1,49 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestRetrieveSingleEntity extends TestBase { + + @Test + public void testRetrieveWithOneKey() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("3", org.get("ID").asText()); + } + + @Test + public void testRetrieveWithTwoKeys() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("1", org.get("BusinessPartnerID").asText()); + assertEquals("A", org.get("RoleCategory").asText()); + } + + @Test + public void testRetrieveWithEmbeddedKey() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='en')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("en", org.get("Language").asText()); + assertEquals("NUTS1", org.get("CodeID").asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java new file mode 100644 index 0000000000..3eab24d5c5 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java @@ -0,0 +1,574 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlProperty; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.query.EdmEntitySetInfo; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRights; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRightsConverter; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DateConverter; + +public class TestJPACUDRequestHelper { + private JPAConversionHelper cut; + + @Before + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Test + public void testInstanceNull() { + + try { + cut.buildGetterMap(null); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testInstanceWithoutGetter() throws ODataJPAProcessorException { + + Map act = cut.buildGetterMap(new DateConverter()); + assertNotNull(act); + assertEquals(1, act.size()); + assertNotNull(act.get("class")); + } + + @Test + public void testInstanceWithGetter() throws ODataJPAProcessorException { + BusinessPartnerRole role = new BusinessPartnerRole(); + role.setBusinessPartnerID("ID"); + + Map act = cut.buildGetterMap(role); + assertNotNull(act); + assertEquals(5, act.size()); + assertEquals("ID", act.get("businessPartnerID")); + } + + @Test + public void testSameInstanceWhenReadingTwice() throws ODataJPAProcessorException { + BusinessPartnerRole role = new BusinessPartnerRole(); + + Map exp = cut.buildGetterMap(role); + Map act = cut.buildGetterMap(role); + + assertTrue(exp == act); + } + + @Ignore + @Test + public void testDifferentInstanceWhenReadingDifferentInstance() throws ODataJPAProcessorException { + + Map exp = cut.buildGetterMap(new BusinessPartnerRole("100", "A")); + Map act = cut.buildGetterMap(new BusinessPartnerRole("100", "A")); + + assertFalse(exp == act); + } + + @Test + public void testConvertEmptyInputStream() throws UnsupportedEncodingException { + final ODataRequest request = mock(ODataRequest.class); + final EdmEntitySetInfo etsInfo = mock(EdmEntitySetInfo.class); + final EdmEntitySet ets = mock(EdmEntitySet.class); + + final InputStream is = new ByteArrayInputStream("".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + when(etsInfo.getTargetEdmEntitySet()).thenReturn(ets); + + try { + cut.convertInputStream(OData.newInstance(), request, ContentType.APPLICATION_JSON, etsInfo); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertInputStream() throws UnsupportedEncodingException, ODataJPAProcessorException, + EdmPrimitiveTypeException { + + final ODataRequest request = mock(ODataRequest.class); + final EdmEntitySetInfo edmEntitySetInfo = mock(EdmEntitySetInfo.class); + final EdmEntitySet edmEntitySet = mock(EdmEntitySet.class); + final EdmEntityType edmEntityType = mock(EdmEntityType.class); + final EdmProperty edmPropertyId = mock(EdmProperty.class); + final EdmPrimitiveType edmTypeId = mock(EdmPrimitiveType.class); + + FullQualifiedName fqn = new FullQualifiedName("test", "Organisation"); + FullQualifiedName fqnString = new FullQualifiedName("test", "Organisation"); + + List propertyNames = new ArrayList<>(); + propertyNames.add("ID"); + + when(edmTypeId.getFullQualifiedName()).thenReturn(fqnString); + when(edmTypeId.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + when(edmTypeId.getName()).thenReturn("String"); + when(edmTypeId.valueOfString(ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyInt(), + ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), + (Class) ArgumentMatchers.any())).thenReturn("35"); + + when(edmEntitySet.getEntityType()).thenReturn(edmEntityType); + when(edmEntityType.getFullQualifiedName()).thenReturn(fqn); + when(edmEntityType.getPropertyNames()).thenReturn(propertyNames); + when(edmEntityType.getProperty("ID")).thenReturn(edmPropertyId); + when(edmPropertyId.getName()).thenReturn("ID"); + when(edmPropertyId.getType()).thenReturn(edmTypeId); + when(edmEntitySetInfo.getEdmEntitySet()).thenReturn(edmEntitySet); + when(edmEntitySetInfo.getTargetEdmEntitySet()).thenReturn(edmEntitySet); + InputStream is = new ByteArrayInputStream("{\"ID\" : \"35\"}".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + + Entity act = cut.convertInputStream(OData.newInstance(), request, ContentType.APPLICATION_JSON, edmEntitySetInfo); + assertEquals("35", act.getProperty("ID").getValue()); + } + + @Test + public void testConvertPropertiesEmptyList() throws ODataJPAProcessException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(0, act.size()); + } + + @Test + public void testConvertPropertiesUnknownValueType() { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + + when(propertyID.getValueType()).thenReturn(ValueType.COLLECTION_ENTITY); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + try { + cut.convertProperties(OData.newInstance(), st, odataProperties); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertPropertiesConvertException() throws ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("iD"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + when(st.getPath(ArgumentMatchers.anyString())).thenThrow(new ODataJPAModelException(new NullPointerException())); + try { + cut.convertProperties(OData.newInstance(), st, odataProperties); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertPropertiesOnePrimitiveProperty() throws ODataJPAProcessException, ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ID")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("iD"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return String.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("35", act.get("iD")); + } + + @Test + public void testConvertPropertiesOneEnumPropertyWithoutConverter() throws ODataJPAProcessException, + ODataJPAModelException { + + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ABCClass")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("aBCClass"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return ABCClassifiaction.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(attribute.isEnum()).thenReturn(true); + when(propertyID.getValueType()).thenReturn(ValueType.ENUM); + when(propertyID.getName()).thenReturn("ABCClass"); + when(propertyID.getValue()).thenReturn(1); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals(ABCClassifiaction.B, act.get("aBCClass")); + } + + @Test + public void testConvertPropertiesOneEnumPropertyWithConverter() throws ODataJPAProcessException, + ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("AccessRights")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("accessRights"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return AccessRights.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(attribute.getConverter()).thenAnswer(new Answer>() { + @Override + public AttributeConverter answer(InvocationOnMock invocation) throws Throwable { + return new AccessRightsConverter(); + } + }); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.ENUM); + when(propertyID.getName()).thenReturn("AccessRights"); + when(propertyID.getValue()).thenReturn((short) 8); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + AccessRights[] actProperty = (AccessRights[]) act.get("accessRights"); + assertArrayEquals(new Object[] { AccessRights.Delete }, actProperty); + } + + @Test + public void testConvertPropertiesOneComplexProperty() throws ODataJPAProcessException, ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath pathID = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ID")).thenReturn(pathID); + when(pathID.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("iD"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return String.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + ComplexValue cv = new ComplexValue(); + List addressPathElements = new ArrayList<>(); + JPAElement addressElement = mock(JPAElement.class); + addressPathElements.add(addressElement); + when(addressElement.getInternalName()).thenReturn("address"); + + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(cv); + odataProperties.add(propertyAddress); + JPAPath pathAddress = mock(JPAPath.class); + when(st.getPath("Address")).thenReturn(pathAddress); + when(pathAddress.getPath()).thenReturn(addressPathElements); + JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(2, act.size()); + assertTrue(act.get("address") instanceof Map); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesOneComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final List addressProperties = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + final ComplexValue cv1 = mock(ComplexValue.class); + + final Property propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(32); + addressProperties.add(propertyNumber); + when(cv1.getValue()).thenReturn(addressProperties); + + odataComment.add(cv1); + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(1, ((List>) act.get("address")).size()); + Map actAddr = (Map) ((List) act.get("address")).get(0); + assertEquals(32, actAddr.get("number")); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesTwoComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + List addressProperties = new ArrayList<>(); + final ComplexValue cv1 = mock(ComplexValue.class); + Property propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(32); + addressProperties.add(propertyNumber); + when(cv1.getValue()).thenReturn(addressProperties); + + addressProperties = new ArrayList<>(); + final ComplexValue cv2 = mock(ComplexValue.class); + propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(16); + addressProperties.add(propertyNumber); + when(cv2.getValue()).thenReturn(addressProperties); + + odataComment.add(cv1); + odataComment.add(cv2); + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(2, ((List>) act.get("address")).size()); + Map actAddr1 = (Map) ((List) act.get("address")).get(0); + assertEquals(32, actAddr1.get("number")); + + Map actAddr2 = (Map) ((List) act.get("address")).get(1); + assertEquals(16, actAddr2.get("number")); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesEmptyComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(0, ((List>) act.get("address")).size()); + } + + @Test + public void testConvertPropertiesOneSimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + odataComment.add("First Test"); + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertEquals(1, ((List) act.get("comment")).size()); + assertEquals("First Test", ((List) act.get("comment")).get(0)); + } + + @Test + public void testConvertPropertiesTwoSimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + odataComment.add("First Test"); + odataComment.add("Second Test"); + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertEquals(2, ((List) act.get("comment")).size()); + assertEquals("First Test", ((List) act.get("comment")).get(0)); + assertEquals("Second Test", ((List) act.get("comment")).get(1)); + } + + @Test + public void testConvertPropertiesEmptySimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertTrue(((List) act.get("comment")).isEmpty()); + } + + private JPAStructuredType createMetadataForSimpleProperty(final String externalName, final String internalName) + throws ODataJPAModelException { + final JPAStructuredType st = mock(JPAStructuredType.class); + final JPAAttribute attribute = mock(JPAAttribute.class); + final JPAPath pathID = mock(JPAPath.class); + final List pathElements = new ArrayList<>(); + pathElements.add(attribute); + when(st.getPath(externalName)).thenReturn(pathID); + when(pathID.getLeaf()).thenReturn(attribute); + when(pathID.getPath()).thenReturn(pathElements); + when(attribute.getInternalName()).thenReturn(internalName); + return st; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java new file mode 100644 index 0000000000..bceaee7331 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java @@ -0,0 +1,210 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmStructuredType; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.deserializer.DeserializerException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriHelper; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; + +public abstract class TestJPAConversionHelper { + + protected JPAConversionHelper cut; + protected EdmEntitySet edmEntitySet; + protected ODataRequest request; + protected OData odata; + protected JPAEntityType et; + + public TestJPAConversionHelper() { + super(); + } + + @Test + public abstract void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + @Test + public abstract void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + @Test + public abstract void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + protected void prepareConvertCompoundKeyToLocation() throws ODataJPAModelException, + SerializerException, ODataJPAProcessorException { + + final List keyPath = new ArrayList(); + + request = mock(ODataRequest.class); + et = mock(JPAEntityType.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + when(et.getKeyPath()).thenReturn(keyPath); + edmEntitySet = mock(EdmEntitySet.class); + + addKeyAttribute(keyPath, "BusinessPartnerID", "businessPartnerID"); + addKeyAttribute(keyPath, "RoleCategory", "roleCategory"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.COMPOUND_KEY); + when(odata.createUriHelper()).thenReturn(uriHelper); + } + + protected void prepareConvertSimpleKeyToLocation() throws ODataJPAModelException { + final List keyPath = new ArrayList(); + + request = mock(ODataRequest.class); + et = mock(JPAEntityType.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + edmEntitySet = mock(EdmEntitySet.class); + when(et.getKeyPath()).thenReturn(keyPath); + + addKeyAttribute(keyPath, "ID", "iD"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.SINGLE); + when(odata.createUriHelper()).thenReturn(uriHelper); + } + + void addKeyAttribute(final List keyPath, final String externalName, final String internalName) { + JPAPath key; + JPAAttribute keyAttribute; + key = mock(JPAPath.class); + keyPath.add(key); + keyAttribute = mock(JPAAttribute.class); + when(keyAttribute.getExternalName()).thenReturn(externalName); + when(keyAttribute.getInternalName()).thenReturn(internalName); + when(key.getLeaf()).thenReturn(keyAttribute); + } + + protected void prepareConvertEmbeddedIdToLocation() throws ODataJPAModelException { + List keyPath = new ArrayList(); + + request = mock(ODataRequest.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + + edmEntitySet = mock(EdmEntitySet.class); + et = mock(JPAEntityType.class); + when(et.getKeyPath()).thenReturn(keyPath); + JPAPath key = mock(JPAPath.class); + keyPath.add(key); + JPAAttribute keyAttribute = mock(JPAAttribute.class); + when(keyAttribute.getExternalName()).thenReturn("Key"); + when(keyAttribute.getInternalName()).thenReturn("key"); + when(keyAttribute.isComplex()).thenReturn(true); + when(keyAttribute.isKey()).thenReturn(true); + when(key.getLeaf()).thenReturn(keyAttribute); + + JPAStructuredType st = mock(JPAStructuredType.class); + when(keyAttribute.getStructuredType()).thenReturn(st); + keyPath = new ArrayList(); + when(st.getPathList()).thenReturn(keyPath); + + addKeyAttribute(keyPath, "CodeID", "codeID"); + addKeyAttribute(keyPath, "CodePublisher", "codePublisher"); + addKeyAttribute(keyPath, "DivisionCode", "divisionCode"); + addKeyAttribute(keyPath, "Language", "language"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.EMBEDDED_ID); + when(odata.createUriHelper()).thenReturn(uriHelper); + + } + + class UriHelperSpy implements UriHelper { + public static final String EMBEDDED_ID = "EmbeddedId"; + public static final String COMPOUND_KEY = "CompoundKey"; + public static final String SINGLE = "SingleID"; + private final String mode; + + public UriHelperSpy(String mode) { + this.mode = mode; + } + + @Override + public String buildCanonicalURL(EdmEntitySet edmEntitySet, Entity entity) throws SerializerException { + if (mode.equals(EMBEDDED_ID)) { + assertEquals(4, entity.getProperties().size()); + int found = 0; + for (final Property property : entity.getProperties()) { + if (property.getName().equals("DivisionCode") && property.getValue().equals("BE1")) + found++; + else if (property.getName().equals("Language") && property.getValue().equals("fr")) + found++; + } + assertEquals("Not all key attributes found", 2, found); + return "AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')"; + } else if (mode.equals(COMPOUND_KEY)) { + assertEquals(2, entity.getProperties().size()); + int found = 0; + for (final Property property : entity.getProperties()) { + if (property.getName().equals("BusinessPartnerID") && property.getValue().equals("35")) + found++; + else if (property.getName().equals("RoleCategory") && property.getValue().equals("A")) + found++; + } + assertEquals("Not all key attributes found", 2, found); + return "BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')"; + } else if (mode.equals(SINGLE)) { + assertEquals(1, entity.getProperties().size()); + assertEquals("35", entity.getProperties().get(0).getValue()); + return "Organisation('35')"; + } + fail(); + return null; + + } + + @Override + public String buildContextURLKeyPredicate(List keys) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildContextURLSelectList(EdmStructuredType type, ExpandOption expand, SelectOption select) + throws SerializerException { + fail(); + return null; + } + + @Override + public String buildKeyPredicate(EdmEntityType edmEntityType, Entity entity) throws SerializerException { + fail(); + return null; + } + + @Override + public UriResourceEntitySet parseEntityId(Edm edm, String entityId, String rawServiceRoot) + throws DeserializerException { + fail(); + return null; + } + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java new file mode 100644 index 0000000000..5f2784eb4e --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java @@ -0,0 +1,71 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.Assert.assertEquals; + +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAConversionHelperEntity extends TestJPAConversionHelper { + + @Before + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Override + @Test + public void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Organization newPOJO = new Organization(); + newPOJO.setID("35"); + + prepareConvertSimpleKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/Organisation('35')", act); + } + + @Override + @Test + public void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + BusinessPartnerRole newPOJO = new BusinessPartnerRole(); + newPOJO.setBusinessPartnerID("35"); + newPOJO.setRoleCategory("A"); + + prepareConvertCompoundKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')", act); + } + + @Override + @Test + public void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + AdministrativeDivisionDescription newPOJO = new AdministrativeDivisionDescription(); + AdministrativeDivisionDescriptionKey primaryKey = new AdministrativeDivisionDescriptionKey(); + primaryKey.setCodeID("NUTS1"); + primaryKey.setCodePublisher("Eurostat"); + primaryKey.setDivisionCode("BE1"); + primaryKey.setLanguage("fr"); + newPOJO.setKey(primaryKey); + + prepareConvertEmbeddedIdToLocation(); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals( + "localhost.test/AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')", + act); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java new file mode 100644 index 0000000000..a1348a1cac --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java @@ -0,0 +1,76 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.Before; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAConversionHelperMap extends TestJPAConversionHelper { + @Before + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Override + public void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap(); + newPOJO.put("businessPartnerID", "35"); + newPOJO.put("roleCategory", "A"); + + prepareConvertCompoundKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')", act); + } + + @Override + public void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap(); + Map primaryKey = new HashMap(); + + primaryKey.put("codeID", "NUTS1"); + primaryKey.put("codePublisher", "Eurostat"); + primaryKey.put("divisionCode", "BE1"); + primaryKey.put("language", "fr"); + newPOJO.put("key", primaryKey); + + prepareConvertEmbeddedIdToLocation(); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals( + "localhost.test/AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')", + act); + } + + @Override + public void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap(); + newPOJO.put("iD", "35"); + + prepareConvertSimpleKeyToLocation(); + when(et.getTypeClass()).then(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Organization.class; + } + }); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/Organisation('35')", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java new file mode 100644 index 0000000000..073f46ed42 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java @@ -0,0 +1,280 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.Tuple; +import javax.persistence.TupleElement; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPACollectionResult; +import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public abstract class TestJPACreateResult extends TestBase { + + protected JPAExpandResult cut; + protected JPAEntityType et; + protected Map> headers; + protected Object jpaEntity; + protected JPATupleChildConverter converter; + + public TestJPACreateResult() { + super(); + } + + @Test + public void testGetChildrenProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + + createCutProvidesEmptyMap(); + + Map act = cut.getChildren(); + + assertNotNull(act); + assertEquals(1, act.size()); + } + + @Test + public void testGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("BusinessPartnerRoles"); + + createCutGetResultSimpleEntity(); + + List act = cut.getResult("root"); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("34", act.get(0).get("BusinessPartnerID")); + } + + @Test + public void testGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisionDescriptions"); + + createCutGetResultWithOneLevelEmbedded(); + + List act = cut.getResult("root"); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("A", act.get(0).get("CodeID")); + assertEquals("Hugo", act.get(0).get("Name")); + } + + @Test + public void testGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + + createCutGetResultWithTwoLevelEmbedded(); + + List act = cut.getResult("root"); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("01", act.get(0).get("ID")); + assertEquals("99", act.get(0).get("AdministrativeInformation/Created/By")); + } + + @Test + public void testGetResultWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithOneLinked(); + Map act = cut.getChildren(); + assertNotNull(act); + assertEquals(1, act.size()); + for (JPAAssociationPath actPath : act.keySet()) { + assertEquals("Children", actPath.getAlias()); + List subResult = act.get(actPath).getResult("Eurostat/NUTS1/BE2"); + assertEquals(1, subResult.size()); + } + } + + @Test + public void testGetResultWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithTwoLinked(); + Map act = cut.getChildren(); + assertNotNull(act); + assertEquals(1, act.size()); + for (JPAAssociationPath actPath : act.keySet()) { + assertEquals("Children", actPath.getAlias()); + List subResult = act.get(actPath).getResult("Eurostat/NUTS1/BE2"); + assertEquals(2, subResult.size()); + } + } + + @Test + public void testGetResultWithPrimitiveCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithSimpleCollection(); + + final Map act = cut.getChildren(); + assertDoesNotContain(cut.getResult("root"), "Comment"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Comment", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((String) o).isEmpty()); + } + } + } + + @Test + public void testGetResultWithComplexCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithComplexCollection(); + + Map act = cut.getChildren(); + assertDoesNotContain(cut.getResult("root"), "InhouseAddress"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("InhouseAddress", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + + @Test + public void testGetResultWithComplexContainingCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithComplexWithCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "Complex/Address"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("Complex/Address")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Complex/Address", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + @Test + public void testGetResultWithContainingNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + createCutGetResultEntityWithNestedComplexCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "Nested"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("Nested")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Nested", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + @Test + public void testGetResultWithDeepComplexContainingCollection() throws ODataJPAModelException, + ODataApplicationException { + createCutGetResultEntityWithDeepComplexWithCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "FirstLevel/SecondLevel/Address"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("FirstLevel/SecondLevel/Address")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("FirstLevel/SecondLevel/Address", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + private void assertDoesNotContain(final List result, final String prefix) { + for (Tuple t : result) { + for (TupleElement e : t.getElements()) + assertFalse(e.getAlias() + " violates prefix check: " + prefix, e.getAlias().startsWith(prefix)); + } + + } + + protected abstract void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException; + + protected abstract void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException; + + protected abstract void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException; +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java new file mode 100644 index 0000000000..6e9ece7f02 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java @@ -0,0 +1,230 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.CollcetionInnerComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollcetionNestedComplex; +import com.sap.olingo.jpa.processor.core.testmodel.Collection; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionDeep; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionFirstLevelComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionPartOfComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionSecondLevelComplex; +import com.sap.olingo.jpa.processor.core.testmodel.InhouseAddress; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAEntityResult extends TestJPACreateResult { + @Before + public void setUp() throws Exception { + headers = new HashMap<>(); + jpaEntity = new Organization(); + helper = new TestHelper(emf, PUNIT_NAME); + et = helper.getJPAEntityType("Organizations"); + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + } + + @Override + protected void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + jpaEntity = new BusinessPartnerRole(); + ((BusinessPartnerRole) jpaEntity).setBusinessPartnerID("34"); + ((BusinessPartnerRole) jpaEntity).setRoleCategory("A"); + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + AdministrativeDivisionDescriptionKey key = new AdministrativeDivisionDescriptionKey(); + key.setCodeID("A"); + key.setLanguage("en"); + jpaEntity = new AdministrativeDivisionDescription(); + ((AdministrativeDivisionDescription) jpaEntity).setName("Hugo"); + ((AdministrativeDivisionDescription) jpaEntity).setKey(key); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException { + + jpaEntity = new Organization(); + ((Organization) jpaEntity).onCreate(); + ((Organization) jpaEntity).setID("01"); + ((Organization) jpaEntity).setCustomString1("Dummy"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisions"); + jpaEntity = new AdministrativeDivision(); + AdministrativeDivision child = new AdministrativeDivision(); + List children = new ArrayList<>(); + children.add(child); + ((AdministrativeDivision) jpaEntity).setChildren(children); + + child.setCodeID("NUTS2"); + child.setDivisionCode("BE21"); + child.setCodePublisher("Eurostat"); + + ((AdministrativeDivision) jpaEntity).setCodeID("NUTS1"); + ((AdministrativeDivision) jpaEntity).setDivisionCode("BE2"); + ((AdministrativeDivision) jpaEntity).setCodePublisher("Eurostat"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithOneLinked(); + + AdministrativeDivision child = new AdministrativeDivision(); + List children = ((AdministrativeDivision) jpaEntity).getChildren(); + children.add(child); + + child.setCodeID("NUTS2"); + child.setDivisionCode("BE22"); + child.setCodePublisher("Eurostat"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } + + @Override + protected void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException { + + final Organization org = new Organization(); + final List comment = org.getComment(); + comment.add("First"); + comment.add("Second"); + org.setID("1"); + jpaEntity = org; + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Persons"); + + final Person person = new Person(); + final List addresses = person.getInhouseAddress(); + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = person; + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Collections"); + + final Collection collection = new Collection(); + final CollectionPartOfComplex complex = new CollectionPartOfComplex(); + final List addresses = complex.getAddress(); + complex.setNumber(2L); + collection.setComplex(complex); + + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("Collections"); + + final Collection collection = new Collection(); + final List nested = collection.getNested(); + + CollcetionNestedComplex nestedItem = new CollcetionNestedComplex(); + CollcetionInnerComplex inner = new CollcetionInnerComplex(); + inner.setFigure1(1L); + inner.setFigure3(3L); + nestedItem.setInner(inner); + nestedItem.setNumber(100L); + nested.add(nestedItem); + + nestedItem = new CollcetionNestedComplex(); + inner = new CollcetionInnerComplex(); + inner.setFigure1(11L); + inner.setFigure3(13L); + nestedItem.setInner(inner); + nestedItem.setNumber(200L); + nested.add(nestedItem); + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } + + @Override + protected void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("CollectionDeeps"); + + final CollectionDeep collection = new CollectionDeep(); + final CollectionFirstLevelComplex firstLevel = new CollectionFirstLevelComplex(); + final CollectionSecondLevelComplex secondLevel = new CollectionSecondLevelComplex(); + + final List addresses = secondLevel.getAddress(); + collection.setID("27"); + collection.setFirstLevel(firstLevel); + firstLevel.setLevelID(3); + firstLevel.setSecondLevel(secondLevel); + + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java new file mode 100644 index 0000000000..8cb3837b0e --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java @@ -0,0 +1,246 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAMapResult extends TestJPACreateResult { + List children; + + @Before + public void setUp() throws Exception { + headers = new HashMap<>(); + jpaEntity = new HashMap(); + helper = new TestHelper(emf, PUNIT_NAME); + et = helper.getJPAEntityType("Organizations"); + children = new ArrayList<>(); + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + // Make Map equal to empty Organization instance + ((Map) jpaEntity).put("type", "2"); + ((Map) jpaEntity).put("comment", new ArrayList(1)); + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + + ((Map) jpaEntity).put("businessPartnerID", "34"); + ((Map) jpaEntity).put("roleCategory", "A"); + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + + Map key = new HashMap<>(); + key.put("codeID", "A"); + key.put("language", "en"); + + ((Map) jpaEntity).put("name", "Hugo"); + ((Map) jpaEntity).put("key", key); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException { + + long time = new Date().getTime(); + Map created = new HashMap<>(); + created.put("by", "99"); + created.put("at", new Timestamp(time)); + + Map admin = new HashMap<>(); + admin.put("created", created); + admin.put("updated", created); + + ((Map) jpaEntity).put("iD", "01"); + ((Map) jpaEntity).put("customString1", "Dummy"); + ((Map) jpaEntity).put("administrativeInformation", admin); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + prepareAdminWithChildren(); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + prepareAdminWithChildren(); + + Map childProperties = new HashMap<>(); + JPARequestEntity child = mock(JPARequestEntity.class); + when(child.getEntityType()).thenReturn(et); + when(child.getData()).thenReturn(childProperties); + childProperties.put("codeID", "NUTS2"); + childProperties.put("divisionCode", "BE22"); + childProperties.put("codePublisher", "Eurostat"); + children.add(child); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + private void prepareAdminWithChildren() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisions"); + + ((Map) jpaEntity).put("codeID", "NUTS1"); + ((Map) jpaEntity).put("divisionCode", "BE2"); + ((Map) jpaEntity).put("codePublisher", "Eurostat"); + + Map childProperties = new HashMap<>(); + + JPARequestEntity child = mock(JPARequestEntity.class); + when(child.getEntityType()).thenReturn(et); + when(child.getData()).thenReturn(childProperties); + childProperties.put("codeID", "NUTS2"); + childProperties.put("divisionCode", "BE21"); + childProperties.put("codePublisher", "Eurostat"); + children.add(child); + ((Map) jpaEntity).put("children", children); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException { + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("comment", Arrays.asList("First", "Second")); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Persons"); + + ((Map) jpaEntity).put("iD", "1"); + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + ((Map) jpaEntity).put("inhouseAddress", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("Collections"); + final Map complex = new HashMap<>(); + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("complex", complex); + complex.put("number", 2L); + + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + complex.put("address", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Collections"); + + ((Map) jpaEntity).put("iD", "1"); + + final Map nested1 = new HashMap<>(); + final Map nested2 = new HashMap<>(); + final Map inner1 = new HashMap<>(); + final Map inner2 = new HashMap<>(); + + nested1.put("inner", inner1); + nested2.put("inner", inner2); + nested1.put("number", 100L); + nested1.put("number", 200L); + + inner1.put("figure1", 1L); + inner1.put("figure3", 3L); + inner2.put("figure1", 11L); + inner2.put("figure3", 13L); + ((Map) jpaEntity).put("nested", Arrays.asList(nested1, nested2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("CollectionDeeps"); + final Map firstLevel = new HashMap<>(); + final Map secondLevel = new HashMap<>(); + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("firstLevel", firstLevel); + firstLevel.put("levelID", 2); + firstLevel.put("secondLevel", secondLevel); + secondLevel.put("number", 2L); + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + secondLevel.put("address", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java new file mode 100644 index 0000000000..a7022e48d8 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java @@ -0,0 +1,158 @@ +package com.sap.olingo.jpa.processor.core.processor; + +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 java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestCreateDeltaBasedResult extends TestJPAModifyProcessor { + private JPACUDRequestProcessor cut; + private List pathElements; + private Person beforeImagePerson; + private Person currentImagePerson; + private JPAAssociationPath path; + + @Before + public void setup() throws ODataException { + cut = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, new JPAConversionHelper()); + pathElements = new ArrayList<>(3); + path = mock(JPAAssociationPath.class); + + beforeImagePerson = new Person(); + beforeImagePerson.setID("1"); + currentImagePerson = new Person(); + currentImagePerson.setID("1"); + when(em.contains(beforeImagePerson)).thenReturn(Boolean.FALSE); + } + + @Test + public void testShallReturnNullIfBeforeImageNotPresent() throws ODataJPAProcessorException { + + final JPAAssociationPath path = mock(JPAAssociationPath.class); + final JPAElement pathItem = mock(JPAElement.class); + pathElements.add(pathItem); + when(pathItem.getInternalName()).thenReturn("roles"); + final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.empty()); + assertNull(act); + } + + @Test(expected = ODataJPAProcessorException.class) + public void testThrowsExceptionIfBeforeIfManaged() throws ODataJPAProcessorException { + when(em.contains(beforeImagePerson)).thenReturn(Boolean.TRUE); + cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(beforeImagePerson)); + } + + @Test + public void testShallReturnNullIfTargetEmpty() throws ODataJPAProcessorException { + + prepareRole(); + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertNull(act); + } + + @Test + public void testShallReturnNullIfNoDeltaFound() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole beforeRole = new BusinessPartnerRole(); + beforeRole.setBusinessPartner(beforeImagePerson); + beforeRole.setRoleCategory("A"); + beforeImagePerson.getRoles().add(beforeRole); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertNull(act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeEmpty() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole exp = new BusinessPartnerRole(); + exp.setBusinessPartner(currentImagePerson); + exp.setRoleCategory("A"); + currentImagePerson.getRoles().add(exp); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeOneNowTwo() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A"); + currentImagePerson.getRoles().add(exp); + + currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B")); + beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B")); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeOneNowTwoInversOrder() throws ODataJPAProcessorException { + + prepareRole(); + currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B")); + beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B")); + final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A"); + currentImagePerson.getRoles().add(exp); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnNewValueIfNotACollection() throws ODataJPAProcessorException { + final CommunicationData exp = prepareBeforeImageCommunicationData(); + beforeImagePerson.setCommunicationData(exp); + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + private void prepareRole() { + + final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class); + pathElements.add(pathItem); + when(path.getPath()).thenReturn(pathElements); + when(pathItem.getInternalName()).thenReturn("roles"); + when(path.getLeaf()).thenReturn(pathItem); + when(pathItem.isCollection()).thenReturn(Boolean.TRUE); + } + + private CommunicationData prepareBeforeImageCommunicationData() { + final CommunicationData afterCommData = new CommunicationData(); + currentImagePerson.setCommunicationData(afterCommData); + final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class); + pathElements.add(pathItem); + when(path.getPath()).thenReturn(pathElements); + when(pathItem.getInternalName()).thenReturn("communicationData"); + when(path.getLeaf()).thenReturn(pathItem); + when(pathItem.isCollection()).thenReturn(Boolean.FALSE); + return afterCommData; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java new file mode 100644 index 0000000000..792095bbb2 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java @@ -0,0 +1,512 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.data.Link; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.serializer.JPASerializer; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestCreateRequestEntity { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static JPAEdmProvider jpaEdm; + protected static DataSource ds; + + @BeforeClass + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + private OData odata; + private JPACUDRequestProcessor cut; + private Entity oDataEntity; + private ServiceMetadata serviceMetadata; + private JPAODataSessionContextAccess sessionContext; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private UriResourceEntitySet uriEts; + private EntityManager em; + private EntityTransaction transaction; + private JPASerializer serializer; + private EdmEntitySet ets; + private List keyPredicates; + private JPAConversionHelper convHelper; + private List pathParts = new ArrayList<>(); + private Map> headers; + + @Before + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + serializer = mock(JPASerializer.class); + uriEts = mock(UriResourceEntitySet.class); + pathParts.add(uriEts); + convHelper = new JPAConversionHelper();// mock(JPAConversionHelper.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + headers = new HashMap<>(0); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(uriEts.getKind()).thenReturn(UriResourceKind.entitySet); + when(ets.getName()).thenReturn("AdministrativeDivisions"); + when(em.getTransaction()).thenReturn(transaction); + cut = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + + } + + @Test + public void testCreateDataAndEtCreated() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getData()); + assertNotNull(act.getEntityType()); + } + + @Test + public void testCreateEtName() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertEquals("AdministrativeDivision", act.getEntityType().getExternalName()); + } + + @Test + public void testCreateDataHasProperty() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + String actValue = (String) act.getData().get("codeID"); + assertNotNull(actValue); + assertEquals("DE50", actValue); + } + + @Test + public void testCreateEmptyRelatedEntities() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getRelatedEntities()); + assertTrue(act.getRelatedEntities().isEmpty()); + } + + @Test + public void testCreateEmptyRelationLinks() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getRelationLinks()); + assertTrue(act.getRelationLinks().isEmpty()); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLink() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull("Is null", actValue); + assertTrue("Wrong type", actValue instanceof List); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkSize() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertEquals("Wrong size", 1, ((List) actValue).size()); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkEntityType() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull(((List) actValue).get(0)); + assertNotNull("Entity type not found", ((JPARequestEntity) ((List) actValue).get(0)).getEntityType()); + assertEquals("Wrong Type", "AdministrativeDivision", ((JPARequestEntity) ((List) actValue).get(0)) + .getEntityType().getExternalName()); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkData() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull(((List) actValue).get(0)); + assertNotNull("Entity type not found", ((JPARequestEntity) ((List) actValue).get(0)).getEntityType()); + Map actData = ((JPARequestEntity) ((List) actValue).get(0)).getData(); + assertNotNull("Data not found", actData); + assertNotNull("CodeID not found", actData.get("codeID")); + assertEquals("Value not found", "DE501", actData.get("codeID")); + } + + @Test + public void testCreateDeepTwoChildResultContainsEntityLinkSize() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addNavigationLinkDE502(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertEquals("Wrong size", 2, ((List) actValue).size()); + } + + @Test + public void testCreateWithLinkToOne() throws ODataJPAProcessorException { + List properties = createProperties(); + createODataEntity(properties); + List bindingLinks = new ArrayList<>(); + addParentBindingLink(bindingLinks); + when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findLinkList(act.getRelationLinks(), ("parent")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + } + + @Test + public void testCreateWithLinkToMany() throws ODataJPAProcessorException { + List properties = createProperties(); + createODataEntity(properties); + List bindingLinks = new ArrayList<>(); + addChildrenBindingLink(bindingLinks); + when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findLinkList(act.getRelationLinks(), ("children")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + assertEquals(2, ((List) actValue).size()); + } + + @Test + public void testCreateDeepToOne() throws ODataJPAProcessorException { + final List properties = createProperties(); + createODataEntity(properties); + + final List navigationLinks = new ArrayList<>(); + final Link navigationLink = addParentNavigationLink(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + when(oDataEntity.getNavigationLink("Parent")).thenReturn(navigationLink); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("parent")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + } + + @Test + public void testCreateOrgWithRoles() throws ODataJPAProcessorException { + + final List properties = new ArrayList<>(); + createPropertyBuPaID(properties, "20"); + createODataEntity(properties); +//----------------------------- + final List navigationLinks = new ArrayList<>(); + + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Roles"); + navigationLinks.add(navigationLink); + final EntityCollection navigationEntitySet = mock(EntityCollection.class); + final List entityCollection = new ArrayList<>(); + + final Entity navigationEntity1 = mock(Entity.class); + final List navigationEntityProperties1 = createPropertiesRoles("20", "A"); + when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);// + entityCollection.add(navigationEntity1); + + final Entity navigationEntity2 = mock(Entity.class); + final List navigationEntityProperties2 = createPropertiesRoles("20", "C"); + when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);// + entityCollection.add(navigationEntity2); + + when(navigationEntitySet.getEntities()).thenReturn(entityCollection); + when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet); + + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + when(oDataEntity.getNavigationLink("Roles")).thenReturn(navigationLink); +//------------------------------------ + when(ets.getName()).thenReturn("Organizations"); + final JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act); + assertNotNull(act.getData()); + assertNotNull(findEntitryList(act.getRelatedEntities(), ("roles"))); + } + + @Test + public void testCreateDeepOneChildViaComplex() throws ODataJPAModelException, ODataException { + final List properties = new ArrayList<>(); + final List inlineProperties = new ArrayList<>(); + final Entity inlineEntity = mock(Entity.class); + + createODataEntity(properties); + + when(ets.getName()).thenReturn("Persons"); + createPropertyBuPaID(properties, "20"); + when(inlineEntity.getProperties()).thenReturn(inlineProperties); + createPropertyBuPaID(inlineProperties, "200"); + + final List adminProperties = createComplexProperty(properties, "AdministrativeInformation", null, null, + oDataEntity); + final List createdProperties = createComplexProperty(adminProperties, "Created", "User", inlineEntity, + oDataEntity); + createPrimitiveProperty(createdProperties, "99", "By"); + createPrimitiveProperty(createdProperties, Timestamp.valueOf("2016-01-20 09:21:23.0"), "At"); + + final JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + final Object actValue = findEntitryList(act.getRelatedEntities(), ("administrativeInformation")); + + assertNotNull(actValue); + assertNotNull(((List) actValue).get(0)); + @SuppressWarnings("unchecked") + JPARequestEntity actDeepEntity = ((List) actValue).get(0); + assertEquals("200", actDeepEntity.getData().get("iD")); + } + + private List createComplexProperty(final List properties, final String name, final String target, + final Entity inlineEntity, final Entity oDataEntity) { + + final Property property = mock(Property.class); + final ComplexValue cv = mock(ComplexValue.class); + final List cProperties = new ArrayList<>(); + final Link navigationLink = mock(Link.class); + + when(property.getName()).thenReturn(name); + when(property.getValue()).thenReturn(cv); + when(property.getValueType()).thenReturn(ValueType.COMPLEX); + when(property.isComplex()).thenReturn(true); + when(property.asComplex()).thenReturn(cv); + + when(cv.getValue()).thenReturn(cProperties); + when(cv.getNavigationLink(target)).thenReturn(navigationLink); + when(navigationLink.getInlineEntity()).thenReturn(inlineEntity); + + when(oDataEntity.getProperty(name)).thenReturn(property); + + properties.add(property); + return cProperties; + } + + private Link addParentNavigationLink(List navigationLinks) { + + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Parent"); + navigationLinks.add(navigationLink); + final Entity navigationEntity = mock(Entity.class); + when(navigationLink.getInlineEntity()).thenReturn(navigationEntity); + final List navigationEntityProperties = createPropertyCodeID("DE5"); + when(navigationEntity.getProperties()).thenReturn(navigationEntityProperties);// + return navigationLink; + } + + private void addParentBindingLink(List bindingLinks) { + Link bindingLink = mock(Link.class); + when(bindingLink.getTitle()).thenReturn("Parent"); + bindingLinks.add(bindingLink); + when(bindingLink.getBindingLink()).thenReturn( + "AdministrativeDivisions(DivisionCode='DE1',CodeID='NUTS1',CodePublisher='Eurostat')"); + } + + private void addChildrenNavigationLinkDE501(List navigationLinks) { + addChildrenNavigationLink(navigationLinks, "DE501", null); + } + + private void addNavigationLinkDE502(List navigationLinks) { + + addChildrenNavigationLink(navigationLinks, "DE501", "DE502"); + } + + private void addChildrenNavigationLink(List navigationLinks, String codeValue1, String codeValue2) { + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Children"); + navigationLinks.add(navigationLink); + final EntityCollection navigationEntitySet = mock(EntityCollection.class); + final List entityCollection = new ArrayList<>(); + + final Entity navigationEntity1 = mock(Entity.class); + final List navigationEntityProperties1 = createPropertyCodeID(codeValue1); + when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);// + entityCollection.add(navigationEntity1); + if (codeValue2 != null) { + Entity navigationEntity2 = mock(Entity.class); + List navigationEntityProperties2 = createPropertyCodeID(codeValue2); + when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);// + entityCollection.add(navigationEntity2); + } + when(navigationEntitySet.getEntities()).thenReturn(entityCollection); + when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet); + when(oDataEntity.getNavigationLink("Children")).thenReturn(navigationLink); + + } + + private void addChildrenBindingLink(List bindingLinks) { + List links = new ArrayList<>(); + + Link bindingLink = mock(Link.class); + when(bindingLink.getTitle()).thenReturn("Children"); + bindingLinks.add(bindingLink); + when(bindingLink.getBindingLinks()).thenReturn(links); + links.add("AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"); + links.add("AdministrativeDivisions(DivisionCode='DE101',CodeID='NUTS3',CodePublisher='Eurostat')"); + } + + private void createODataEntity(final List properties) { + oDataEntity = mock(Entity.class); + when(oDataEntity.getProperties()).thenReturn(properties); + } + + private List createProperties() { + return createPropertyCodeID("DE50"); + } + + private List createPropertyCodeID(final String codeID) { + List properties = new ArrayList<>(); + createPrimitiveProperty(properties, codeID, "CodeID"); + return properties; + } + + private void createPropertyBuPaID(final List properties, final String value) { + + createPrimitiveProperty(properties, value, "ID"); + } + + private void createPrimitiveProperty(final List properties, final Object value, final String name) { + + final Property property = mock(Property.class); + when(property.getName()).thenReturn(name); + when(property.getValue()).thenReturn(value); + when(property.getValueType()).thenReturn(ValueType.PRIMITIVE); + properties.add(property); + } + + private List createPropertiesRoles(String BuPaId, String RoleCategory) { + List properties = new ArrayList<>(); + createPrimitiveProperty(properties, BuPaId, "BusinessPartnerID"); + createPrimitiveProperty(properties, RoleCategory, "RoleCategory"); + return properties; + } + + private Object findEntitryList(Map> relatedEntities, + String assoziationName) { + for (Entry> entity : relatedEntities.entrySet()) { + if (entity.getKey().getPath().get(0).getInternalName().equals(assoziationName)) + return entity.getValue(); + } + return null; + } + + private Object findLinkList(Map> relationLink, String assoziationName) { + for (Entry> entity : relationLink.entrySet()) { + if (entity.getKey().getPath().get(0).getInternalName().equals(assoziationName)) + return entity.getValue(); + } + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java new file mode 100644 index 0000000000..7d38548a33 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java @@ -0,0 +1,455 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.data.Parameter; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmAction; +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlProperty; +import org.apache.olingo.commons.api.edm.provider.CsdlReturnType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.deserializer.DeserializerResult; +import org.apache.olingo.server.api.deserializer.ODataDeserializer; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceAction; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData; +import com.sap.olingo.jpa.processor.core.testobjects.FileAccess; +import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActionNoParameter; +import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActions; + +public class TestJPAActionProcessor { + + private JPAActionRequestProcessor cut; + private ContentType requestFormat; + @Mock + private ODataRequest request; + @Mock + private ODataResponse response; + @Mock + private OData odata; + @Mock + private ODataDeserializer deserializer; + @Mock + private JPAOperationSerializer serializer; + @Mock + private JPAODataSessionContextAccess sessionContext; + @Mock + private JPAODataRequestContextAccess requestContext; + @Mock + private JPAServiceDocument sd; + @Mock + private UriInfo uriInfo; + private List uriResources; + @Mock + private UriResourceAction resource; + @Mock + private EdmAction edmAction; + @Mock + private JPAAction action; + private Map actionParameter; + @Mock + private CsdlReturnType returnType; + @Mock + private UriResourceEntitySet bindingEntity; + + @Before + public void setup() throws ODataException { + MockitoAnnotations.initMocks(this); + + uriResources = new ArrayList<>(); + uriResources.add(resource); + actionParameter = new HashMap<>(); + + EntityManager em = mock(EntityManager.class); + CriteriaBuilder cb = mock(CriteriaBuilder.class); + JPAEdmProvider edmProvider = mock(JPAEdmProvider.class); + DeserializerResult dResult = mock(DeserializerResult.class); + SerializerResult serializerResult = mock(SerializerResult.class); + + when(requestContext.getEntityManager()).thenReturn(em); + when(em.getCriteriaBuilder()).thenReturn(cb); + when(sessionContext.getEdmProvider()).thenReturn(edmProvider); + when(edmProvider.getServiceDocument()).thenReturn(sd); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + when(serializer.getContentType()).thenReturn(ContentType.APPLICATION_JSON); + + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(resource.getAction()).thenReturn(edmAction); + when(edmAction.isBound()).thenReturn(Boolean.FALSE); + when(sd.getAction(edmAction)).thenReturn(action); + when(odata.createDeserializer((ContentType) any())).thenReturn(deserializer); + + when(deserializer.actionParameters(request.getBody(), resource.getAction())).thenReturn(dResult); + when(dResult.getActionParameters()).thenReturn(actionParameter); + + requestFormat = ContentType.APPLICATION_JSON; + + cut = new JPAActionRequestProcessor(odata, sessionContext, requestContext); + } + + @Test + public void testCallsConstructorWithoutParemeter() throws InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, + SecurityException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + setConstructorAndMethod("unboundReturnPrimitivetNoParameter"); + + cut.performAction(request, response, requestFormat); + + assertEquals(1, TestJavaActionNoParameter.constructorCalls); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsConstructorWithParemeter() throws ODataJPAProcessException, InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, + SecurityException, ODataApplicationException { + TestJavaActions.constructorCalls = 0; + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundWithOutParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + cut.performAction(request, response, requestFormat); + + assertEquals(1, TestJavaActions.constructorCalls); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionVoidNoParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundWithOutParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionPrimitiveNoParameterReturnValue() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, SerializerException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundReturnFacetNoParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class); + when(action.getResultParameter()).thenReturn(rParam); + + EdmReturnType rt = mock(EdmReturnType.class); + EdmType type = mock(EdmType.class); + when(edmAction.getReturnType()).thenReturn(rt); + when(rt.getType()).thenReturn(type); + when(type.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(200); + verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type)); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionEntityNoParameterReturnValue() throws NoSuchMethodException, + SecurityException, SerializerException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("returnEmbeddable"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class); + when(action.getResultParameter()).thenReturn(rParam); + + EdmReturnType rt = mock(EdmReturnType.class); + EdmComplexType type = mock(EdmComplexType.class); + when(edmAction.getReturnType()).thenReturn(rt); + when(rt.getType()).thenReturn(type); + when(type.getKind()).thenReturn(EdmTypeKind.COMPLEX); + + JPAStructuredType st = mock(JPAStructuredType.class); + when(sd.getComplexType((EdmComplexType) any())).thenReturn(st); + when(st.getTypeClass()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return CommunicationData.class; + } + }); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(200); + verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type)); + } + + @Test + public void testCallsActionVoidOneParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataJPAModelException, NumberFormatException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneParameter", Short.class); + + addParameter(m, new Short("10"), "A", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(new Short((short) 10), TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOneEnumerationParameterReturnNoContent() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneEnumerationParameter", FileAccess.class); + + addParameter(m, FileAccess.Create, "AccessRights", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(FileAccess.Create, TestJavaActionNoParameter.enumeration); + } + + @Test + public void testCallsActionVoidTwoParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataJPAModelException, NumberFormatException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidTwoParameter", Short.class, Integer.class); + + addParameter(m, new Short("10"), "A", 0); + addParameter(m, new Integer("200000"), "B", 1); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(new Short((short) 10), TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOneParameterNullableGivenNullReturnNoContent() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneParameter", Short.class); + + addParameter(m, null, "A", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNull(TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOnlyBindingParameter() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundOnlyBinding", AdministrativeDivision.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + } + + @Test + public void testCallsActionVoidBindingParameterPlusTwoBothNull() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class, Integer.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[1])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("A"); + + jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[2])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("B"); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + assertNull(TestJavaActionNoParameter.param1); + assertNull(TestJavaActionNoParameter.param2); + } + + @Test + public void testCallsActionVoidBindingParameterPlusTwoFirstNull() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class, Integer.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[1])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("A"); + + addParameter(m, 20, "B", 2); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + assertNull(TestJavaActionNoParameter.param1); + assertEquals(new Integer(20), TestJavaActionNoParameter.param2); + } + + private void setBindingParameter(Method m) throws ODataJPAModelException, EdmPrimitiveTypeException { + final JPAParameter bindingParam = addParameter(m, null, "Root", 0); + when(bindingParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return AdministrativeDivision.class; + } + }); + final List keys = new ArrayList<>(); + final UriParameter key1 = mock(UriParameter.class); + when(bindingEntity.getKeyPredicates()).thenReturn(keys); + when(key1.getName()).thenReturn("CodeID"); + when(key1.getText()).thenReturn("LAU2"); + keys.add(key1); + + final JPAEntityType et = mock(JPAEntityType.class); + final JPAPath codePath = mock(JPAPath.class); + final JPAAttribute code = mock(JPAAttribute.class); + final EdmPrimitiveType edmString = mock(EdmPrimitiveType.class); + final CsdlProperty edmProperty = mock(CsdlProperty.class); + when(sd.getEntity((EdmType) any())).thenReturn(et); + when(et.getPath("CodeID")).thenReturn(codePath); + when(codePath.getLeaf()).thenReturn(code); + when(code.getInternalName()).thenReturn("codeID"); + when(code.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + when(code.getProperty()).thenReturn(edmProperty); + when(odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String)).thenReturn(edmString); + when(edmString.fromUriLiteral("LAU2")).thenReturn("LAU2"); + when(edmString.valueOfString("LAU2", false, 0, 0, 0, true, code.getType())).thenAnswer( + new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + return "LAU2"; + } + }); + } + + private JPAParameter addParameter(final Method m, final Object value, final String name, int index) + throws ODataJPAModelException { + + Parameter param = mock(Parameter.class); + when(param.getValue()).thenReturn(value); + when(param.getName()).thenReturn(name); + when(param.getValueType()).thenReturn(ValueType.PRIMITIVE); + actionParameter.put(name, param); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[index])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn(name); + return jpaParam; + } + + @SuppressWarnings("unchecked") + private Method setConstructorAndMethod(String methodName, Class... parameterTypes) throws NoSuchMethodException { + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActionNoParameter.class.getConstructors()[0]; + Method m = TestJavaActionNoParameter.class.getMethod(methodName, parameterTypes); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + return m; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java new file mode 100644 index 0000000000..4d71e9658f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java @@ -0,0 +1,512 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.http.HttpMethod; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult; + +public class TestJPAClearProcessor extends TestJPAModifyProcessor { + private ODataRequest request; + + @Before + public void setup() throws ODataException { + request = mock(ODataRequest.class); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + } + + @Test + public void testSuccessReturnCode() throws ODataApplicationException { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + prepareDeleteName2(); + processor.clearFields(request, response); + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testHockIsCalled() throws ODataApplicationException { + // .../Organizations('35')/Name2 + + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertTrue(spy.called); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.clearFields(request, new ODataResponse()); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testSimplePropertyEntityTypeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertEquals("Organization", spy.et.getExternalName()); + } + + @Test + public void testSimplePropertyKeyProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + List keys = new ArrayList<>(); + UriParameter uriParam = mock(UriParameter.class); + when(uriParam.getText()).thenReturn("'35'"); + when(uriParam.getName()).thenReturn("ID"); + keys.add(uriParam); + + when(uriEts.getKeyPredicates()).thenReturn(keys); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.keyPredicates.size()); + assertEquals("35", spy.keyPredicates.get("iD")); + } + + @Test + public void testSimplePropertyAttributeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("name2", keys[0].toString()); + } + + @Test + public void testComplexPropertyHoleProvided() throws ODataApplicationException { + // .../Organizations('35')/Address + RequestHandleSpy spy = prepareDeleteAddress(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("address", keys[0].toString()); + } + + @Test + public void testSimplePropertyValueAttributeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2/$value + RequestHandleSpy spy = prepareDeleteName2(); + + UriResourceValue uriProperty; + uriProperty = mock(UriResourceValue.class); + pathParts.add(uriProperty); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("name2", keys[0].toString()); + } + + @Test + public void testComplexPropertyOnePropertyProvided() throws ODataApplicationException { + // .../Organizations('35')/Address/Country + RequestHandleSpy spy = prepareDeleteAddressCountry(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + @SuppressWarnings("unchecked") + Map address = (Map) spy.jpaAttributes.get("address"); + assertEquals(1, address.size()); + Object[] keys = address.keySet().toArray(); + assertEquals("country", keys[0].toString()); + } + + @SuppressWarnings("unchecked") + @Test + public void testTwoComplexPropertiesOnePropertyProvided() throws ODataApplicationException { + // .../Organizations('4')/AdministrativeInformation/Updated/By + RequestHandleSpy spy = prepareDeleteAdminInfo(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + Map adminInfo = (Map) spy.jpaAttributes.get("administrativeInformation"); + assertEquals(1, adminInfo.size()); + Map update = (Map) adminInfo.get("updated"); + assertEquals(1, update.size()); + Object[] keys = update.keySet().toArray(); + assertEquals("by", keys[0].toString()); + } + + @SuppressWarnings("unchecked") + @Test + public void testTwoComplexPropertiesOnePropertyValueProvided() throws ODataApplicationException { + // .../Organizations('4')/AdministrativeInformation/Updated/By/$value + RequestHandleSpy spy = prepareDeleteAdminInfo(); + + UriResourceValue uriProperty; + uriProperty = mock(UriResourceValue.class); + pathParts.add(uriProperty); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + Map adminInfo = (Map) spy.jpaAttributes.get("administrativeInformation"); + assertEquals(1, adminInfo.size()); + Map update = (Map) adminInfo.get("updated"); + assertEquals(1, update.size()); + Object[] keys = update.keySet().toArray(); + assertEquals("by", keys[0].toString()); + } + + @Test + public void testBeginIsCalledOnNoTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(1)).begin(); + } + + @Test + public void testBeginIsNotCalledOnTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + when(transaction.isActive()).thenReturn(true); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(0)).begin(); + } + + @Test + public void testCommitIsCalledOnNoTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(1)).commit(); + } + + @Test + public void testCommitIsNotCalledOnTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + when(transaction.isActive()).thenReturn(true); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(0)).commit(); + } + + @Test + public void testErrorReturnCodeWithRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(1); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testErrorReturnCodeWithOutRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(1); + when(transaction.isActive()).thenReturn(true); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + verify(transaction, times(0)).rollback(); + return; + } + fail(); + } + + @Test + public void testReraiseWithRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(2); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testReraiseReturnCodeWithOutRollback() throws ODataJPAProcessException { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(2); + when(transaction.isActive()).thenReturn(true); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + verify(transaction, times(0)).rollback(); + return; + } + fail(); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.clearFields(request, response); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.clearFields(request, response); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + when(request.getMethod()).thenReturn(HttpMethod.POST); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class), + any(HttpMethod.class)); + + try { + processor.clearFields(request, response); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.clearFields(request, response); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + private RequestHandleSpy prepareDeleteName2() { + + UriResourcePrimitiveProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Name2"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + private RequestHandleSpy prepareDeleteAddress() { + + UriResourceComplexProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Address"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + private RequestHandleSpy prepareDeleteAddressCountry() { + RequestHandleSpy spy = prepareDeleteAddress(); + + UriResourcePrimitiveProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Country"); + + return spy; + } + + private RequestHandleSpy prepareDeleteAdminInfo() { + + UriResourceComplexProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("AdministrativeInformation"); + + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Updated"); + + UriResourcePrimitiveProperty uriPrimProperty; + uriPrimProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriPrimProperty); + when(uriPrimProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("By"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public Map keyPredicates; + public Map jpaAttributes; + public JPAEntityType et; + public boolean called; + public Map> headers; + private int raiseEx; + + @Override + public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em, + final HttpMethod verb) throws ODataJPAProcessException { + + this.et = requestEntity.getEntityType(); + this.keyPredicates = requestEntity.getKeys(); + this.jpaAttributes = requestEntity.getData(); + this.headers = requestEntity.getAllHeader(); + called = true; + + if (raiseEx == 1) + throw new NullPointerException(); + if (raiseEx == 2) + throw new ODataJPAProcessorException(MessageKeys.NOT_SUPPORTED_DELETE, HttpStatusCode.NOT_IMPLEMENTED); + return null; + } + + public void raiseException(int type) { + this.raiseEx = type; + + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java new file mode 100644 index 0000000000..b8261fb380 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java @@ -0,0 +1,592 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.junit.Test; +import org.mockito.ArgumentMatchers; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPACreateProcessor extends TestJPAModifyProcessor { + + @Test + public void testHookIsCalled() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.called); + } + + @Test + public void testEntityTypeProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals("Organization", spy.et.getExternalName()); + } + + @SuppressWarnings("unchecked") + @Test + public void testAttributesProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + Map attributes = new HashMap<>(1); + + attributes.put("ID", "35"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(convHelper.convertProperties(ArgumentMatchers.any(OData.class), ArgumentMatchers.any(JPAStructuredType.class), + ArgumentMatchers.any( + List.class))).thenReturn(attributes); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.jpaAttributes); + assertEquals(1, spy.jpaAttributes.size()); + assertEquals("35", spy.jpaAttributes.get("ID")); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testThrowExpectedExceptionInCaseOfError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testThrowUnexpectedExceptionInCaseOfError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(NullPointerException.class).when(handler).createEntity(any(JPARequestEntity.class), any( + EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testMinimalResponseLocationHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testMinimalResponseODataEntityIdHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.ODATA_ENTITY_ID)); + } + + @Test + public void testMinimalResponseStatusCode() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponsePreferApplied() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals("return=minimal", response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testRepresentationResponseStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseStatusCodeMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + byte[] act = new byte[100]; + response.getContent().read(act); + String s = new String(act).trim(); + assertEquals("{\"ID\":\"35\"}", s); + } + + @Test + public void testRepresentationResponseContentMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + byte[] act = new byte[100]; + response.getContent().read(act); + String s = new String(act).trim(); + assertEquals("{\"ID\":\"35\"}", s); + } + + @Test + public void testRepresentationLocationHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testRepresentationLocationHeaderMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testResponseCreateChildSameTypeContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + when(ets.getName()).thenReturn("AdministrativeDivisions"); + final AdministrativeDivision div = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS1", + "DE6")); + final AdministrativeDivision child = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS2", + "DE60")); + div.getChildren().add(child); + final RequestHandleSpy spy = new RequestHandleSpy(div); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareRequestToCreateChild(spy); + + final UriResourceNavigation uriChild = mock(UriResourceNavigation.class); + final List uriKeys = new ArrayList<>(); + final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class); + + createKeyPredicate(uriKeys, "DivisionCode", "DE6"); + createKeyPredicate(uriKeys, "CodeID", "NUTS1"); + createKeyPredicate(uriKeys, "CodePublisher", "Eurostat"); + when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty); + when(uriChild.getProperty()).thenReturn(naviProperty); + when(naviProperty.getName()).thenReturn("Children"); + when(uriEts.getKeyPredicates()).thenReturn(uriKeys); + when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod(); + when(convHelper.buildGetterMap(div)).thenReturn(new JPAConversionHelper().determineGetter(div)); + when(convHelper.buildGetterMap(child)).thenReturn(new JPAConversionHelper().determineGetter(child)); + pathParts.add(uriChild); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.requestEntity.getKeys()); + assertEquals("DE6", spy.requestEntity.getKeys().get("divisionCode")); + assertNotNull(spy.requestEntity.getRelatedEntities()); + for (Entry> c : spy.requestEntity.getRelatedEntities().entrySet()) + assertEquals("Children", c.getKey().getAlias()); + } + + @Test + public void testResponseCreateChildDifferentTypeContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + final Organization org = new Organization("Test"); + final BusinessPartnerRole role = new BusinessPartnerRole(); + role.setBusinessPartner(org); + role.setRoleCategory("A"); + org.getRoles().add(role); + + final RequestHandleSpy spy = new RequestHandleSpy(org); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareRequestToCreateChild(spy); + + final UriResourceNavigation uriChild = mock(UriResourceNavigation.class); + final List uriKeys = new ArrayList<>(); + final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class); + final EdmNavigationPropertyBinding naviBinding = mock(EdmNavigationPropertyBinding.class); + final EdmEntityContainer container = mock(EdmEntityContainer.class); + final List naviBindings = new ArrayList<>(1); + final EdmEntitySet targetEts = mock(EdmEntitySet.class); + naviBindings.add(naviBinding); + + createKeyPredicate(uriKeys, "ID", "Test"); + when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty); + when(uriChild.getProperty()).thenReturn(naviProperty); + when(naviProperty.getName()).thenReturn("Roles"); + when(uriEts.getKeyPredicates()).thenReturn(uriKeys); + when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod(); + when(convHelper.buildGetterMap(org)).thenReturn(new JPAConversionHelper().determineGetter(org)); + when(convHelper.buildGetterMap(role)).thenReturn(new JPAConversionHelper().determineGetter(role)); + when(ets.getNavigationPropertyBindings()).thenReturn(naviBindings); + when(naviBinding.getPath()).thenReturn("Roles"); + when(naviBinding.getTarget()).thenReturn("BusinessPartnerRoles"); + when(ets.getEntityContainer()).thenReturn(container); + when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(targetEts); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.BusinessPartnerRole"); + final List keyNames = Arrays.asList("BusinessPartnerID", "RoleCategory"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + createKeyProperty(fqn, edmET, "BusinessPartnerID", "Test"); + createKeyProperty(fqn, edmET, "RoleCategory", "A"); + // edmType.getFullQualifiedName().getFullQualifiedNameAsString() + + pathParts.add(uriChild); + // return serviceMetadata.getEdm().getEntityType(es.getODataEntityType().getExternalFQN()); + // com.sap.olingo.jpa.BusinessPartnerRole + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.requestEntity.getKeys()); + assertEquals("Test", spy.requestEntity.getKeys().get("iD")); + assertNotNull(spy.requestEntity.getRelatedEntities()); + for (Entry> c : spy.requestEntity.getRelatedEntities().entrySet()) + assertEquals("Roles", c.getKey().getAlias()); + } + + protected ODataRequest prepareRequestToCreateChild(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + // .../AdministrativeDivisions(DivisionCode='DE6',CodeID='NUTS1',CodePublisher='Eurostat')/Children + final ODataRequest request = prepareSimpleRequest("return=representation"); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision"); + final List keyNames = Arrays.asList("DivisionCode", "CodeID", "CodePublisher"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + + createKeyProperty(fqn, edmET, "DivisionCode", "DE6"); + createKeyProperty(fqn, edmET, "CodeID", "NUTS1"); + createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat"); + + createKeyProperty(fqn, edmET, "DivisionCode", "DE60"); + createKeyProperty(fqn, edmET, "CodeID", "NUTS2"); + createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat"); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes())); + + return request; + } + + private void createKeyPredicate(final List uriKeys, String name, String value) { + UriParameter key = mock(UriParameter.class); + uriKeys.add(key); + when(key.getName()).thenReturn(name); + when(key.getText()).thenReturn("'" + value + "'"); + } + + private void createKeyProperty(final FullQualifiedName fqn, final EdmEntityType edmET, String name, String value) + throws EdmPrimitiveTypeException { + final EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + when(edmET.getKeyPropertyRef(name)).thenReturn(refType); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + final EdmProperty edmProperty = mock(EdmProperty.class); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn(name); + EdmPrimitiveType type = mock(EdmPrimitiveType.class); + when(edmProperty.getType()).thenReturn(type); + when(type.valueToString(ArgumentMatchers.eq(value), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers + .any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(value); + when(type.toUriLiteral(ArgumentMatchers.anyString())).thenReturn(value); + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public Map> headers; + public JPARequestEntity requestEntity; + private final Object result; + + RequestHandleSpy(Object result) { + this.result = result; + } + + RequestHandleSpy() { + this.result = new Organization(); + ((Organization) result).setID("35"); + } + + @Override + public Object createEntity(final JPARequestEntity requestEntity, EntityManager em) + throws ODataJPAProcessException { + + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + this.em = em; + this.headers = requestEntity.getAllHeader(); + this.called = true; + this.requestEntity = requestEntity; + return result; + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + this.noValidateCalls++; + } + + } + + class RequestHandleMapResultSpy extends JPAAbstractCUDRequestHandler { + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public JPARequestEntity requestEntity; + + @Override + public Object createEntity(final JPARequestEntity requestEntity, EntityManager em) + throws ODataJPAProcessException { + Map result = new HashMap<>(); + result.put("iD", "35"); + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + this.em = em; + this.called = true; + this.requestEntity = requestEntity; + return result; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java new file mode 100644 index 0000000000..0f6068f5ce --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java @@ -0,0 +1,347 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPADeleteProcessor { + private JPACUDRequestProcessor processor; + private OData odata; + private ServiceMetadata serviceMetadata; + private JPAODataSessionContextAccess sessionContext; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private UriResourceEntitySet uriEts; + private EdmEntitySet ets; + private List keyPredicates; + private JPAServiceDebugger debugger; + private EntityManager em; + private EntityTransaction transaction; + + private static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static EntityManagerFactory emf; + private static JPAEdmProvider jpaEdm; + private static DataSource ds; + + @BeforeClass + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + @Before + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + debugger = mock(JPAServiceDebugger.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + final List pathParts = new ArrayList<>(); + uriEts = mock(UriResourceEntitySet.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + pathParts.add(uriEts); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(sessionContext.getDebugger()).thenReturn(debugger); + when(requestContext.getEntityManager()).thenReturn(emf.createEntityManager()); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(ets.getName()).thenReturn("Organizations"); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + } + + @Test + public void testSuccessReturnCode() throws ODataApplicationException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(new RequestHandleSpy()); + + processor.deleteEntity(request, response); + assertEquals(204, response.getStatusCode()); + } + + @Test + public void testThrowUnexpectedExceptionInCaseOfError() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + doThrow(NullPointerException.class).when(handler).deleteEntity(any(JPARequestEntity.class), any( + EntityManager.class)); + + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testThrowExpectedExceptionInCaseOfError() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertEntityType() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param = mock(UriParameter.class); + + keyPredicates.add(param); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(param.getName()).thenReturn("ID"); + when(param.getText()).thenReturn("'1'"); + + processor.deleteEntity(request, response); + + assertEquals("com.sap.olingo.jpa.processor.core.testmodel.Organization", spy.et.getInternalName()); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = mock(ODataRequest.class); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.deleteEntity(request, response); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testConvertKeySingleAttribute() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param = mock(UriParameter.class); + + keyPredicates.add(param); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(param.getName()).thenReturn("ID"); + when(param.getText()).thenReturn("'1'"); + processor.deleteEntity(request, response); + + assertEquals(1, spy.keyPredicates.size()); + assertTrue(spy.keyPredicates.get("iD") instanceof String); + assertEquals("1", spy.keyPredicates.get("iD")); + } + + @Test + public void testConvertKeyTwoAttributes() throws ODataJPAProcessException { + // BusinessPartnerRole + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param1 = mock(UriParameter.class); + UriParameter param2 = mock(UriParameter.class); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(ets.getName()).thenReturn("BusinessPartnerRoles"); + when(param1.getName()).thenReturn("BusinessPartnerID"); + when(param1.getText()).thenReturn("'1'"); + when(param2.getName()).thenReturn("RoleCategory"); + when(param2.getText()).thenReturn("'A'"); + keyPredicates.add(param1); + keyPredicates.add(param2); + processor.deleteEntity(request, response); + + assertEquals(2, spy.keyPredicates.size()); + assertTrue(spy.keyPredicates.get("businessPartnerID") instanceof String); + assertEquals("1", spy.keyPredicates.get("businessPartnerID")); + assertTrue(spy.keyPredicates.get("roleCategory") instanceof String); + assertEquals("A", spy.keyPredicates.get("roleCategory")); + + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.deleteEntity(request, response); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + when(requestContext.getEntityManager()).thenReturn(em); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + + processor.deleteEntity(request, response); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.FALSE); + when(requestContext.getEntityManager()).thenReturn(em); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public Map keyPredicates; + public JPAEntityType et; + public Map> headers; + + @Override + public void deleteEntity(final JPARequestEntity entity, final EntityManager em) { + + this.keyPredicates = entity.getKeys(); + this.et = entity.getEntityType(); + this.headers = entity.getAllHeader(); + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java new file mode 100644 index 0000000000..2a160f2b3a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java @@ -0,0 +1,251 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.core.edm.primitivetype.EdmString; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.Before; +import org.junit.BeforeClass; +import org.mockito.ArgumentMatchers; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.query.EdmEntitySetInfo; +import com.sap.olingo.jpa.processor.core.serializer.JPASerializer; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public abstract class TestJPAModifyProcessor { + protected static final String LOCATION_HEADER = "Organization('35')"; + protected static final String PREFERENCE_APPLIED = "return=minimal"; + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static JPAEdmProvider jpaEdm; + protected static DataSource ds; + + @BeforeClass + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + protected JPACUDRequestProcessor processor; + protected OData odata; + protected ServiceMetadata serviceMetadata; + protected JPAODataSessionContextAccess sessionContext; + protected JPAODataRequestContextAccess requestContext; + protected UriInfo uriInfo; + protected UriResourceEntitySet uriEts; + protected EntityManager em; + protected EntityTransaction transaction; + protected JPASerializer serializer; + protected EdmEntitySet ets; + protected EdmEntitySetInfo etsInfo; + protected List keyPredicates; + protected JPAConversionHelper convHelper; + protected List pathParts = new ArrayList<>(); + protected SerializerResult serializerResult; + protected List header = new ArrayList<>(); + protected JPAServiceDebugger debugger; + + @Before + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + etsInfo = mock(EdmEntitySetInfo.class); + serializer = mock(JPASerializer.class); + uriEts = mock(UriResourceEntitySet.class); + pathParts.add(uriEts); + convHelper = mock(JPAConversionHelper.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + serializerResult = mock(SerializerResult.class); + debugger = mock(JPAServiceDebugger.class); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(sessionContext.getDebugger()).thenReturn(debugger); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(uriEts.getKind()).thenReturn(UriResourceKind.entitySet); + when(ets.getName()).thenReturn("Organizations"); + when(em.getTransaction()).thenReturn(transaction); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + + } + + protected ODataRequest prepareRepresentationRequest(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + + ODataRequest request = prepareSimpleRequest("return=representation"); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + Organization org = new Organization(); + when(em.find(Organization.class, "35")).thenReturn(org); + org.setID("35"); + Edm edm = mock(Edm.class); + when(serviceMetadata.getEdm()).thenReturn(edm); + EdmEntityType edmET = mock(EdmEntityType.class); + FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.Organization"); + when(edm.getEntityType(fqn)).thenReturn(edmET); + List keyNames = new ArrayList<>(); + keyNames.add("ID"); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + when(edmET.getKeyPropertyRef("ID")).thenReturn(refType); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + EdmProperty edmProperty = mock(EdmProperty.class); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("ID"); + EdmPrimitiveType type = mock(EdmPrimitiveType.class); + when(edmProperty.getType()).thenReturn(type); + when(type.toUriLiteral(ArgumentMatchers.any())).thenReturn("35"); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes())); + + return request; + } + + protected ODataRequest prepareLinkRequest(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + + // .../AdministrativeDivisions(DivisionCode='DE60',CodeID='NUTS2',CodePublisher='Eurostat') + final ODataRequest request = prepareSimpleRequest("return=representation"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision"); + final List keyNames = new ArrayList<>(); + + final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60"); + final AdministrativeDivision div = new AdministrativeDivision(key); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.find(AdministrativeDivision.class, key)).thenReturn(div); + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(ets.getName()).thenReturn("AdministrativeDivisions"); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + keyNames.add("DivisionCode"); + keyNames.add("CodeID"); + keyNames.add("CodePublisher"); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + + EdmPrimitiveType type = EdmString.getInstance(); + EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + EdmProperty edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("DivisionCode")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("DivisionCode"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + refType = mock(EdmKeyPropertyRef.class); + edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("CodeID")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("CodeID"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + refType = mock(EdmKeyPropertyRef.class); + edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("CodePublisher")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("CodePublisher"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ParentCodeID\":\"NUTS1\"}".getBytes())); + + return request; + + } + + protected ODataRequest prepareSimpleRequest() throws ODataException, ODataJPAProcessorException, SerializerException { + + return prepareSimpleRequest("return=minimal"); + } + + protected ODataRequest prepareSimpleRequest(String content) throws ODataException, ODataJPAProcessorException, + SerializerException { + + final EntityTransaction transaction = mock(EntityTransaction.class); + when(em.getTransaction()).thenReturn(transaction); + + final ODataRequest request = mock(ODataRequest.class); + when(request.getHeaders(HttpHeader.PREFER)).thenReturn(header); + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + header.add(content); + + Entity odataEntity = mock(Entity.class); + when(convHelper.convertInputStream(same(odata), same(request), same(ContentType.JSON), any())).thenReturn( + odataEntity); + when(convHelper.convertKeyToLocal(ArgumentMatchers.eq(odata), ArgumentMatchers.eq(request), ArgumentMatchers.eq( + ets), ArgumentMatchers.any(JPAEntityType.class), ArgumentMatchers.any())).thenReturn(LOCATION_HEADER); + return request; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java new file mode 100644 index 0000000000..4677a71698 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java @@ -0,0 +1,181 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; + +public class TestJPARequestLinkImpl { + private JPARequestLinkImpl cut; + private JPAAssociationPath path; + private List items; + private JPAConversionHelper helper; + private JPAAssociationAttribute pathLeaf; + + @Before + public void setUp() throws ODataJPAModelException { + helper = new JPAConversionHelper(); + items = new ArrayList(); + path = mock(JPAAssociationPath.class); + pathLeaf = mock(JPAAssociationAttribute.class); + when(path.getJoinColumnsList()).thenReturn(items); + } + + @Ignore + @Test + public void testCreateMultipleStringKeysChildren() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("codeID", "CodeID", "parentCodeID", "ParentCodeID")); + items.add(createConditionItem("divisionCode", "DivisionCode", "parentDivisionCode", "ParentDivisionCode")); + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("DE100", act.get("parentDivisionCode")); + assertEquals("NUTS3", act.get("parentCodeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateMultipleStringKeysParent() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("parentCodeID", "ParentCodeID", "codeID", "CodeID")); + items.add(createConditionItem("parentDivisionCode", "ParentDivisionCode", "divisionCode", "DivisionCode")); + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("DE100", act.get("divisionCode")); + assertEquals("NUTS3", act.get("codeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Ignore + @Test + public void testCreateMultipleStringValuesChildren() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("codeID", "CodeID", "parentCodeID", "ParentCodeID")); + items.add(createConditionItem("divisionCode", "DivisionCode", "parentDivisionCode", "ParentDivisionCode")); + Map act = cut.getValues(); + + assertNotNull(act); + assertEquals("DE100", act.get("divisionCode")); + assertEquals("NUTS3", act.get("codeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateMultipleStringValuesParent() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("parentCodeID", "ParentCodeID", "codeID", "CodeID")); + items.add(createConditionItem("parentDivisionCode", "ParentDivisionCode", "divisionCode", "DivisionCode")); + Map act = cut.getValues(); + + assertNotNull(act); + assertEquals("DE100", act.get("parentDivisionCode")); + assertEquals("NUTS3", act.get("parentCodeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateSingleStringKey() throws ODataJPAModelException, ODataException { + String link = "BusinessPartners('123456')"; + cut = new JPARequestLinkImpl(path, link, helper); + + completeJPAPath(); + + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("123456", act.get("ID")); + } + + @Test + public void testCreateSingleStringValue() throws ODataJPAModelException, ODataException { + String link = "BusinessPartners('123456')"; + cut = new JPARequestLinkImpl(path, link, helper); + completeJPAPath(); + + Map act = cut.getValues(); + assertNotNull(act); + assertEquals("123456", act.get("businessPartnerID")); + } + + private void completeJPAPath() throws ODataJPAModelException { + JPAEntityType targetEt = mock(JPAEntityType.class); + JPAEntityType sourceEt = mock(JPAEntityType.class); + JPAAttribute bupaKey = mock(JPAAttribute.class); + JPAAttribute roleKey1 = mock(JPAAttribute.class); + JPAAttribute roleKey2 = mock(JPAAttribute.class); + List bupaKeys = new ArrayList(); + List roleKeys = new ArrayList(); + bupaKeys.add(bupaKey); + roleKeys.add(roleKey1); + roleKeys.add(roleKey2); + when(bupaKey.getInternalName()).thenReturn("ID"); + when(bupaKey.getExternalName()).thenReturn("ID"); + when(roleKey1.getInternalName()).thenReturn("businessPartnerID"); + when(roleKey1.getExternalName()).thenReturn("BusinessPartnerID"); + when(roleKey2.getInternalName()).thenReturn("roleCategory"); + when(roleKey2.getExternalName()).thenReturn("BusinessPartnerRole"); + + items.add(createConditionItem("businessPartnerID", "BusinessPartnerID", "ID", "ID")); + when(path.getLeaf()).thenReturn(pathLeaf); + when(pathLeaf.getInternalName()).thenReturn("businessPartner"); + when(path.getTargetType()).thenReturn(targetEt); + when(path.getSourceType()).thenReturn(sourceEt); + when(targetEt.getKey()).thenReturn(bupaKeys); + when(sourceEt.getKey()).thenReturn(roleKeys); + } + + private JPAOnConditionItem createConditionItem(String leftInternalName, String leftExternalName, + String rightInternalName, String rightExternalName) throws ODataJPAModelException { + + JPAOnConditionItem item = mock(JPAOnConditionItem.class); + + JPAPath leftPath = mock(JPAPath.class); + JPAPath rightPath = mock(JPAPath.class); + when(item.getLeftPath()).thenReturn(leftPath); + when(item.getRightPath()).thenReturn(rightPath); + + JPAAttribute leftAttribute = mock(JPAAttribute.class); + JPAAttribute rightAttribute = mock(JPAAttribute.class); + when(leftPath.getLeaf()).thenReturn(leftAttribute); + when(rightPath.getLeaf()).thenReturn(rightAttribute); + + when(leftAttribute.getInternalName()).thenReturn(leftInternalName); + when(leftAttribute.getExternalName()).thenReturn(leftExternalName); + when(rightAttribute.getInternalName()).thenReturn(rightInternalName); + when(rightAttribute.getExternalName()).thenReturn(rightExternalName); + when(leftAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String); + when(rightAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String); + + return item; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java new file mode 100644 index 0000000000..2dc50848bb --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java @@ -0,0 +1,397 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpMethod; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAUpdateProcessor extends TestJPAModifyProcessor { + + @Test + public void testHockIsCalled() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.called); + } + + @Test + public void testHttpMethodProvided() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpMethod.PATCH, spy.method); + } + + @Test + public void testEntityTypeProvided() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.et instanceof JPAEntityType); + } + + @SuppressWarnings("unchecked") + @Test + public void testJPAAttributes() throws ODataJPAModelException, ODataException, UnsupportedEncodingException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + InputStream is = new ByteArrayInputStream("{\"ID\" : \"35\", \"Country\" : \"USA\"}".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + Map jpaAttributes = new HashMap<>(); + jpaAttributes.put("id", "35"); + jpaAttributes.put("country", "USA"); + when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class))) + .thenReturn(jpaAttributes); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(2, spy.jpaAttributes.size()); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testMinimalResponseUpdateStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponseCreatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponseUpdatePreferHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testMinimalResponseCreatedPreferHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testRepresentationResponseUpdatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false, + new Organization()))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseCreatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true, + new Organization()))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseUpdatedErrorMissingEntity() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false, null))); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testRepresentationResponseCreatedErrorMissingEntity() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true, null))); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class), + any(HttpMethod.class)); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testResponseErrorIfNull() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(null)); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testResponseUpdateLink() throws ODataJPAProcessorException, ODataException { + + final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60"); + final AdministrativeDivision resultEntity = new AdministrativeDivision(key); + + final AdministrativeDivisionKey childKey = new AdministrativeDivisionKey("Eurostat", "NUTS3", "DE600"); + final AdministrativeDivision childEntity = new AdministrativeDivision(childKey); + + final JPAUpdateResult result = new JPAUpdateResult(false, resultEntity); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareLinkRequest(new RequestHandleSpy(result)); + + resultEntity.setChildren(new ArrayList<>(Arrays.asList(childEntity))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertNotNull(response); + + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public HttpMethod method; + public Map> headers; + private final JPAUpdateResult change; + // private Map keys; + + RequestHandleSpy() { + this(new JPAUpdateResult(true, new Organization())); + } + + RequestHandleSpy(final JPAUpdateResult typeOfChange) { + this.change = typeOfChange; + } + + @Override + public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em, + final HttpMethod verb) throws ODataJPAProcessException { + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + // this.keys = requestEntity.getKeys(); + this.em = em; + this.called = true; + this.method = verb; + this.headers = requestEntity.getAllHeader(); + return change; + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + this.noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java new file mode 100644 index 0000000000..cfe31f8ae1 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java @@ -0,0 +1,364 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData; +import com.sap.olingo.jpa.processor.core.testobjects.BusinessPartnerRoleWithoutSetter; +import com.sap.olingo.jpa.processor.core.testobjects.OrganizationWithoutGetter; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestModifyUtil extends TestBase { + private JPAModifyUtil cut; + private Map jpaAttributes; + private BusinessPartner partner; + private JPAEntityType org; + + @Before + public void setUp() throws ODataException { + cut = new JPAModifyUtil(); + jpaAttributes = new HashMap<>(); + partner = new Organization(); + helper = new TestHelper(emf, PUNIT_NAME); + org = helper.getJPAEntityType("Organizations"); + } + + @Test + public void testSetAttributeOneAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + } + + @Test + public void testSetAttributeMultipleAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", "2"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributeIfAttributeNull() throws ODataJPAProcessException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", null); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNull(partner.getType()); + } + + @Test + public void testDoNotSetAttributeIfNotInMap() throws ODataJPAProcessException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributesDeepOneAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + } + + @Test + public void testSetAttributesDeepMultipleAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("country", "DEU"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("DEU", partner.getCountry()); + } + + @Test + public void testSetAttributeDeepIfAttributeNull() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", null); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNull(partner.getType()); + } + + @Test + public void testDoNotSetAttributeDeepIfNotInMap() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributesDeepShallIgnoreRequestEntities() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + JPARequestEntity roles = mock(JPARequestEntity.class); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("roles", roles); + cut.setAttributesDeep(jpaAttributes, partner, org); + } + + @Test + public void testSetAttributesDeepOneLevelViaGetter() throws ODataJPAProcessException, + ODataJPAInvocationTargetException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("address", embeddedAttributes); + embeddedAttributes.put("cityName", "Test Town"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAddress()); + assertEquals("Test Town", partner.getAddress().getCityName()); + } + + @Test(expected = NullPointerException.class) + public void testSetAttributesDeepOneLevelViaGetterWithWrongRequestData() throws Throwable { + Map embeddedAttributes = new HashMap<>(); + Map innerEmbeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("administrativeInformation", embeddedAttributes); + embeddedAttributes.put("updated", innerEmbeddedAttributes); + innerEmbeddedAttributes.put("by", null); + try { + cut.setAttributesDeep(jpaAttributes, partner, org); + } catch (ODataJPAInvocationTargetException e) { + assertEquals("Organization/AdministrativeInformation/Updated/By", e.getPath()); + throw e.getCause(); + } + } + + @Test + public void testDoNotSetAttributesDeepOneLevelIfNotProvided() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("address", null); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNull(partner.getAddress()); + } + + @Test + public void testSetAttributesDeepOneLevelIfNull() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + final PostalAddressData address = new PostalAddressData(); + address.setCityName("Test City"); + + partner.setAddress(address); + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAddress()); + assertEquals("Test City", partner.getAddress().getCityName()); + } + + @Test + public void testSetAttributesDeepOneLevelViaSetter() throws ODataJPAProcessException, + ODataJPAInvocationTargetException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("communicationData", embeddedAttributes); + embeddedAttributes.put("email", "Test@Town"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getCommunicationData()); + assertEquals("Test@Town", partner.getCommunicationData().getEmail()); + } + + @Test + public void testSetAttributesDeepTwoLevel() throws ODataJPAProcessException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + Map innerEmbeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("administrativeInformation", embeddedAttributes); + embeddedAttributes.put("updated", innerEmbeddedAttributes); + innerEmbeddedAttributes.put("by", "Hugo"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAdministrativeInformation()); + assertNotNull(partner.getAdministrativeInformation().getUpdated()); + assertEquals("Hugo", partner.getAdministrativeInformation().getUpdated().getBy()); + } + + @Test + public void testCreatePrimaryKeyOneStringKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + jpaAttributes.put("iD", "Willi"); + String act = (String) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals("Willi", act); + } + + @Test + public void testCreatePrimaryKeyOneIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Integer.class; + } + }); + + jpaAttributes.put("iD", new Integer(10)); + Integer act = (Integer) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals(new Integer(10), act); + } + + @Test + public void testCreatePrimaryKeyOneBigIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BigInteger.class; + } + }); + + jpaAttributes.put("iD", new BigInteger("10")); + BigInteger act = (BigInteger) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals(new BigInteger("10"), act); + } + + @Test + public void testCreatePrimaryKeyMultipleField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = mock(JPAEntityType.class); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return AdministrativeDivisionKey.class; + } + }); + + jpaAttributes.put("codePublisher", "Test"); + jpaAttributes.put("codeID", "10"); + jpaAttributes.put("divisionCode", "10.1"); + AdministrativeDivisionKey act = (AdministrativeDivisionKey) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals("Test", act.getCodePublisher()); + assertEquals("10", act.getCodeID()); + assertEquals("10.1", act.getDivisionCode()); + } + + @Test + public void testDeepLinkComplexNotExist() throws ODataJPAProcessorException, ODataJPAModelException { + final Organization source = new Organization("100"); + final Person target = new Person(); + target.setID("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "AdministrativeInformation/Updated/User"); + + cut.linkEntities(source, target, path); + + assertNotNull(source.getAdministrativeInformation()); + assertNotNull(source.getAdministrativeInformation().getUpdated()); + assertEquals(target, source.getAdministrativeInformation().getUpdated().getUser()); + } + + @Test + public void testDirectLink() throws ODataJPAProcessorException, ODataJPAModelException { + final Organization source = new Organization("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setBusinessPartnerID("100"); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.linkEntities(source, target, path); + + assertNotNull(source.getRoles()); + assertNotNull(source.getRoles().toArray()[0]); + assertEquals(target, source.getRoles().toArray()[0]); + } + + @Test + public void testSetForeignKeyOneKey() throws ODataJPAModelException, ODataJPAProcessorException { + final Organization source = new Organization("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.setForeignKey(source, target, path); + assertEquals("100", target.getBusinessPartnerID()); + } + + @Test(expected = ODataJPAProcessorException.class) + public void testSetForeignKeyTrhowsExceptionOnMissingGetter() throws ODataJPAModelException, + ODataJPAProcessorException { + final OrganizationWithoutGetter source = new OrganizationWithoutGetter("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.setForeignKey(source, target, path); + } + + @Test(expected = ODataJPAProcessorException.class) + public void testSetForeignKeyTrhowsExceptionOnMissingSetter() throws ODataJPAModelException, + ODataJPAProcessorException { + final Organization source = new Organization("100"); + final BusinessPartnerRoleWithoutSetter target = new BusinessPartnerRoleWithoutSetter(); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.setForeignKey(source, target, path); + } + + private JPAEntityType createSingleKeyEntityType() throws ODataJPAModelException { + final List keyAttributes = new ArrayList<>(); + final JPAAttribute keyAttribut = mock(JPAAttribute.class); + final JPAEntityType et = mock(JPAEntityType.class); + + when(keyAttribut.getInternalName()).thenReturn("iD"); + keyAttributes.add(keyAttribut); + when(et.getKey()).thenReturn(keyAttributes); + return et; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java new file mode 100644 index 0000000000..89e81876da --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.server.api.uri.UriParameter; +import org.junit.Before; +import org.junit.Test; + +public class TestEdmEntitySetResult { + private EdmEntitySetResult cut; + private List keys; + private EdmEntitySet es; + private EdmEntitySet est; + + @Before + public void setup() { + keys = new ArrayList<>(); + es = mock(EdmEntitySet.class); + when(es.getName()).thenReturn("Persons"); + est = mock(EdmEntitySet.class); + when(est.getName()).thenReturn("BusinessPartnerRoles"); + } + + @Test + public void testGetEntitySetName() { + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals("Persons", cut.getName()); + } + + @Test + public void testGetEntitySetGetKeys() { + final UriParameter key = mock(UriParameter.class); + when(key.getName()).thenReturn("ID"); + keys.add(key); + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals(keys, cut.getKeyPredicates()); + } + + @Test + public void testGetEntitySetGet() { + cut = new EdmEntitySetResult(es, keys, "Roles"); + assertEquals("Roles", cut.getNavigationPath()); + } + + @Test + public void testDetermineTargetEntitySetWithNaviNull() { + when(es.getNavigationPropertyBindings()).thenReturn(null); + cut = new EdmEntitySetResult(es, keys, null); + assertEquals(es, cut.getTargetEdmEntitySet()); + } + + @Test + public void testDetermineTargetEntitySetWithNaviEmpty() { + when(es.getNavigationPropertyBindings()).thenReturn(null); + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals(es, cut.getTargetEdmEntitySet()); + } + +// return edmEntitySet.getEntityContainer().getEntitySet(navi.getTarget()); + @Test + public void testDetermineTargetEntitySetWithNavigation() { + final EdmEntityContainer container = mock(EdmEntityContainer.class); + final List bindings = new ArrayList<>(2); + EdmNavigationPropertyBinding binding = mock(EdmNavigationPropertyBinding.class); + bindings.add(binding); + when(binding.getPath()).thenReturn("InhouseAddress"); + + binding = mock(EdmNavigationPropertyBinding.class); + bindings.add(binding); + when(binding.getPath()).thenReturn("Roles"); + when(binding.getTarget()).thenReturn("BusinessPartnerRoles"); + when(es.getEntityContainer()).thenReturn(container); + when(es.getNavigationPropertyBindings()).thenReturn(bindings); + when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(est); + + cut = new EdmEntitySetResult(es, keys, "Roles"); + assertEquals(es, cut.getEdmEntitySet()); + assertEquals(est, cut.getTargetEdmEntitySet()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java new file mode 100644 index 0000000000..3dd3394187 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java @@ -0,0 +1,249 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; + +public class TestJPAExpandQueryCreateResult extends TestBase { + private JPAExpandJoinQuery cut; + private JPAODataSessionContextAccess context; + + @Before + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + createHeaders(); + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "BusinessPartnerRole"); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, + TestBase.enumPackages), ds, null); + cut = new JPAExpandJoinQuery( + null, context, emf.createEntityManager(), new ExpandItemDouble(targetEntity).getResourcePath(), + helper.getJPAAssociationPath("Organizations", "Roles"), helper.sd.getEntity(targetEntity), + new HashMap>()); + // new EdmEntitySetDouble(nameBuilder, "Organisations"), null, new HashMap>()); + } + + @Test + public void checkConvertOneResult() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "1"); + oneResult.put("RoleCategory", "A"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("1")); + assertEquals(1, act.get("1").size()); + assertEquals("1", act.get("1").get(0).get("BusinessPartnerID")); + } + + @Test + public void checkConvertTwoResultOneParent() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(2, act.get("2").size()); + assertEquals("2", act.get("2").get(0).get("BusinessPartnerID")); + } + + @Test + public void checkConvertTwoResultOneParentTop1() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, 1); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("A", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertTwoResultOneParentSkip1() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 1, 1000); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("C", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertTwoResultTwoParent() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "1"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(2, act.size()); + assertNotNull(act.get("1")); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("C", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertOneResultCompundKey() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent"); + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE25"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE2"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("NUTS/2/BE25")); + assertEquals(1, act.get("NUTS/2/BE25").size()); + assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode")); + } + + @Test + public void checkConvertTwoResultsCompundKey() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE25"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE2"); + t = new TupleDouble(oneResult); + result.add(t); + + oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE10"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE1"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(2, act.size()); + assertNotNull(act.get("NUTS/2/BE25")); + assertEquals(1, act.get("NUTS/2/BE25").size()); + assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode")); + assertNotNull(act.get("NUTS/2/BE10")); + assertEquals(1, act.get("NUTS/2/BE10").size()); + assertEquals("BE1", act.get("NUTS/2/BE10").get(0).get("ParentDivisionCode")); + } + + @Test + public void checkConvertOneResultJoinTable() throws ODataException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "SupportEngineers"); + + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "Person"); + cut = new JPAExpandJoinQuery( + null, context, emf.createEntityManager(), new ExpandItemDouble(targetEntity).getResourcePath(), + helper.getJPAAssociationPath("Organizations", "SupportEngineers"), helper.sd.getEntity(targetEntity), + new HashMap>()); + + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("SupportEngineers" + JPAExpandJoinQuery.ALIAS_SEPERATOR + "ID", "2"); + oneResult.put("ID", "97"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("97", act.get("2").get(0).get("ID")); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java new file mode 100644 index 0000000000..b02e16799f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java @@ -0,0 +1,116 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.Expression; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAExpandResult extends TestBase { + private JPAExpandJoinQuery cut; + private EntityManager em; + private JPAODataSessionContextAccess sessionContext; + private TestHelper helper; + + @Before + public void setup() throws ODataException { + createHeaders(); + helper = new TestHelper(emf, PUNIT_NAME); + em = emf.createEntityManager(); + sessionContext = mock(JPAODataSessionContextAccess.class); + JPAServiceDebugger debugger = mock(JPAServiceDebugger.class); + + when(sessionContext.getEdmProvider()).thenReturn(helper.edmProvider); + when(sessionContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor()); + when(sessionContext.getDebugger()).thenReturn(debugger); + } + + @Test + public void testSelectAllWithAllExpand() throws ODataException { + // .../Organizations?$expand=Roles&$format=json + JPAInlineItemInfo item = createOrgExpandRoles(null, null); + + cut = new JPAExpandJoinQuery(OData.newInstance(), sessionContext, em, item, headers); + JPAExpandQueryResult act = cut.execute(); + assertEquals(4, act.getNoResults()); + assertEquals(7, act.getNoResultsDeep()); + } + + @Test + public void testSelectOrgByIdWithAllExpand() throws ODataException { + + // .../Organizations('2')?$expand=Roles&$format=json + UriParameter key = mock(UriParameter.class); + when(key.getName()).thenReturn("ID"); + when(key.getText()).thenReturn("'2'"); + List keyPredicates = new ArrayList<>(); + keyPredicates.add(key); + JPAInlineItemInfo item = createOrgExpandRoles(keyPredicates, null); + + cut = new JPAExpandJoinQuery(OData.newInstance(), sessionContext, em, item, headers); + JPAExpandQueryResult act = cut.execute(); + assertEquals(1, act.getNoResults()); + assertEquals(2, act.getNoResultsDeep()); + } + + private JPAInlineItemInfo createOrgExpandRoles(final List keyPredicates, Expression expression) + throws ODataJPAModelException, ODataApplicationException { + JPAEntityType et = helper.getJPAEntityType("BusinessPartnerRoles"); + JPAExpandItemWrapper uriInfo = mock(JPAExpandItemWrapper.class); + UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + EdmEntityType edmType = mock(EdmEntityType.class); + + List hops = new ArrayList<>(); + JPANavigationProptertyInfo hop = new JPANavigationProptertyInfo(helper.sd, uriEts, helper.getJPAEntityType( + "Organizations").getAssociationPath("Roles"), null); + hops.add(hop); + + JPAInlineItemInfo item = mock(JPAInlineItemInfo.class); + UriResourceNavigation target = mock(UriResourceNavigation.class); + EdmNavigationProperty targetProperty = mock(EdmNavigationProperty.class); + when(targetProperty.getName()).thenReturn("Roles"); + when(target.getProperty()).thenReturn(targetProperty); + List resourceParts = new ArrayList<>(); + resourceParts.add(target); + + hop = new JPANavigationProptertyInfo(helper.sd, null, null, et); + hops.add(hop); + + when(item.getEntityType()).thenReturn(et); + when(item.getUriInfo()).thenReturn(uriInfo); + when(item.getHops()).thenReturn(hops); + when(item.getExpandAssociation()).thenReturn(helper.getJPAEntityType("Organizations") + .getAssociationPath("Roles")); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriEts.getType()).thenReturn(edmType); + when(edmType.getNamespace()).thenReturn(PUNIT_NAME); + when(edmType.getName()).thenReturn("Organization"); + return item; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java new file mode 100644 index 0000000000..a55f63b9ba --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.query; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAFunction { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static DataSource ds; + + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + + @Before + public void setup() { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + emf.getProperties(); + } + + @Ignore // TODO check is path is in general allowed + @Test + public void testNavigationAfterFunctionNotAllowed() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, + "Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Parent"); + helper.assertStatus(501); + } + + @Test + public void testFunctionGenerateQueryString() throws IOException, ODataException, SQLException { + createFunction(); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, + "Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')"); + helper.assertStatus(200); + } + + private void createFunction() { + final EntityManager em = emf.createEntityManager(); + final EntityTransaction t = em.getTransaction(); + final StringBuilder createSiblingsString = new StringBuilder(); + createSiblingsString.append( + "CREATE FUNCTION \"OLINGO\".\"Siblings\" (\"Publisher\" VARCHAR(10), \"ID\" VARCHAR(10), \"Division\" VARCHAR(10)) "); + createSiblingsString.append( + "RETURNS TABLE(\"CodePublisher\" VARCHAR(10),\"CodeID\" VARCHAR(10),\"DivisionCode\" VARCHAR(10),"); + createSiblingsString.append( + "\"CountryISOCode\" VARCHAR(4), \"ParentCodeID\" VARCHAR(10),\"ParentDivisionCode\" VARCHAR(10),"); + createSiblingsString.append("\"AlternativeCode\" VARCHAR(10),\"Area\" int, \"Population\" BIGINT) "); + createSiblingsString.append("READS SQL DATA "); + createSiblingsString.append("RETURN TABLE( SELECT * FROM \"AdministrativeDivision\" as a WHERE "); + createSiblingsString.append("EXISTS (SELECT \"CodePublisher\" "); + createSiblingsString.append("FROM \"OLINGO\".\"AdministrativeDivision\" as b "); + createSiblingsString.append("WHERE b.\"CodeID\" = \"ID\" "); + createSiblingsString.append("AND b.\"DivisionCode\" = \"Division\" "); + createSiblingsString.append("AND b.\"CodePublisher\" = a.\"CodePublisher\" "); + createSiblingsString.append("AND b.\"ParentCodeID\" = a.\"ParentCodeID\" "); + createSiblingsString.append("AND b.\"ParentDivisionCode\" = a.\"ParentDivisionCode\") "); + createSiblingsString.append("AND NOT( a.\"CodePublisher\" = \"Publisher\" "); + createSiblingsString.append("AND a.\"CodeID\" = \"ID\" "); + createSiblingsString.append("AND a.\"DivisionCode\" = \"Division\" )); "); + t.begin(); + Query qP = em.createNativeQuery(createSiblingsString.toString()); + qP.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java new file mode 100644 index 0000000000..036b36ccf0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java @@ -0,0 +1,149 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.notNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.core.edm.primitivetype.EdmBoolean; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; + +public class TestJPAFunctionDB { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + private JPAODataDatabaseProcessor dbProcessor; + + private OData odata; + private JPAODataSessionContextAccess context; + private JPAODataRequestContextAccess requestContext; + private ODataRequest request; + private ODataResponse response; + private JPAFunctionRequestProcessor cut; + private EdmFunction edmFunction; + private UriInfo uriInfo; + private List uriResources; + private UriResourceFunction uriResource; + private JPAServiceDocument sd; + private JPADataBaseFunction function; + private JPAOperationSerializer serializer; + private SerializerResult serializerResult; + private EntityManager em; + + @Before + public void setup() throws ODataException { + final JPAEdmProvider provider = mock(JPAEdmProvider.class); + + em = mock(EntityManager.class); + request = mock(ODataRequest.class); + response = mock(ODataResponse.class); + uriInfo = mock(UriInfo.class); + odata = mock(OData.class); + serializer = mock(JPAOperationSerializer.class); + serializerResult = mock(SerializerResult.class); + context = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + dbProcessor = mock(JPAODataDatabaseProcessor.class); + sd = mock(JPAServiceDocument.class); + uriResource = mock(UriResourceFunction.class); + function = mock(JPADataBaseFunction.class); + uriResources = new ArrayList<>(); + edmFunction = mock(EdmFunction.class); + + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getEntityManager()).thenReturn(em); + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(context.getDatabaseProcessor()).thenReturn(dbProcessor); + when(context.getEdmProvider()).thenReturn(provider); + when(provider.getServiceDocument()).thenReturn(sd); + uriResources.add(uriResource); + when(uriResource.getFunction()).thenReturn(edmFunction); + when(sd.getFunction(edmFunction)).thenReturn(function); + when(function.getFunctionType()).thenReturn(EdmFunctionType.UserDefinedFunction); + cut = new JPAFunctionRequestProcessor(odata, context, requestContext); + } + + @Test + public void testCallsFunctionWithBooleanReturnType() throws ODataApplicationException, ODataLibraryException, + ODataJPAModelException { + + EdmReturnType edmReturnType = mock(EdmReturnType.class); + JPAOperationResultParameter resultParam = mock(JPAOperationResultParameter.class); + when(function.getResultParameter()).thenReturn(resultParam); + when(resultParam.getTypeFQN()).thenReturn(new FullQualifiedName(PUNIT_NAME, "CheckRights")); + when(resultParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Boolean.class; + } + }); + + when(edmFunction.getReturnType()).thenReturn(edmReturnType); + when(edmReturnType.getType()).thenReturn(new EdmBoolean()); + + cut.retrieveData(request, response, ContentType.JSON); + verify(dbProcessor, times(1)).executeFunctionQuery(eq(uriResources), eq(function), (Class) notNull(), eq(em)); + } + + @Test + public void testCallsFunctionCount() throws ODataApplicationException, ODataLibraryException, + ODataJPAModelException { + + EdmReturnType edmReturnType = mock(EdmReturnType.class); + JPAOperationResultParameter resultParam = mock(JPAOperationResultParameter.class); + when(function.getResultParameter()).thenReturn(resultParam); + when(resultParam.getTypeFQN()).thenReturn(new FullQualifiedName(PUNIT_NAME, "CheckRights")); + when(resultParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Boolean.class; + } + }); + + when(edmFunction.getReturnType()).thenReturn(edmReturnType); + when(edmReturnType.getType()).thenReturn(new EdmBoolean()); + + cut.retrieveData(request, response, ContentType.JSON); + verify(dbProcessor, times(1)).executeFunctionQuery(eq(uriResources), eq(function), (Class) notNull(), eq(em)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java new file mode 100644 index 0000000000..088aaa04e0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java @@ -0,0 +1,162 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmParameter; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionParameter; + +public class TestJPAFunctionJava { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + private JPAFunctionRequestProcessor cut; + private OData odata; + private JPAODataSessionContextAccess context; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private List uriResources; + private ODataRequest request; + private ODataResponse response; + private UriResourceFunction uriResource; + private EdmFunction edmFunction; + private JPAOperationSerializer serializer; + private SerializerResult serializerResult; + + @Before + public void setup() throws ODataException { + odata = mock(OData.class); + context = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + EntityManager em = mock(EntityManager.class); + uriInfo = mock(UriInfo.class); + serializer = mock(JPAOperationSerializer.class); + serializerResult = mock(SerializerResult.class); + + DataSource ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + final EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + uriResources = new ArrayList<>(); + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(context.getEdmProvider()).thenReturn(new JPAEdmProvider(PUNIT_NAME, emf, null, new String[] { + "com.sap.olingo.jpa.processor.core", "com.sap.olingo.jpa.processor.core.testmodel" })); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + + request = mock(ODataRequest.class); + response = mock(ODataResponse.class); + uriResource = mock(UriResourceFunction.class); + edmFunction = mock(EdmFunction.class); + uriResources.add(uriResource); + when(uriResource.getFunction()).thenReturn(edmFunction); + + cut = new JPAFunctionRequestProcessor(odata, context, requestContext); + } + + @After + public void teardown() { + TestFunctionParameter.calls = 0; + TestFunctionParameter.param1 = 0; + TestFunctionParameter.param2 = 0; + } + + @Test + public void testCallsFunction() throws ODataApplicationException, ODataLibraryException { + EdmParameter edmParamA = mock(EdmParameter.class); + EdmParameter edmParamB = mock(EdmParameter.class); + EdmReturnType edmReturn = mock(EdmReturnType.class); + EdmType edmType = mock(EdmType.class); + + when(edmFunction.getReturnType()).thenReturn(edmReturn); + when(edmFunction.getName()).thenReturn("Sum"); + when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME); + when(edmFunction.getParameter("A")).thenReturn(edmParamA); + when(edmParamA.getType()).thenReturn(new EdmInt32()); + when(edmFunction.getParameter("B")).thenReturn(edmParamB); + when(edmParamB.getType()).thenReturn(new EdmInt32()); + List parameterList = buildParameters(); + when(uriResource.getParameters()).thenReturn(parameterList); + when(edmReturn.getType()).thenReturn(edmType); + when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.retrieveData(request, response, ContentType.JSON); + assertEquals(1, TestFunctionParameter.calls); + } + + @Test + public void testProvidesParameter() throws ODataApplicationException, ODataLibraryException { + EdmParameter edmParamA = mock(EdmParameter.class); + EdmParameter edmParamB = mock(EdmParameter.class); + EdmReturnType edmReturn = mock(EdmReturnType.class); + EdmType edmType = mock(EdmType.class); + + when(edmFunction.getReturnType()).thenReturn(edmReturn); + when(edmFunction.getName()).thenReturn("Sum"); + when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME); + when(edmFunction.getParameter("A")).thenReturn(edmParamA); + when(edmParamA.getType()).thenReturn(new EdmInt32()); + when(edmFunction.getParameter("B")).thenReturn(edmParamB); + when(edmParamB.getType()).thenReturn(new EdmInt32()); + List parameterList = buildParameters(); + when(uriResource.getParameters()).thenReturn(parameterList); + when(edmReturn.getType()).thenReturn(edmType); + when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.retrieveData(request, response, ContentType.JSON); + assertEquals(5, TestFunctionParameter.param1); + assertEquals(7, TestFunctionParameter.param2); + } + + private List buildParameters() { + UriParameter param1 = mock(UriParameter.class); + UriParameter param2 = mock(UriParameter.class); + when(param1.getName()).thenReturn("A"); + when(param1.getText()).thenReturn("5"); + when(param2.getName()).thenReturn("B"); + when(param2.getText()).thenReturn("7"); + return Arrays.asList(new UriParameter[] { param1, param2 }); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java new file mode 100644 index 0000000000..82254025df --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java @@ -0,0 +1,187 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAFunctionSerializer { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static DataSource ds; + + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + + @Before + public void setup() { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + emf.getProperties(); + } + + @Test + public void testFunctionReturnsEntityType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("Area").asInt()); + assertEquals(1250, r.get("Area").asInt()); + } + + @Test + public void testFunctionReturnsEntityTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsEntityTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityType(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + ArrayNode values = (ArrayNode) r.get("value"); + assertNotNull(values.get(0)); + assertNotNull(values.get(0).get("Area").asInt()); + assertEquals(1250, values.get(0).get("Area").asInt()); + assertNotNull(values.get(1)); + assertNotNull(values.get(1).get("Area").asInt()); + assertEquals(625, values.get(1).get("Area").asInt()); + } + + @Test + public void testFunctionReturnsPrimitiveType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r); + assertNotNull(r.get("value")); + assertEquals(124, r.get("value").asInt()); + } + + @Test + public void testFunctionReturnsPrimitiveTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsPrimitiveTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfPrimitiveValues(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ArrayNode r = helper.getValues(); + assertNotNull(r); + assertNotNull(r.get(0)); + assertEquals(124, r.get(0).asInt()); + assertNotNull(r.get(1)); + assertEquals(62, r.get(1).asInt()); + } + + @Test + public void testFunctionReturnsComplexType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r); + assertNotNull(r.get("LandlinePhoneNumber")); + assertEquals(124, r.get("LandlinePhoneNumber").asInt()); + } + + @Test + public void testFunctionReturnsComplexTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsComplexTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfComplexType(A='Willi')", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ArrayNode r = helper.getValues(); + assertNotNull(r); + assertNotNull(r.get(0)); + assertNotNull(r.get(0).get("Created")); + } + + @Test + public void testUsesConverter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ConvertBirthday()", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + } + + @Test + public void testFunctionReturnsEntityTypeWithCollection() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityTypeWithCollction(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("value")); + ObjectNode person = (ObjectNode) r.get("value").get(0); + ArrayNode addr = (ArrayNode) person.get("InhouseAddress"); + assertEquals(2, addr.size()); + } + + @Test + public void testFunctionReturnsEntityTypeWithDeepCollection() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityTypeWithDeepCollction(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("FirstLevel")); + ObjectNode first = (ObjectNode) r.get("FirstLevel"); + assertEquals(10, first.get("LevelID").asInt()); + + assertNotNull(first.get("SecondLevel")); + ObjectNode second = (ObjectNode) first.get("SecondLevel"); + assertEquals(5L, second.get("Number").asLong()); + ArrayNode addr = (ArrayNode) second.get("Address"); + assertEquals(2, addr.size()); + assertEquals("ADMIN", addr.get(1).get("TaskID").asText()); + + ArrayNode comment = (ArrayNode) second.get("Comment"); + assertEquals(3, comment.size()); + assertEquals("Three", comment.get(2).asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java new file mode 100644 index 0000000000..6afdf27c6d --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java @@ -0,0 +1,126 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.converter.JPAEntityResultConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPAInstanceResultConverter extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPAEntityResultConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + + @Before + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList(); + HashMap keyStrings = new HashMap(); + keyStrings.put("BE21", "DivisionCode='BE21',CodeID='NUTS2',CodePublisher='Eurostat'"); + keyStrings.put("BE22", "DivisionCode='BE22',CodeID='NUTS2',CodePublisher='Eurostat'"); + + uriHelper = new UriHelperDouble(); + uriHelper.setKeyPredicates(keyStrings, "DivisionCode"); + cut = new JPAEntityResultConverter(uriHelper, helper.sd, + jpaQueryResult, new EdmEntityTypeDouble(nameBuilder, "AdministrativeDivision")); + } + + @Test + public void checkConvertsEmptyResult() throws ODataApplicationException, SerializerException, URISyntaxException { + assertNotNull(cut.getResult()); + } + + @Test + public void checkConvertsOneResult() throws ODataApplicationException, SerializerException, URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + } + + @Test + public void checkConvertsTwoResult() throws ODataApplicationException, SerializerException, URISyntaxException { + + jpaQueryResult.add(firstResult()); + jpaQueryResult.add(secondResult()); + EntityCollection act = cut.getResult(); + assertEquals(2, act.getEntities().size()); + } + + @Test + public void checkConvertsOneResultOneElement() throws ODataApplicationException, SerializerException, + URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + assertEquals("BE21", act.getEntities().get(0).getProperty("DivisionCode").getValue().toString()); + + } + + @Test + public void checkConvertsOneResultMultiElement() throws ODataApplicationException, SerializerException, + URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + assertEquals("BE21", act.getEntities().get(0).getProperty("DivisionCode").getValue().toString()); + assertEquals("BE2", act.getEntities().get(0).getProperty("ParentDivisionCode").getValue().toString()); + assertEquals("0", act.getEntities().get(0).getProperty("Population").getValue().toString()); + } + + AdministrativeDivision firstResult() { + AdministrativeDivision division = new AdministrativeDivision(); + + division.setCodePublisher("Eurostat"); + division.setCodeID("NUTS2"); + division.setDivisionCode("BE21"); + division.setCountryCode("BEL"); + division.setParentCodeID("NUTS1"); + division.setParentDivisionCode("BE2"); + division.setAlternativeCode(""); + division.setArea(0); + division.setPopulation(0); + return division; + } + + private Object secondResult() { + AdministrativeDivision division = new AdministrativeDivision(); + + division.setCodePublisher("Eurostat"); + division.setCodeID("NUTS2"); + division.setDivisionCode("BE22"); + division.setCountryCode("BEL"); + division.setParentCodeID("NUTS1"); + division.setParentDivisionCode("BE2"); + division.setAlternativeCode(""); + division.setArea(0); + division.setPopulation(0); + return division; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java new file mode 100644 index 0000000000..74329c6f29 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java @@ -0,0 +1,633 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Ignore; +import org.junit.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAProcessorExpand extends TestBase { + + @Test + public void testExpandEntitySet() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID&$expand=Roles"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + ObjectNode org = (ObjectNode) orgs.get(0); + ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(1, roles.size()); + + org = (ObjectNode) orgs.get(3); + roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + } + + @Test + public void testExpandOneEntity() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('2')?$expand=Roles"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(2, roles.size()); + int found = 0; + for (final JsonNode role : roles) { + final String id = role.get("BusinessPartnerID").asText(); + final String code = role.get("RoleCategory").asText(); + if (id.equals("2") && (code.equals("A") || code.equals("C"))) + found++; + } + assertEquals("Not all expected results found", 2, found); + } + + @Test + public void testExpandOneEntityCompoundKey() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent"); + helper.assertStatus(200); + + final ObjectNode divsion = helper.getValue(); + final ObjectNode parent = (ObjectNode) divsion.get("Parent"); + assertEquals("BE2", parent.get("DivisionCode").asText()); + + } + + @Test + public void testExpandOneEntityCompoundKeyCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)"); + helper.assertStatus(200); + + final ObjectNode divsion = helper.getValue(); + final ArrayNode parent = (ArrayNode) divsion.get("Children"); + assertEquals(8, parent.size()); + assertEquals("BE251", parent.get(0).get("DivisionCode").asText()); + + } + + @Test + public void testExpandEntitySetWithOutParentKeySelection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Name1&$select=Name1&$expand=Roles"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(9); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + + } + + @Test + public void testExpandEntitySetViaNonKeyField_FieldNotSelected() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created?$select=At&$expand=User"); + helper.assertStatus(200); + + final ObjectNode created = helper.getValue(); + assertNotNull(created.get("User")); + } + + @Test + public void testExpandEntitySetViaNonKeyFieldNavi2Hops() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created?$expand=User"); + helper.assertStatus(200); + + final ObjectNode created = helper.getValue(); + @SuppressWarnings("unused") + final ObjectNode user = (ObjectNode) created.get("User"); + } + + @Test + public void testExpandEntityViaComplexProperty() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address?$expand=AdministrativeDivision"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ObjectNode created = (ObjectNode) org.get("AdministrativeDivision"); + assertEquals("USA", created.get("ParentDivisionCode").asText()); + } + + @Ignore // Version 4.4.0 of olingo does not path the expand correctly + // org.apache.olingo.server.core.uri.parser.ExpandParser -> parseExpandPath + // see https://issues.apache.org/jira/browse/OLINGO-1143 + @Test + public void testExpandEntitySetViaNonKeyFieldNavi0Hops() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$expand=AdministrativeInformation/Created/User"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ObjectNode admin = (ObjectNode) org.get("AdministrativeInformation"); + final ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User")); + + } + + @Ignore // Version 4.4.0 of olingo does not path the expand correctly + // org.apache.olingo.server.core.uri.parser.ExpandParser -> parseExpandPath + // see https://issues.apache.org/jira/browse/OLINGO-1143 + @Test + public void testExpandEntitySetViaNonKeyFieldNavi1Hop() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation?$expand=Created/User"); + helper.assertStatus(200); + + final ObjectNode admin = helper.getValue(); + final ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User")); + } + + @Test + public void testNestedExpandNestedExpand2LevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($expand=Children)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Children")); + final ArrayNode children = (ArrayNode) parent.get("Children"); + assertEquals(8, children.size()); + assertEquals("NUTS3", children.get(0).get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand3LevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='33016',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Parent")); + assertNotNull(parent.get("Parent").get("CodeID")); + assertEquals("NUTS3", parent.get("CodeID").asText()); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent); + assertNotNull(grandParent.get("CodeID")); + assertEquals("NUTS2", grandParent.get("CodeID").asText()); + final ObjectNode greateGrandParent = (ObjectNode) grandParent.get("Parent"); + assertNotNull(greateGrandParent); + assertNotNull(greateGrandParent.get("CodeID")); + assertEquals("NUTS1", greateGrandParent.get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand3Only1PossibleLevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("CodeID")); + assertEquals("NUTS1", parent.get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand2LevelsMixed() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address?$select=Country&$expand=AdministrativeDivision($expand=Parent)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode admin = (ObjectNode) div.get("AdministrativeDivision"); + assertNotNull(admin); + final ObjectNode parent = (ObjectNode) admin.get("Parent"); + assertEquals("3166-1", parent.get("CodeID").asText()); + } + + @Ignore // TODO check how the result should look like + @Test + public void testExpandWithNavigationToEntity() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='3',CodePublisher='NUTS')?$expand=Parent/Parent"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Parent").get("CodeID")); + assertEquals("1", parent.get("Parent").get("CodeID").asText()); + } + + @Ignore // TODO check with Olingo looks like OData does not support this + @Test + public void testExpandWithNavigationToProperty() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent/CodeID"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("CodeID")); + assertEquals("NUTS2", parent.get("CodeID").asText()); + // TODO: Check how to create the response correctly + // assertEquals(1, parent.size()); + } + + @Test + public void testExpandAfterNavigationToEntity() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'&$expand=Children($orderby=DivisionCode)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("value").get(0).get("Children"); + assertNotNull(children); + assertEquals(3, children.size()); + assertEquals("BE211", children.get(0).get("DivisionCode").asText()); + assertEquals("BE212", children.get(1).get("DivisionCode").asText()); + assertEquals("BE213", children.get(2).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDesc() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(5, children.size()); + assertEquals("BE25", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByAsc() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(5, children.size()); + assertEquals("BE21", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDescTop() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($top=2;$orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(2, children.size()); + assertEquals("BE25", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDescTopSkip() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($top=2;$skip=2;$orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(2, children.size()); + assertEquals("BE23", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithCount() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($count=true)&$orderby=Roles/$count desc"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("Roles")); + ArrayNode roles = (ArrayNode) org.get("Roles"); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(roles.size(), org.get("Roles@odata.count").asInt()); + } + + @Test + public void testExpandWithCountPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('2')?$expand=Roles/$count"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(2, org.get("Roles@odata.count").asInt()); + } + + @Ignore // ODataJsonSerializer.writeExpandedNavigationProperty does not write a "@odata.count" for to 1 relations + @Test + public void testExpandOppositeDirectionWithCount() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')?$expand=Organization/$count"); + helper.assertStatus(200); + + final ObjectNode role = helper.getValue(); + assertNotNull(role.get("Organization")); + assertNotNull(role.get("Organization@odata.count")); + assertEquals(1, role.get("Organization@odata.count").asText()); + } + + @Test + public void testExpandWithCountAndTop() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($count=true;$top=1)&$orderby=Roles/$count desc"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("Roles")); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(3, org.get("Roles@odata.count").asInt()); + } + + @Test + public void testExpandWithOrderByDescTopSkipAndExternalOrderBy() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($orderby=RoleCategory desc)&$orderby=Roles/$count desc"); + + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertEquals("3", org.get("ID").asText()); + assertNotNull(org.get("Roles")); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + final ObjectNode firstRole = (ObjectNode) roles.get(0); + assertEquals("C", firstRole.get("RoleCategory").asText()); + } + + @Test + public void testExpandWithFilter() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($filter=DivisionCode eq 'BE252')"); + + helper.assertStatus(200); + + final ObjectNode division = helper.getValue(); + assertEquals("BE25", division.get("DivisionCode").asText()); + assertNotNull(division.get("Children")); + final ArrayNode children = (ArrayNode) division.get("Children"); + assertEquals(1, children.size()); + final ObjectNode firstChild = (ObjectNode) children.get(0); + assertEquals("BE252", firstChild.get("DivisionCode").asText()); + } + + @Test + public void testFilterExpandWithFilter() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode eq 'BE25' and CodeID eq 'NUTS2'&$expand=Children($filter=DivisionCode eq 'BE252')"); + + helper.assertStatus(200); + + final JsonNode value = helper.getValue().get("value"); + assertNotNull(value.get(0)); + final ObjectNode division = (ObjectNode) value.get(0); + + assertEquals("BE25", division.get("DivisionCode").asText()); + ArrayNode children = (ArrayNode) division.get("Children"); + assertEquals(1, children.size()); + final ObjectNode firstChild = (ObjectNode) children.get(0); + assertEquals("BE252", firstChild.get("DivisionCode").asText()); + } + + @Test + public void testFilterExpandWithFilterOnParentDescription() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=LocationName eq 'Deutschland'&$expand=Roles&$orderby=ID asc"); + + helper.assertStatus(200); + + final JsonNode value = helper.getValue().get("value"); + assertNotNull(value.get(0)); + final ArrayNode roles = (ArrayNode) value.get(0).get("Roles"); + + assertEquals(1, roles.size()); + } + + @Test + public void testExpandCompleteEntitySet() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$expand=Roles&orderby=ID"); + + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertEquals("1", org.get("ID").asText()); + assertNotNull(org.get("Roles")); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(1, roles.size()); + final ObjectNode firstRole = (ObjectNode) roles.get(0); + assertEquals("A", firstRole.get("RoleCategory").asText()); + } + + @Test + public void testExpandTwoNavigationPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent,Children"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandAllNavigationPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandAllNavigationPathOfPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandLevel1() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=1)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final TextNode divCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE258", divCode.asText()); + } + + @Test + public void testExpandLevel2() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=2)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertFalse(org.get("Parent") instanceof NullNode); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + final TextNode parentDivCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE258", parentDivCode.asText()); + + assertFalse(parent.get("Parent") instanceof NullNode); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent.get("DivisionCode")); + final TextNode grandparentDivCode = (TextNode) grandParent.get("DivisionCode"); + assertEquals("BE25", grandparentDivCode.asText()); + } + + @Test + public void testExpandLevelMax() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE241',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($levels=max)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertFalse(org.get("Parent") instanceof NullNode); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + final TextNode parentDivCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE24", parentDivCode.asText()); + + assertFalse(parent.get("Parent") instanceof NullNode); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent.get("DivisionCode")); + final TextNode grandparentDivCode = (TextNode) grandParent.get("DivisionCode"); + assertEquals("BE2", grandparentDivCode.asText()); + } + + @Test + public void testExpandAllNavigationPathWithComplex() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles")); + + } + + @Test + public void testExpandCompleteEntitySet2() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "AdministrativeDivisions?$expand=Parent"); + + helper.assertStatus(200); + } + + @Test + public void testExpandViaJoinTable() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('2')?$select=Name1&$expand=SupportEngineers($select=FirstName,LastName)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("SupportEngineers")); + + } + + @Test + public void testExpandViaJoinTable2Levels() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('1')?$select=Name1&$expand=SupportEngineers($select=FirstName,LastName;$expand=SupportedOrganizations)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("SupportEngineers")); + ArrayNode supportOrgs = (ArrayNode) org.get("SupportEngineers").get(0).get("SupportedOrganizations"); + assertNotNull(supportOrgs); + assertEquals(1, supportOrgs.size()); + + supportOrgs = (ArrayNode) org.get("SupportEngineers").get(1).get("SupportedOrganizations"); + assertNotNull(supportOrgs); + assertEquals(2, supportOrgs.size()); + } + + @Test + public void testExpandViaJoinTable1LevelNoSubType() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=LastName&$expand=Teams"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org); + } + + @Test + public void testExpandViaJoinTable1LevelNoMapped() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(1)?$expand=OneToMany"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToMany")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToMany"); + assertEquals(2, oneToMany.size()); + } + + @Test + public void testExpandViaJoinTable1LevelNoMappedHidden() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(2)?$expand=OneToManyHidden"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToManyHidden")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToManyHidden"); + assertEquals(2, oneToMany.size()); + } + + @Test + public void testExpandViaJoinTableComplex() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(1)/Complex?$expand=OneToManyComplex"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToManyComplex")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToManyComplex"); + assertEquals(2, oneToMany.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java new file mode 100644 index 0000000000..36b5409d06 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java @@ -0,0 +1,233 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.UriInfoDouble; + +public class TestJPAQueryBuildSelectionPathList extends TestBase { + + private JPAAbstractJoinQuery cut; + private JPAODataSessionContextAccess context; + private UriInfo uriInfo; + + @Before + public void setup() throws ODataException { + buildUriInfo("BusinessPartners", "BusinessPartner"); + + helper = new TestHelper(emf, PUNIT_NAME); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + createHeaders(); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages), ds, + null); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + } + + private List buildUriInfo(final String esName, final String etName) { + uriInfo = mock(UriInfo.class); + final EdmEntitySet odataEs = mock(EdmEntitySet.class); + final EdmType odataType = mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class); + when(uriInfo.getUriResourceParts()).thenReturn(resources); + when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + when(esResource.getEntitySet()).thenReturn(odataEs); + when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + when(esResource.getType()).thenReturn(odataType); + when(odataEs.getName()).thenReturn(esName); + when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + when(odataType.getName()).thenReturn(etName); + resources.add(esResource); + return resources; + } + + @Test + public void checkSelectAllAsNoSelectionGiven() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(23, act.size()); + } + + @Test + public void checkSelectAllAsStarGiven() throws ODataApplicationException { + + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("*"))); + assertEquals(23, act.size()); + } + + @Test + public void checkSelectPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Country"))); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectAllFromComplexWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address"))); + assertEquals(10, act.size()); + } + + @Test + public void checkSelectKeyNoDuplicates() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("ID"))); + assertEquals(1, act.size()); + } + + @Test + public void checkSelectAllFromNavigationComplexPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble( + "Address/CountryName"))); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectTwoPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Country,ETag"))); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectAllFromComplexAndOnePrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address,ETag"))); + assertEquals(11, act.size()); + } + + @Test + public void checkSelectAllFromNavgateComplexPrimitiveAndOnePrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble( + "Address/CountryName,Country"))); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectNavigationCompex() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty complexResource = mock(UriResourceComplexProperty.class); + final EdmProperty property = mock(EdmProperty.class); + when(complexResource.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(complexResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(5, act.size()); + } + + @Test + public void checkSelectNavigationCompexComplex() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class); + final EdmProperty adminInfoProperty = mock(EdmProperty.class); + when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty); + when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(adminInfoResource); + + final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class); + final EdmProperty createdProperty = mock(EdmProperty.class); + when(createdResource.getProperty()).thenReturn(createdProperty); + when(createdProperty.getName()).thenReturn("Created"); + resourcePath.add(createdResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectNavigationCompexComplexProperty() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class); + final EdmProperty adminInfoProperty = mock(EdmProperty.class); + when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty); + when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(adminInfoResource); + + final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class); + final EdmProperty createdProperty = mock(EdmProperty.class); + when(createdResource.getProperty()).thenReturn(createdProperty); + when(createdProperty.getName()).thenReturn("Created"); + resourcePath.add(createdResource); + + final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty byProperty = mock(EdmProperty.class); + when(byResource.getProperty()).thenReturn(byProperty); + when(byProperty.getName()).thenReturn("By"); + resourcePath.add(byResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectNavigationPropertyValue() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + + final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty byProperty = mock(EdmProperty.class); + when(byResource.getProperty()).thenReturn(byProperty); + when(byProperty.getName()).thenReturn("Country"); + resourcePath.add(byResource); + + final UriResourceValue valueResource = mock(UriResourceValue.class); + when(valueResource.getSegmentValue()).thenReturn(Util.VALUE_RESOURCE.toLowerCase()); + resourcePath.add(valueResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectNavigationCompexWithSelectPrimitive() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty addressResource = mock(UriResourceComplexProperty.class); + final EdmProperty addressProperty = mock(EdmProperty.class); + when(addressResource.getProperty()).thenReturn(addressProperty); + when(addressProperty.getName()).thenReturn("Address"); + resourcePath.add(addressResource); + + SelectOption selOptions = new SelectOptionDouble("CountryName"); + + when(uriInfo.getSelectOption()).thenReturn(selOptions); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java new file mode 100644 index 0000000000..44054f5bcc --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java @@ -0,0 +1,151 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryCollection extends TestBase { + + @Test + public void testSelectPropertyAndCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$select=ID,Comment&orderby=ID"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("ID")); + ArrayNode comment = (ArrayNode) org.get("Comment"); + assertEquals(2, comment.size()); + } + + // @Ignore // See https://issues.apache.org/jira/browse/OLINGO-1231 + @Test + public void testSelectPropertyOfCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')/InhouseAddress?$select=Building"); + helper.assertStatus(200); + + final ArrayNode buildings = helper.getValues(); + assertEquals(2, buildings.size()); + ObjectNode building = (ObjectNode) buildings.get(0); + TextNode number = (TextNode) building.get("Building"); + assertNotNull(number); + } + + @Test + public void testSelectAllWithComplexCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')?$select=*"); + helper.assertStatus(200); + + final ObjectNode person = helper.getValue(); + ArrayNode comment = (ArrayNode) person.get("InhouseAddress"); + assertEquals(2, comment.size()); + } + + @Test + public void testSelectAllWithPrimitiveCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('1')?$select=*"); + helper.assertStatus(200); + + final ObjectNode person = helper.getValue(); + ArrayNode comment = (ArrayNode) person.get("Comment"); + assertEquals(2, comment.size()); + } + + @Test + public void testSelectWithNestedComplexCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('504')?$select=Nested"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ArrayNode nested = (ArrayNode) collection.get("Nested"); + assertEquals(1, nested.size()); + ObjectNode n = (ObjectNode) nested.get(0); + assertEquals(1L, n.get("Number").asLong()); + assertFalse(n.get("Inner") instanceof NullNode); + assertEquals(6L, n.get("Inner").get("Figure3").asLong()); + } + + @Test + public void testSelectComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('502')?$select=Complex"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(32L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(2, complex.get("Address").size()); + assertEquals("DEV", complex.get("Address").get(0).get("TaskID").asText()); + } + + @Test + public void testSelectComplexContainingTwoCollections() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('501')?$select=Complex"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(-1L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(1, complex.get("Address").size()); + assertEquals("MAIN", complex.get("Address").get(0).get("TaskID").asText()); + assertFalse(complex.get("Comment") instanceof NullNode); + assertEquals(1, complex.get("Comment").size()); + assertEquals("This is another test", complex.get("Comment").get(0).asText()); + } + + @Test + public void testSelectAllWithComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Collections('502')"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(32L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(2, complex.get("Address").size()); + assertEquals("DEV", complex.get("Address").get(0).get("TaskID").asText()); + } + + @Test + public void testSelectAllDeepComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CollectionDeeps('501')"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("FirstLevel"); + assertEquals(1, complex.get("LevelID").asInt()); + assertFalse(complex.get("SecondLevel") instanceof NullNode); + ObjectNode second = (ObjectNode) complex.get("SecondLevel"); + ArrayNode address = (ArrayNode) second.get("Address"); + assertEquals(32, address.get(0).get("RoomNumber").asInt()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java new file mode 100644 index 0000000000..b08351c1c8 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java @@ -0,0 +1,162 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.criteria.From; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Root; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAQueryFromClause extends TestBase { + private JPAAbstractJoinQuery cut; + private JPAEntityType jpaEntityType; + + @Before + public void setup() throws ODataException { + final UriInfo uriInfo = Mockito.mock(UriInfo.class); + final EdmEntitySet odataEs = Mockito.mock(EdmEntitySet.class); + final EdmType odataType = Mockito.mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = Mockito.mock(UriResourceEntitySet.class); + Mockito.when(uriInfo.getUriResourceParts()).thenReturn(resources); + Mockito.when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + Mockito.when(esResource.getEntitySet()).thenReturn(odataEs); + Mockito.when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + Mockito.when(esResource.getType()).thenReturn(odataType); + Mockito.when(odataEs.getName()).thenReturn("Organizations"); + Mockito.when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + Mockito.when(odataType.getName()).thenReturn("Organization"); + resources.add(esResource); + + helper = new TestHelper(emf, PUNIT_NAME); + jpaEntityType = helper.getJPAEntityType("Organizations"); + JPAODataSessionContextAccess context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, + TestBase.enumPackages), ds, null); + createHeaders(); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + } + + @Test + public void checkFromListContainsRoot() throws ODataApplicationException { + + Map> act = cut.createFromClause(new ArrayList(1), + new ArrayList(), cut.cq); + assertNotNull(act.get(jpaEntityType.getExternalFQN().getFullQualifiedNameAsString())); + } + + @Test + public void checkFromListOrderByContainsOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + final JPAAssociationPath exp = buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + assertNotNull(act.get(exp.getAlias())); + } + + @Test + public void checkFromListOrderByOuterJoinOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + + @SuppressWarnings("unchecked") + Root root = (Root) act.get(jpaEntityType.getExternalFQN() + .getFullQualifiedNameAsString()); + Set> joins = root.getJoins(); + assertEquals(1, joins.size()); + + for (Join join : joins) { + assertEquals(JoinType.LEFT, join.getJoinType()); + } + } + + @Test + public void checkFromListOrderByOuterJoinOnConditionOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + + @SuppressWarnings("unchecked") + Root root = (Root) act.get(jpaEntityType.getExternalFQN() + .getFullQualifiedNameAsString()); + Set> joins = root.getJoins(); + assertEquals(1, joins.size()); + + for (Join join : joins) { + assertNull(join.getOn()); + } + } + + @Test + public void checkFromListDescriptionAssozationAllFields() throws ODataApplicationException, ODataJPAModelException { + List orderBy = new ArrayList<>(); + List descriptionPathList = new ArrayList<>(); + JPAEntityType entity = helper.getJPAEntityType("Organizations"); + descriptionPathList.add(entity.getPath("Address/CountryName")); + + JPAAttribute attri = helper.getJPAAttribute("Organizations", "address"); + JPAAttribute exp = attri.getStructuredType().getAttribute("countryName"); + + Map> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq); + assertEquals(2, act.size()); + assertNotNull(act.get(exp.getInternalName())); + } + + @Test + public void checkFromListDescriptionAssozationAllFields2() throws ODataApplicationException, ODataJPAModelException { + List orderBy = new ArrayList<>(); + List descriptionPathList = new ArrayList<>(); + JPAEntityType entity = helper.getJPAEntityType("Organizations"); + descriptionPathList.add(entity.getPath("Address/RegionName")); + + JPAAttribute attri = helper.getJPAAttribute("Organizations", "address"); + JPAAttribute exp = attri.getStructuredType().getAttribute("regionName"); + + Map> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq); + assertEquals(2, act.size()); + assertNotNull(act.get(exp.getInternalName())); + } + + private JPAAssociationPath buildRoleAssociationPath(final List orderBy) + throws ODataJPAModelException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + orderBy.add(exp); + return exp; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java new file mode 100644 index 0000000000..49c1c76d97 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java @@ -0,0 +1,81 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Ignore; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryJSONAnnotations extends TestBase { + + @Test + public void testEntityWithMetadataFullContainNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.navigationLink")); + assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText()); + } + + @Test + public void testEntityWithMetadataMinimalWithoutNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=minimal"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNull(org.get("Roles@odata.navigationLink")); + } + + @Test + public void testEntityWithMetadataNoneWithoutNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=none"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNull(org.get("Roles@odata.navigationLink")); + } + + @Test + public void testEntityExpandWithMetadataFullContainNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$expand=Roles&$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.navigationLink")); + assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText()); + } + + @Ignore // See https://issues.apache.org/jira/browse/OLINGO-1248 + @Test + public void testEntityWithMetadataFullContainNavigationLinkOfComplex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + ObjectNode admin = (ObjectNode) org.get("AdministrativeInformation"); + ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User@odata.navigationLink")); + assertEquals("Organizations('3')/AdministrativeInformation/Created/User", created.get("User@odata.navigationLink") + .asText()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java new file mode 100644 index 0000000000..f65c884269 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java @@ -0,0 +1,290 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryNavigation extends TestBase { + + @Test + public void testNavigationOneHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Roles"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testNoNavigationOneEntity() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Third Org.", org.get("Name1").asText()); + } + + @Test + public void testNoNavigationOneEntityCollection() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + ArrayNode comment = (ArrayNode) org.get("Comment"); + assertEquals(2, comment.size()); + } + + @Test + public void testNoNavigationOneEntityNoContent() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1000')"); + helper.assertStatus(404); + } + + @Test + public void testNavigationToComplexValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created"); + helper.assertStatus(200); + + ObjectNode created = helper.getValue(); + assertEquals("99", created.get("By").asText()); + } + + @Test + public void testNavigationOneHopAndOrderBy() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Roles?$orderby=RoleCategory desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("C", orgs.get(0).get("RoleCategory").asText()); + assertEquals("A", orgs.get(2).get("RoleCategory").asText()); + } + + @Test + public void testNavigationOneHopReverse() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='2',RoleCategory='A')/BusinessPartner"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("2", org.get("ID").asText()); + } + + @Test + public void testNavigationViaComplexTypeToComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/AdministrativeInformation"); + helper.assertStatus(200); + + ObjectNode admin = helper.getValue(); + ObjectNode created = (ObjectNode) admin.get("Created"); + assertEquals("99", created.get("By").asText()); + } + + @Test + public void testNavigationViaComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("99", org.get("ID").asText()); + } + + @Test + public void testNavigationViaComplexTypeTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/Address/AdministrativeDivision"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("3166-1", org.get("ParentCodeID").asText()); + } + + @Test + public void testNavigationSelfToOneOneHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("NUTS2", org.get("CodeID").asText()); + assertEquals("BE35", org.get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToOneTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent/Parent"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("NUTS1", org.get("CodeID").asText()); + assertEquals("BE3", org.get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToManyOneHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + assertEquals("NUTS2", orgs.get(0).get("CodeID").asText()); + assertEquals("BE25", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToManyTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + assertEquals("NUTS3", orgs.get(0).get("CodeID").asText()); + assertEquals("BE258", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToOneThreeHopsNoResult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address/AdministrativeDivision/Parent/Parent"); + helper.assertStatus(204); + } + + @Test + public void testNavigationSelfToManyOneHopsNoResult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address/AdministrativeDivision/Children"); + helper.assertStatus(200); + } + + @Test + public void testNavigationJoinTableDefined() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('97')/SupportedOrganizations"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testNavigationJoinTableDefinedSecondHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='98',RoleCategory='X')/BusinessPartner/com.sap.olingo.jpa.Person/SupportedOrganizations"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testNavigationJoinTableMappedBy() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/SupportEngineers"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testNavigationComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/AdministrativeInformation"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + + assertNotNull(org.get("Created")); + assertNotNull(org.get("Updated")); + } + + @Test + public void testNavigationPrimitiveCollectionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/Comment"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals( + "This is another test")); + assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals( + "This is another test")); + } + + @Test + public void testNavigationComplexCollectionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/InhouseAddress"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + } + + @Test + public void testNavigationComplexCollectionPropertyEmptyReult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('98')/InhouseAddress"); + helper.assertStatus(200); + } + + @Test + public void testNavigationPrimitiveCollectionPropertyTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')/Organization/Comment"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals( + "This is another test")); + assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals( + "This is another test")); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java new file mode 100644 index 0000000000..8e3b6defce --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java @@ -0,0 +1,52 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryNavigationCount extends TestBase { + + @Test + public void testEntitySetCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations/$count"); + assertEquals(200, helper.getStatus()); + + assertEquals("10", helper.getRawResult()); + } + + @Test + public void testEntityNavigateCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Roles/$count"); + assertEquals(200, helper.getStatus()); + + assertEquals("3", helper.getRawResult()); + } + + @Test + public void testEntitySetCountWithFilterOn() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations/$count?$filter=Address/HouseNumber gt '30'"); + + assertEquals(200, helper.getStatus()); + assertEquals("7", helper.getRawResult()); + } + + @Test + public void testEntitySetCountWithFilterOnDescription() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons/$count?$filter=LocationName eq 'Deutschland'"); + + assertEquals(200, helper.getStatus()); + assertEquals("2", helper.getRawResult()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java new file mode 100644 index 0000000000..3caca51d56 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java @@ -0,0 +1,174 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryOrderByClause extends TestBase { + + @Test + public void testOrderByOneProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Name1"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("Eighth Org.", orgs.get(0).get("Name1").asText()); + assertEquals("Third Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderByOneComplexPropertyAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Address/Region"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-CA", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-UT", orgs.get(9).get("Address").get("Region").asText()); + } + + @Test + public void testOrderByOneComplexPropertyDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Address/Region desc"); + if (helper.getStatus() != 200) + System.out.println(helper.getRawResult()); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + } + + @Test + public void testOrderByTwoPropertiesDescAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Address/Region desc,Name1 asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("Third Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderByTwoPropertiesDescDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Address/Region desc,Name1 desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("First Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderBy$CountDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Roles/$count desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(0).get("ID").asText()); + assertEquals("2", orgs.get(1).get("ID").asText()); + } + + @Test + public void testOrderBy$CountAndSelectAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID,Name1,Name2,Address/CountryName&$orderby=Roles/$count asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(9).get("ID").asText()); + assertEquals("2", orgs.get(8).get("ID").asText()); + } + + @Test + public void testCollcetionOrderBy$CountAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count asc"); + + helper.assertStatus(200); + ArrayNode deeps = helper.getValues(); + assertEquals("501", deeps.get(0).get("ID").asText()); + assertEquals("502", deeps.get(1).get("ID").asText()); + } + + @Test + public void testCollcetionOrderBy$CountDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count desc"); + + helper.assertStatus(200); + ArrayNode deeps = helper.getValues(); + assertEquals("502", deeps.get(0).get("ID").asText()); + assertEquals("501", deeps.get(1).get("ID").asText()); + } + + @Test + public void testOrderBy$CountAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Roles/$count asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(9).get("ID").asText()); + assertEquals("2", orgs.get(8).get("ID").asText()); + } + + @Test + public void testOrderBy$CountDescComplexPropertyAcs() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Roles/$count desc,Address/Region desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(0).get("ID").asText()); + assertEquals("2", orgs.get(1).get("ID").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("6", orgs.get(9).get("ID").asText()); + } + + @Test + public void testOrderByAndFilter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodeID eq 'NUTS' or CodeID eq '3166-1'&$orderby=CountryCode desc"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + assertEquals("USA", orgs.get(0).get("CountryCode").asText()); + } + + @Test + public void testOrderByNavigationOneHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Roles?$orderby=RoleCategory desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("C", orgs.get(0).get("RoleCategory").asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java new file mode 100644 index 0000000000..a964c0f23f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java @@ -0,0 +1,176 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.Ignore; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.testmodel.ImageLoader; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQuerySelectByPath extends TestBase { + + @Test + public void testNavigationToOwnPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Name1"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Third Org.", org.get("value").asText()); + } + + @Test + public void testNavigationToOwnEmptyPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/BirthDay"); + helper.assertStatus(204); + } + + @Test + public void testNavigationToOwnPrimitivePropertyEntityDoesNotExistEntity() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('9999')/BirthDay"); + helper.assertStatus(404); + } + + @Test + public void testNavigationToOwnPrimitiveDescriptionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/LocationName"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Vereinigte Staaten von Amerika", org.get("value").asText()); + } + + @Test + public void testNavigationToComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("USA", org.get("Country").asText()); + } + + @Test + public void testNavigationToNotExistingComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('97')/CommunicationData"); + helper.assertStatus(204); + } + + @Test + public void testNavigationToNestedComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/AdministrativeInformation/Created"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("98", org.get("By").asText()); + } + + @Test + public void testNavigationViaComplexAndNaviPropertyToPrimitive() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/FirstName"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Max", org.get("value").asText()); + } + + @Test + public void testNavigationToComplexPropertySelect() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/Address?$select=Country,Region"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals(3, org.size()); // Node "@odata.context" is also counted + assertEquals("USA", org.get("Country").asText()); + assertEquals("US-UT", org.get("Region").asText()); + } + + @Test + public void testNavigationToComplexPropertyExpand() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("USA", org.get("Country").asText()); + } + + @Test + public void testNavigationToComplexPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address/Region"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + System.out.println(org); + assertEquals("US-UT", org.get("value").asText()); + assertTrue(org.get("@odata.context").asText().endsWith("$metadata#Organizations/Address/Region")); + } + + @Ignore // TODO check image load + @Test + public void testNavigationToStreamValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "PersonImages('99')/$value"); + helper.assertStatus(200); + + byte[] act = helper.getBinaryResult(); + assertEquals(93316, act.length, 0); + } + + @Ignore // TODO check image load + @Test + public void testNavigationToStreamValueVia() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/Image/$value"); + helper.assertStatus(200); + + byte[] act = helper.getBinaryResult(); + assertEquals(93316, act.length, 0); + } + + @Ignore // TODO check image load + @Test + public void testNavigationToComplexAttributeValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/AdministrativeInformation/Created/By/$value"); + helper.assertStatus(200); + + String act = helper.getRawResult(); + assertEquals("98", act); + } + + @Ignore // TODO check image load + @Test + public void testNavigationToPrimitiveAttributeValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/ID/$value"); + helper.assertStatus(200); + + String act = helper.getRawResult(); + assertEquals("4", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java new file mode 100644 index 0000000000..337072e25a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java @@ -0,0 +1,465 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.Selection; + +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.EdmPropertyDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandOptionDouble; +import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble; +import com.sap.olingo.jpa.processor.core.util.TestQueryBase; +import com.sap.olingo.jpa.processor.core.util.UriInfoDouble; +import com.sap.olingo.jpa.processor.core.util.UriResourceNavigationDouble; +import com.sap.olingo.jpa.processor.core.util.UriResourcePropertyDouble; + +public class TestJPAQuerySelectClause extends TestQueryBase { + + @Test + public void checkSelectAll() throws ODataApplicationException, ODataJPAModelException { + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("*"))), root); + assertEquals(jpaEntityType.getPathList().size(), selectClause.size()); + + } + + @Test + public void checkSelectAllWithSelectionNull() throws ODataApplicationException, ODataJPAModelException { + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(new UriInfoDouble( + null)), root); + + assertEquals(jpaEntityType.getPathList().size(), selectClause.size()); + } + + @Test + public void checkSelectExpandViaIgnoredProperties() throws ODataApplicationException, ODataJPAModelException { + // Organizations('3')/Address?$expand=AdministrativeDivision + fillJoinTable(root); + List expItems = new ArrayList<>(); + EdmEntityType startEntity = new EdmEntityTypeDouble(nameBuilder, "Organization"); + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "AdministrativeDivision"); + + ExpandOption expOps = new ExpandOptionDouble("AdministrativeDivision", expItems); + expItems.add(new ExpandItemDouble(targetEntity)); + List startResources = new ArrayList<>(); + UriInfoDouble uriInfo = new UriInfoDouble(null); + uriInfo.setExpandOpts(expOps); + uriInfo.setUriResources(startResources); + + startResources.add(new UriResourceNavigationDouble(startEntity)); + startResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("Address"))); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + + assertContains(selectClause, "Address/RegionCodeID"); + } + + @Test + public void checkSelectOnePropertyCreatedAt() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("CreationDateTime"))), root); + assertEquals(2, selectClause.size()); + assertContains(selectClause, "CreationDateTime"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectOnePropertyID() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("ID"))), root); + assertEquals(1, selectClause.size()); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectOnePropertyPartKey() throws ODataException { + jpaEntityType = helper.getJPAEntityType("AdministrativeDivisionDescriptions"); + buildUriInfo("AdministrativeDivisionDescriptions", "AdministrativeDivisionDescription"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble((new SelectOptionDouble("CodePublisher")))), root); + assertEquals(4, selectClause.size()); + assertContains(selectClause, "CodePublisher"); + assertContains(selectClause, "CodeID"); + assertContains(selectClause, "DivisionCode"); + assertContains(selectClause, "Language"); + } + + @Test + public void checkSelectPropertyTypeCreatedAt() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))), root); + + assertEquals(3, selectClause.size()); + assertContains(selectClause, "CreationDateTime"); + assertContains(selectClause, "Type"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectSupertypePropertyTypeName2() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + buildUriInfo("Organizations", "Organization"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Type,Name2"))), root); + assertContains(selectClause, "Name2"); + assertContains(selectClause, "Type"); + assertContains(selectClause, "ID"); + assertEquals(3, selectClause.size()); + } + + @Test + public void checkSelectCompleteComplexType() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address"))), root); + assertEquals(TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + 1, selectClause.size()); + } + + @Test + public void checkSelectCompleteNestedComplexTypeLowLevel() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation/Created"))), root); + assertEquals(3, selectClause.size()); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "AdministrativeInformation/Created/At"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectCompleteNestedComplexTypeHighLevel() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation"))), root); + assertEquals(5, selectClause.size()); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "AdministrativeInformation/Created/At"); + assertContains(selectClause, "AdministrativeInformation/Updated/By"); + assertContains(selectClause, "AdministrativeInformation/Updated/At"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectElementOfComplexType() throws ODataException { + // Organizations$select=Address/Country + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + // SELECT c.address.geocode FROM Company c WHERE c.name = 'Random House' + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address/Country"))), root); + assertContains(selectClause, "Address/Country"); + assertContains(selectClause, "ID"); + assertEquals(2, selectClause.size()); + } + + @Test + public void checkSelectTextJoinSingleAttribute() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address/CountryName"))), root); + assertContains(selectClause, "Address/CountryName"); + assertContains(selectClause, "ID"); + assertEquals(2, selectClause.size()); + } + + @Test + public void checkSelectTextJoinCompextType() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address"))), root); + assertEquals(TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + 1, selectClause.size()); + assertContains(selectClause, "Address/CountryName"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectStreamValueStatic() throws ODataException { + jpaEntityType = helper.getJPAEntityType("PersonImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("PersonImages", "PersonImage"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address")); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "Image"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectStreamValueDynamic() throws ODataException { + jpaEntityType = helper.getJPAEntityType("OrganizationImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("OrganizationImages", "OrganizationImage"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address")); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "Image"); + assertContains(selectClause, "MimeType"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectPropertyValue() throws ODataException { + jpaEntityType = helper.getJPAEntityType("PersonImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("PersonImages", "PersonImage"); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(null); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + // PersonImages('99')/AdministrativeInformation/Created/By/$value + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("AdministrativeInformation"))); + uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("Created"))); + uriResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("By"))); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "ID"); + } + + private void assertContains(List> selectClause, String alias) { + for (Selection selection : selectClause) { + if (selection.getAlias().equals(alias)) + return; + } + fail(alias + " not found"); + } + + private class UriResourceValueDouble implements UriResourceValue { + + @Override + public UriResourceKind getKind() { + return UriResourceKind.value; + } + + @Override + public String getSegmentValue() { + return null; + } + } + + private class UriResourceComplexPropertyDouble implements UriResourceComplexProperty { + private final EdmProperty property; + + public UriResourceComplexPropertyDouble(EdmProperty property) { + super(); + this.property = property; + } + + @Override + public EdmProperty getProperty() { + return property; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexType() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexTypeFilter() { + fail(); + return null; + } + + } + + private class UriResourceEntitySetDouble implements UriResourceEntitySet { + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmEntitySet getEntitySet() { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityType() { + fail(); + return null; + } + + @Override + public List getKeyPredicates() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnCollection() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnEntry() { + fail(); + return null; + } + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java new file mode 100644 index 0000000000..72422549c5 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java @@ -0,0 +1,374 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.sql.Date; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Predicate.BooleanOperator; + +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.eclipse.persistence.internal.jpa.querydef.CompoundExpressionImpl; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair; +import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.JPAEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.TestQueryBase; + +public class TestJPAQueryWithProtection extends TestQueryBase { + private JPAODataSessionContextAccess contextSpy; + private JPAServiceDocument sdSpy; + private EdmType odataType; + private List attributes; + private Set claimNames; + private List pathList; + private JPAEntityType etSpy; + private List protections; + + @Override + @Before + public void setup() throws ODataException { + super.setup(); + contextSpy = Mockito.spy(context); + JPAEdmProvider providerSpy = Mockito.spy(context.getEdmProvider()); + sdSpy = Mockito.spy(context.getEdmProvider().getServiceDocument()); + when(contextSpy.getEdmProvider()).thenReturn(providerSpy); + when(providerSpy.getServiceDocument()).thenReturn(sdSpy); + + } + + @Test + public void testRestrictOnePropertyOneValue() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(3, bupa.size()); + } + + @Test + public void testRestrictOnePropertyTwoValues() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(16, bupa.size()); + } + + @Test + public void testRestrictOnePropertyNoProvider() throws IOException, ODataException { + JPAODataClaimsProvider claims = null; + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(403); + } + + @Test + public void testRestrictOnePropertyNoValue() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(403); + } + + @Test + public void testRestrictOnePropertyBetweenValues() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin", "Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(16, bupa.size()); + } + + @Test + public void testRestrictOnePropertyOneValueWithNavigationToRoles() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds('99')/Roles", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(2, bupa.size()); + } + + @Test + public void testRestrictComplexOnePropertyOnValue() throws ODataException { + prepareTest(); + prepareComplexAttributeCreateUser("UserId"); + + claimNames.add("UserId"); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath("UserId"); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEqual(act); + } + + @Test + public void testRestrictComplexOnePropertyUpperLowerValues() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin", "Willi")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath("UserId"); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertBetween(act); + } + + @Test + public void testRestrictComplexOnePropertyTwoValues() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin")); + claims.add(claimName, new JPAClaimsPair<>("Willi")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.OR, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + @Test + public void testRestrictComplexOnePropertyOneValuesDate() throws ODataException { + final String claimName = "CreationDate"; + prepareTest(); + prepareComplexAttributeDate(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01"))); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEqual(act); + } + + @Test + public void testRestrictComplexOnePropertyUpperLowerValuesDate() throws ODataException { + final String claimName = "CreationDate"; + prepareTest(); + prepareComplexAttributeDate(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01"), Date.valueOf("9999-12-30"))); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertBetween(act); + } + + @Test + public void testRestrictComplexTwoPropertyOneValuesOperatorAND() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + prepareComplexAttributeUpdateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.AND, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + @Test + public void testRestrictTwoPropertiesOneValuesOperatorAND() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + prepareComplexAttributeUpdateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.AND, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + private void assertBetween(Expression act) { + assertExpression(act, "between", 3); + } + + private void assertEqual(Expression act) { + assertExpression(act, "equal", 2); + } + + private void assertExpression(Expression act, String operator, int size) { + assertNotNull(act); + final List> actChildren = ((CompoundExpressionImpl) act).getChildExpressions(); + assertEquals(size, actChildren.size()); + assertEquals(operator, ((CompoundExpressionImpl) act).getOperation()); + assertEquals("Path", actChildren.get(0).getClass().getInterfaces()[0].getSimpleName()); + } + + private void prepareComplexAttributeUser(final String claimName, final String pathName, + final String intermediateElement) throws ODataJPAModelException { + + final JPAProtectionInfo protection = Mockito.mock(JPAProtectionInfo.class); + protections.add(protection); + + final String path = pathName; + pathList.add(path); + final JPAPath jpaPath = Mockito.mock(JPAPath.class); + final JPAElement adminAttri = Mockito.mock(JPAElement.class); + final JPAElement complexAttri = Mockito.mock(JPAElement.class); + final JPAAttribute simpleAttri = Mockito.mock(JPAAttribute.class); + final List pathElements = Arrays.asList(new JPAElement[] { adminAttri, complexAttri, simpleAttri }); + doReturn(pathElements).when(jpaPath).getPath(); + doReturn("administrativeInformation").when(adminAttri).getInternalName(); + doReturn(intermediateElement).when(complexAttri).getInternalName(); + doReturn("by").when(simpleAttri).getInternalName(); + doReturn(String.class).when(simpleAttri).getType(); + doReturn(simpleAttri).when(jpaPath).getLeaf(); + doReturn(jpaPath).when(etSpy).getPath(path); + + doReturn(simpleAttri).when(protection).getAttribute(); + doReturn(jpaPath).when(protection).getPath(); + doReturn(claimName).when(protection).getClaimName(); + } + + private void prepareComplexAttributeCreateUser(final String claimName) throws ODataJPAModelException { + prepareComplexAttributeUser(claimName, "AdministrativeInformation/Created/By", "created"); + } + + private void prepareComplexAttributeUpdateUser(final String claimName) throws ODataJPAModelException { + prepareComplexAttributeUser(claimName, "AdministrativeInformation/Updated/By", "updated"); + } + + private void prepareComplexAttributeDate(final String claimName) throws ODataJPAModelException { + + final JPAProtectionInfo protection = Mockito.mock(JPAProtectionInfo.class); + protections.add(protection); + + final String path = "AdministrativeInformation/Created/At"; + pathList.add(path); + final JPAPath jpaPath = Mockito.mock(JPAPath.class); + final JPAElement adminAttri = Mockito.mock(JPAElement.class); + final JPAElement complexAttri = Mockito.mock(JPAElement.class); + final JPAAttribute simpleAttri = Mockito.mock(JPAAttribute.class); + final List pathElements = Arrays.asList(new JPAElement[] { adminAttri, complexAttri, simpleAttri }); + doReturn(pathElements).when(jpaPath).getPath(); + doReturn("administrativeInformation").when(adminAttri).getInternalName(); + doReturn("created").when(complexAttri).getInternalName(); + doReturn("at").when(simpleAttri).getInternalName(); + doReturn(Date.class).when(simpleAttri).getType(); + doReturn(simpleAttri).when(jpaPath).getLeaf(); + doReturn(jpaPath).when(etSpy).getPath(path); + + doReturn(simpleAttri).when(protection).getAttribute(); + doReturn(jpaPath).when(protection).getPath(); + doReturn(claimName).when(protection).getClaimName(); + + } + + private void prepareTest() throws ODataException { + buildUriInfo("BusinessPartnerProtecteds", "BusinessPartnerProtected"); + odataType = ((UriResourceEntitySet) uriInfo.getUriResourceParts().get(0)).getType(); + attributes = new ArrayList<>(); + claimNames = new HashSet<>(); + pathList = new ArrayList<>(); + protections = new ArrayList<>(); + + etSpy = Mockito.spy(new JPAEntityTypeDouble(sdSpy.getEntity("BusinessPartnerProtecteds"))); + doReturn(attributes).when(etSpy).getAttributes(); + doReturn(protections).when(etSpy).getProtections(); + doReturn(etSpy).when(sdSpy).getEntity("BusinessPartnerProtecteds"); + doReturn(etSpy).when(sdSpy).getEntity(odataType); + cut = new JPAJoinQuery(null, contextSpy, emf.createEntityManager(), headers, uriInfo); + cut.createFromClause(new ArrayList(1), new ArrayList(), cut.cq); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java new file mode 100644 index 0000000000..683fdc6708 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java @@ -0,0 +1,311 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.queryoption.OrderByItem; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SelectItem; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.api.JPAODataPage; +import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAServerDrivenPaging extends TestBase { + @Test + public void testReturnsNotImplementedIfPagingProviderNotAvailable() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz"); + helper.assertStatus(501); + } + + @Test + public void testReturnsGoneIfPagingProviderRetunrsNullForSkiptoken() throws IOException, ODataException { + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getNextPage("xyz")).thenReturn(null); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider); + helper.assertStatus(410); + + } + + @Test + public void testReturnsFullResultIfProviderDoesNotReturnPage() throws IOException, ODataException { + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenReturn(null); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations", provider); + helper.assertStatus(200); + assertEquals(10, helper.getValues().size()); + } + + @Test + public void testReturnsPartResultIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + } + + @Test + public void testReturnsNextLinkIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + assertEquals("Organizations?$skiptoken='Hugo'", helper.getValue().get("@odata.nextLink").asText()); + } + + @Test + public void testReturnsNextLinkNotAStringIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, new Integer(123456789))); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + assertEquals("Organizations?$skiptoken=123456789", helper.getValue().get("@odata.nextLink").asText()); + } + + @Test + public void testReturnsNextPagesRespectingFilter() throws IOException, ODataException { + final UriInfo uriInfo = buildUriInfo(); + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getNextPage("xyz")).thenReturn(new JPAODataPage(uriInfo, 5, 5, null)); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + ObjectNode org = (ObjectNode) helper.getValues().get(4); + assertEquals("1", org.get("ID").asText()); + } + + @Test + public void testEntityManagerProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), any(), any(), isNotNull()); + } + + @Test + public void testCountQueryProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), any(), isNotNull(), any()); + } + + @Test + public void testMaxPageSizeHeaderProvided() throws IOException, ODataException { + + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=50"); + headers.put("Prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), isNotNull(), any(), any()); + } + + @Test + public void testMaxPageSizeHeaderProvidedInLowerCase() throws IOException, ODataException { + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=50"); + headers.put("prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), isNotNull(), any(), any()); + } + + @Test + public void testUriInfoProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(isNotNull(), any(), any(), any()); + } + + @Test + public void testMaxPageSiteHeaderNotANumber() throws IOException, ODataException { + + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=Hugo"); + headers.put("Prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(400); + + } + + @Test + public void testSelectSubsetOfFields() throws IOException, ODataException { + final UriInfo uriInfo = buildUriInfo(); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + final SelectOption selOpt = mock(SelectOption.class); + final List selItems = new ArrayList<>(); + final SelectItem selItem = mock(SelectItem.class); + + when(uriInfo.getSelectOption()).thenReturn(selOpt); + when(selOpt.getKind()).thenReturn(SystemQueryOptionKind.SELECT); + when(selOpt.getSelectItems()).thenReturn(selItems); + selItems.add(selItem); + + final UriInfoResource selectPath = mock(UriInfoResource.class); + final List selectPathItems = new ArrayList<>(1); + final UriResourcePrimitiveProperty selectResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty selectProperty = mock(EdmProperty.class); + selectPathItems.add(selectResource); + when(selItem.getResourcePath()).thenReturn(selectPath); + when(selectPath.getUriResourceParts()).thenReturn(selectPathItems); + when(selectResource.getSegmentValue()).thenReturn("ID"); + when(selectResource.getProperty()).thenReturn(selectProperty); + when(selectProperty.getName()).thenReturn("ID"); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + when(provider.getNextPage("'Hugo'")).thenReturn(new JPAODataPage(uriInfo, 5, 5, "Willi")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc&$select=ID", + provider); + helper.assertStatus(200); + assertNull(helper.getValues().get(0).get("Country")); + IntegrationTestHelper act = new IntegrationTestHelper(emf, "Organizations?$skiptoken='Hugo'", + provider); + act.assertStatus(200); + assertEquals(5, act.getValues().size()); + assertNull(act.getValues().get(0).get("Country")); + + } + + private UriInfo buildUriInfo() throws EdmPrimitiveTypeException { + final UriInfo uriInfo = mock(UriInfo.class); + final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class); + final EdmEntitySet es = mock(EdmEntitySet.class); + final EdmEntityType et = mock(EdmEntityType.class); + final EdmType type = mock(EdmType.class); + final OrderByOption order = mock(OrderByOption.class); + final OrderByItem orderItem = mock(OrderByItem.class); + final Member orderExpression = mock(Member.class); + final UriInfoResource orderResourcePath = mock(UriInfoResource.class); + final UriResourcePrimitiveProperty orderResourcePathItem = mock(UriResourcePrimitiveProperty.class); + final EdmProperty orderProperty = mock(EdmProperty.class); + final List orderItems = new ArrayList<>(); + final List orderResourcePathItems = new ArrayList<>(); + + final EdmProperty propertyID = mock(EdmProperty.class); // type.getStructuralProperty(propertyName); + final EdmProperty propertyCountry = mock(EdmProperty.class); + final EdmPrimitiveType propertyType = mock(EdmPrimitiveType.class); + + orderItems.add(orderItem); + orderResourcePathItems.add(orderResourcePathItem); + when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet); + when(uriEs.getEntitySet()).thenReturn(es); + when(uriEs.getType()).thenReturn(type); + when(uriEs.isCollection()).thenReturn(true); + when(es.getName()).thenReturn("Organizations"); + when(es.getEntityType()).thenReturn(et); + when(type.getNamespace()).thenReturn("com.sap.olingo.jpa"); + when(type.getName()).thenReturn("Organization"); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName("com.sap.olingo.jpa", "Organization")); + when(et.getPropertyNames()).thenReturn(Arrays.asList("ID", "Country")); + when(et.getStructuralProperty("ID")).thenReturn(propertyID); + when(et.getStructuralProperty("Country")).thenReturn(propertyCountry); + + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.isPrimitive()).thenReturn(true); + when(propertyID.getType()).thenReturn(propertyType); + when(propertyCountry.getName()).thenReturn("Country"); + when(propertyCountry.isPrimitive()).thenReturn(true); + when(propertyCountry.getType()).thenReturn(propertyType); + when(propertyType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + when(propertyType.valueToString(any(), any(), any(), any(), any(), any())).thenAnswer(i -> i.getArguments()[0] + .toString()); + + when(order.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY); + when(orderItem.isDescending()).thenReturn(true); + when(orderItem.getExpression()).thenReturn(orderExpression); + when(orderExpression.getResourcePath()).thenReturn(orderResourcePath); + when(orderResourcePath.getUriResourceParts()).thenReturn(orderResourcePathItems); + when(orderResourcePathItem.getProperty()).thenReturn(orderProperty); + when(orderProperty.getName()).thenReturn("ID"); + when(order.getOrders()).thenReturn(orderItems); + final List resourceParts = new ArrayList<>(); + resourceParts.add(uriEs); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriInfo.getOrderByOption()).thenReturn(order); + return uriInfo; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java new file mode 100644 index 0000000000..d74660dbc6 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java @@ -0,0 +1,248 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static com.sap.olingo.jpa.processor.core.query.JPAExpandQueryResult.ROOT_RESULT_KEY; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPATupleChildConverter extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPATupleChildConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + private Map keyPredicates; + private HashMap> queryResult = new HashMap<>(1); + + @Before + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList<>(); + + queryResult.put(ROOT_RESULT_KEY, jpaQueryResult); + uriHelper = new UriHelperDouble(); + keyPredicates = new HashMap<>(); + uriHelper.setKeyPredicates(keyPredicates, "ID"); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "Organization")); + + } + + @Test + public void checkConvertsEmptyResult() throws ODataApplicationException, ODataJPAModelException { + + assertNotNull(cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations")))); + } + + @Test + public void checkConvertsOneResultOneElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result = new HashMap<>(); + + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + } + + @Test + public void checkConvertsOneResultOneKey() throws ODataApplicationException, ODataJPAModelException { + HashMap result = new HashMap<>(); + keyPredicates.put("1", "'1'"); + + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("Organizations" + "('1')", act.getEntities().get(0).getId().getPath()); + } + + @Test + public void checkConvertsTwoResultsOneElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + result = new HashMap<>(); + result.put("ID", new String("5")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + keyPredicates.put("5", "Organizations('5')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(2, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + assertEquals("5", act.getEntities().get(1).getProperty("ID").getValue().toString()); + } + + @Test + public void checkConvertsOneResultsTwoElements() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", new String("1")); + result.put("Name1", new String("Willi")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + assertEquals("Willi", act.getEntities().get(0).getProperty("Name1").getValue().toString()); + } + + @Test + public void checkConvertsOneResultsOneComplexElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", "1"); + result.put("Address/CityName", "Test City"); + result.put("Address/Country", "GB"); + result.put("Address/PostalCode", "ZE1 3AA"); + result.put("Address/StreetName", "Test Road"); + result.put("Address/HouseNumber", "123"); + result.put("Address/POBox", "155"); + result.put("Address/Region", "GB-12"); + result.put("Address/CountryName", "Willi"); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + + assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("Address").getValueType()); + ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("Address").getValue(); + assertEquals(NO_POSTAL_ADDRESS_FIELDS, value.getValue().size()); + } + + @Test + public void checkConvertsOneResultsOneNestedComplexElement() throws ODataApplicationException, + ODataJPAModelException { + HashMap result; + +// AdministrativeInformation adminInfo = new AdministrativeInformation(); +// adminInfo.setCreated(new ChangeInformation("Joe Doe", Timestamp.valueOf("2016-01-22 12:25:23"))); +// adminInfo.setUpdated(new ChangeInformation("Joe Doe", Timestamp.valueOf("2016-01-24 14:29:45"))); + result = new HashMap<>(); + result.put("ID", "1"); + result.put("AdministrativeInformation/Created/By", "Joe Doe"); + result.put("AdministrativeInformation/Created/At", "2016-01-22 12:25:23"); + result.put("AdministrativeInformation/Updated/By", "Joe Doe"); + result.put("AdministrativeInformation/Updated/At", "2016-01-24 14:29:45"); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + // Check first level + assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("AdministrativeInformation").getValueType()); + ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("AdministrativeInformation").getValue(); + assertEquals(NO_ADMIN_INFO_FIELDS, value.getValue().size()); + // Check second level + assertEquals(ValueType.COMPLEX, value.getValue().get(0).getValueType()); + } + + @Test + public void checkConvertsOneResultsOneElementOfComplexElement() throws ODataApplicationException, + ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", "1"); + result.put("Address/Region", new String("CA")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("CA", ((ComplexValue) act.getEntities().get(0).getProperty("Address").getValue()).getValue().get(0) + .getValue().toString()); + } + + @Test + public void checkConvertMediaStreamStaticMime() throws ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + HashMap> result = new HashMap<>(1); + result.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "PersonImage")); + + HashMap entityResult; + byte[] image = { -119, 10 }; + entityResult = new HashMap<>(); + entityResult.put("ID", "1"); + entityResult.put("Image", image); + jpaQueryResult.add(new TupleDouble(entityResult)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType( + "PersonImages"))).get(ROOT_RESULT_KEY); + + assertEquals("image/png", act.getEntities().get(0).getMediaContentType()); + } + + @Test + public void checkConvertMediaStreamDynamicMime() throws ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + HashMap> result = new HashMap<>(1); + result.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "OrganizationImage")); + + HashMap entityResult; + byte[] image = { -119, 10 }; + entityResult = new HashMap<>(); + entityResult.put("ID", "9"); + entityResult.put("Image", image); + entityResult.put("MimeType", "image/svg+xml"); + jpaQueryResult.add(new TupleDouble(entityResult)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType( + "OrganizationImages"))).get(ROOT_RESULT_KEY); + assertEquals("image/svg+xml", act.getEntities().get(0).getMediaContentType()); + assertEquals(2, act.getEntities().get(0).getProperties().size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java new file mode 100644 index 0000000000..d109ed7487 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java @@ -0,0 +1,111 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static com.sap.olingo.jpa.processor.core.query.JPAExpandQueryResult.ROOT_RESULT_KEY; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.Before; +import org.junit.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPATupleChildConverterCompoundKey extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPATupleChildConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + private Map keyPredicates; + + @Before + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList<>(); + uriHelper = new UriHelperDouble(); + keyPredicates = new HashMap<>(); + } + + @Test + public void checkConvertsOneResultsTwoKeys() throws ODataApplicationException, ODataJPAModelException { + // .../BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C') + + HashMap> resultContainer = new HashMap<>(1); + resultContainer.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "BusinessPartnerRole")); + + HashMap result; + + result = new HashMap<>(); + result.put("BusinessPartnerID", new String("3")); + result.put("RoleCategory", new String("C")); + jpaQueryResult.add(new TupleDouble(result)); + + uriHelper.setKeyPredicates(keyPredicates, "BusinessPartnerID"); + keyPredicates.put("3", "BusinessPartnerID='3',RoleCategory='C'"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType( + "BusinessPartnerRoles"))).get(ROOT_RESULT_KEY); + + assertEquals(1, act.getEntities().size()); + assertEquals("3", act.getEntities().get(0).getProperty("BusinessPartnerID").getValue().toString()); + assertEquals("C", act.getEntities().get(0).getProperty("RoleCategory").getValue().toString()); + + assertEquals("BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C')", + act.getEntities().get(0).getId().getPath()); + } + + @Test // EmbeddedIds are resolved to elementary key properties + public void checkConvertsOneResultsEmbeddedKey() throws ODataApplicationException, ODataJPAModelException { + // .../AdministrativeDivisionDescriptions(CodePublisher='ISO', CodeID='3166-1', DivisionCode='DEU',Language='en') + + HashMap> resultContainer = new HashMap<>(1); + resultContainer.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "AdministrativeDivisionDescription")); + + AdministrativeDivisionDescriptionKey country = new AdministrativeDivisionDescriptionKey(); + country.setLanguage("en"); + + HashMap result; + + result = new HashMap<>(); + result.put("CodePublisher", new String("ISO")); + result.put("CodeID", new String("3166-1")); + result.put("DivisionCode", new String("DEU")); + result.put("Language", new String("en")); + jpaQueryResult.add(new TupleDouble(result)); + uriHelper.setKeyPredicates(keyPredicates, "DivisionCode"); + keyPredicates.put("DEU", "CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en'"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType( + "AdministrativeDivisionDescriptions"))).get(ROOT_RESULT_KEY); + + assertEquals(1, act.getEntities().size()); + assertEquals("ISO", act.getEntities().get(0).getProperty("CodePublisher").getValue().toString()); + assertEquals("en", act.getEntities().get(0).getProperty("Language").getValue().toString()); + + assertEquals( + "AdministrativeDivisionDescriptions(CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en')", + act.getEntities().get(0).getId().getPath()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java new file mode 100644 index 0000000000..f43c87e0d4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java @@ -0,0 +1,78 @@ +package com.sap.olingo.jpa.processor.core.util; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmBindingTarget; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmMapping; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.EdmTerm; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class EdmEntitySetDouble implements EdmEntitySet { + private final String name; + private final EdmEntityType type; + // private final JPAEdmNameBuilder nameBuilder; + + public EdmEntitySetDouble(final JPAEdmNameBuilder nameBuilder, final String name) { + super(); + this.name = name; + this.type = new EdmEntityTypeDouble(nameBuilder, name.substring(0, name.length() - 1)); + // this.nameBuilder = nameBuilder; + } + + @Override + public String getTitle() { + return null; + } + + @Override + public EdmBindingTarget getRelatedBindingTarget(final String path) { + return null; + } + + @Override + public List getNavigationPropertyBindings() { + return null; + } + + @Override + public EdmEntityContainer getEntityContainer() { + return null; + } + + @Override + public EdmEntityType getEntityType() { + return type; + } + + @Override + public String getName() { + return name; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + return null; + } + + @Override + public List getAnnotations() { + return null; + } + + @Override + public boolean isIncludeInServiceDocument() { + return false; + } + + @Override + public EdmMapping getMapping() { + org.junit.Assert.fail(); + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java new file mode 100644 index 0000000000..48562479ac --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java @@ -0,0 +1,141 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmElement; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class EdmEntityTypeDouble implements EdmEntityType { + + private final String name; + private final JPAEdmNameBuilder nameBuilder; + + public EdmEntityTypeDouble(final JPAEdmNameBuilder nameBuilder, final String name) { + this.name = name; + this.nameBuilder = nameBuilder; + } + + @Override + public EdmElement getProperty(final String name) { + fail(); + return null; + } + + @Override + public List getPropertyNames() { + fail(); + return null; + } + + @Override + public EdmProperty getStructuralProperty(final String name) { + fail(); + return null; + } + + @Override + public EdmNavigationProperty getNavigationProperty(final String name) { + fail(); + return null; + } + + @Override + public List getNavigationPropertyNames() { + fail(); + return null; + } + + @Override + public boolean compatibleTo(final EdmType targetType) { + fail(); + return false; + } + + @Override + public boolean isOpenType() { + fail(); + return false; + } + + @Override + public boolean isAbstract() { + fail(); + return false; + } + + @Override + public FullQualifiedName getFullQualifiedName() { + return nameBuilder.buildFQN(name); + } + + @Override + public String getNamespace() { + return nameBuilder.buildNamespace(); + } + + @Override + public EdmTypeKind getKind() { + fail(); + return null; + } + + @Override + public String getName() { + return name; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public List getKeyPredicateNames() { + fail(); + return null; + } + + @Override + public List getKeyPropertyRefs() { + fail(); + return null; + } + + @Override + public EdmKeyPropertyRef getKeyPropertyRef(final String keyPredicateName) { + fail(); + return null; + } + + @Override + public boolean hasStream() { + fail(); + return false; + } + + @Override + public EdmEntityType getBaseType() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java new file mode 100644 index 0000000000..246094ff7f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java @@ -0,0 +1,80 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmReferentialConstraint; +import org.apache.olingo.commons.api.edm.EdmTerm; + +public class EdmNavigationPropertyDouble implements EdmNavigationProperty { + private final String name; + + public EdmNavigationPropertyDouble(final String name) { + super(); + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public EdmEntityType getType() { + fail(); + return null; + } + + @Override + public boolean isNullable() { + fail(); + return false; + } + + @Override + public boolean containsTarget() { + fail(); + return false; + } + + @Override + public EdmNavigationProperty getPartner() { + fail(); + return null; + } + + @Override + public String getReferencingPropertyName(final String referencedPropertyName) { + fail(); + return null; + } + + @Override + public List getReferentialConstraints() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java new file mode 100644 index 0000000000..b2f1cf7574 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java @@ -0,0 +1,112 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmMapping; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.geo.SRID; + +public class EdmPropertyDouble implements EdmProperty { + private final String name; + + public EdmPropertyDouble(final String name) { + super(); + this.name = name; + } + + @Override + public String getName() { + + return name; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public EdmMapping getMapping() { + fail(); + return null; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public String getMimeType() { + fail(); + return null; + } + + @Override + public boolean isPrimitive() { + fail(); + return false; + } + + @Override + public boolean isNullable() { + fail(); + return false; + } + + @Override + public Integer getMaxLength() { + fail(); + return null; + } + + @Override + public Integer getPrecision() { + fail(); + return null; + } + + @Override + public Integer getScale() { + fail(); + return null; + } + + @Override + public SRID getSrid() { + fail(); + return null; + } + + @Override + public boolean isUnicode() { + fail(); + return false; + } + + @Override + public String getDefaultValue() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java new file mode 100644 index 0000000000..b129f6f10c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java @@ -0,0 +1,115 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class ExpandItemDouble implements ExpandItem { + private UriResourceNavigation target; + + public ExpandItemDouble(final EdmEntityType naviTargetEntity) { + target = new UriResourceNavigationDouble(naviTargetEntity, new EdmNavigationPropertyDouble( + naviTargetEntity.getName())); + } + + @Override + public LevelsExpandOption getLevelsOption() { + return null; + } + + @Override + public FilterOption getFilterOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + fail(); + return null; + } + + @Override + public UriInfoResource getResourcePath() { + return new UriInfoResourceDouble(target); + } + + @Override + public boolean isStar() { + return false; + } + + @Override + public boolean isRef() { + fail(); + return false; + } + + @Override + public EdmType getStartTypeFilter() { + fail(); + return null; + } + + @Override + public boolean hasCountPath() { + fail(); + return false; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java new file mode 100644 index 0000000000..c9cc1f6835 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java @@ -0,0 +1,43 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; + +public class ExpandOptionDouble implements ExpandOption { + private final String text; + private final List items; + + public ExpandOptionDouble(final String text, final List items) { + super(); + this.text = text; + this.items = items; + } + + @Override + public SystemQueryOptionKind getKind() { + fail(); + return null; + } + + @Override + public String getName() { + fail(); + return null; + } + + @Override + public String getText() { + return text; + } + + @Override + public List getExpandItems() { + return items; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java new file mode 100644 index 0000000000..8e8eb6d559 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java @@ -0,0 +1,373 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletInputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.olingo.commons.api.http.HttpMethod; + +public class HttpServletRequestDouble implements HttpServletRequest { + private final HttpRequestHeaderDouble reqHeader; + private final String queryString; + private final StringBuffer url; + private final StringBuffer input; + + public HttpServletRequestDouble(final String uri) throws IOException { + this(uri, null); + } + + public HttpServletRequestDouble(final String uri, final StringBuffer body) throws IOException { + this(uri, body, null); + } + + public HttpServletRequestDouble(final String uri, final StringBuffer body, + final Map> headers) throws IOException { + + super(); + this.reqHeader = new HttpRequestHeaderDouble(); + String[] uriParts = uri.split("\\?"); + this.url = new StringBuffer(uriParts[0]); + queryString = (uriParts.length == 2) ? uriParts[1] : null; + this.input = body; + if (uri.contains("$batch")) { + reqHeader.setBatchRequest(); + } + this.reqHeader.setHeaders(headers); + } + + @Override + public Object getAttribute(final String name) { + if (!"requestMapping".equals(name)) + fail(); + return null; + } + + @Override + public Enumeration getAttributeNames() { + fail(); + return null; + } + + @Override + public String getCharacterEncoding() { + fail(); + return null; + } + + @Override + public void setCharacterEncoding(final String env) throws UnsupportedEncodingException { + fail(); + + } + + @Override + public int getContentLength() { + fail(); + return 0; + } + + @Override + public String getContentType() { + fail(); + return null; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return new ServletInputStreamDouble(input); + } + + @Override + public String getParameter(final String name) { + fail(); + return null; + } + + @Override + public Enumeration getParameterNames() { + fail(); + return null; + } + + @Override + public String[] getParameterValues(final String name) { + fail(); + return null; + } + + @Override + public Map getParameterMap() { + fail(); + return null; + } + + @Override + public String getProtocol() { + return "HTTP/1.1"; + } + + @Override + public String getScheme() { + fail(); + return null; + } + + @Override + public String getServerName() { + fail(); + return null; + } + + @Override + public int getServerPort() { + fail(); + return 0; + } + + @Override + public BufferedReader getReader() throws IOException { + fail(); + return null; + } + + @Override + public String getRemoteAddr() { + fail(); + return null; + } + + @Override + public String getRemoteHost() { + fail(); + return null; + } + + @Override + public void setAttribute(final String name, final Object o) { + fail(); + + } + + @Override + public void removeAttribute(final String name) { + fail(); + + } + + @Override + public Locale getLocale() { + fail(); + return null; + } + + @Override + public Enumeration getLocales() { + fail(); + return null; + } + + @Override + public boolean isSecure() { + fail(); + return false; + } + + @Override + public RequestDispatcher getRequestDispatcher(final String path) { + fail(); + return null; + } + + @Override + public String getRealPath(final String path) { + fail(); + return null; + } + + @Override + public int getRemotePort() { + fail(); + return 0; + } + + @Override + public String getLocalName() { + fail(); + return null; + } + + @Override + public String getLocalAddr() { + fail(); + return null; + } + + @Override + public int getLocalPort() { + fail(); + return 0; + } + + @Override + public String getAuthType() { + fail(); + return null; + } + + @Override + public Cookie[] getCookies() { + fail(); + return null; + } + + @Override + public long getDateHeader(final String name) { + fail(); + return 0; + } + + @Override + public String getHeader(final String name) { + return null; + } + + @Override + public Enumeration getHeaders(final String name) { + + return reqHeader.get(name); + } + + @Override + public Enumeration getHeaderNames() { + return reqHeader.getEnumerator(); + } + + @Override + public int getIntHeader(final String name) { + fail(); + return 0; + } + + @Override + public String getMethod() { + if (url.toString().contains("$batch")) + return HttpMethod.POST.toString(); + else + return HttpMethod.GET.toString(); + } + + @Override + public String getPathInfo() { + fail(); + return null; + } + + @Override + public String getPathTranslated() { + fail(); + return null; + } + + @Override + public String getContextPath() { + fail(); + return null; + } + + @Override + public String getQueryString() { + // $orderby=Roles/$count%20desc,Address/Region%20asc&$select=ID,Name1 + return queryString; + } + + @Override + public String getRemoteUser() { + fail(); + return null; + } + + @Override + public boolean isUserInRole(final String role) { + fail(); + return false; + } + + @Override + public Principal getUserPrincipal() { + fail(); + return null; + } + + @Override + public String getRequestedSessionId() { + fail(); + return null; + } + + @Override + public String getRequestURI() { + fail(); + return null; + } + + @Override + public StringBuffer getRequestURL() { + // http://localhost:8090/BuPa/BuPa.svc/AdministrativeDivisions(DivisionCode='BE252',CodeID='3',CodePublisher='NUTS')/Parent/Parent + // http://localhost:8090/BuPa/BuPa.svc/Organizations + return url; + } + + @Override + public String getServletPath() { + return "/Olingo.svc"; + } + + @Override + public HttpSession getSession(final boolean create) { + return null; + } + + @Override + public HttpSession getSession() { + fail(); + return null; + } + + @Override + public boolean isRequestedSessionIdValid() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromURL() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + fail(); + return false; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java new file mode 100644 index 0000000000..9863e82acc --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java @@ -0,0 +1,253 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +public class HttpServletResponseDouble implements HttpServletResponse { + + private int setStatus; + private ServletOutputStream outputStream = new OutPutStream(); + + @Override + public String getCharacterEncoding() { + fail(); + return null; + } + + @Override + public String getContentType() { + fail(); + return null; + } + + @Override + public ServletOutputStream getOutputStream() throws IOException { + return this.outputStream; + } + + @Override + public PrintWriter getWriter() throws IOException { + fail(); + return null; + } + + @Override + public void setCharacterEncoding(String charset) { + fail(); + + } + + @Override + public void setContentLength(int len) { + fail(); + + } + + @Override + public void setContentType(String type) { + fail(); + + } + + @Override + public void setBufferSize(int size) { + fail(); + + } + + @Override + public int getBufferSize() { + return ((OutPutStream) this.outputStream).getSize(); + } + + @Override + public void flushBuffer() throws IOException { + fail(); + + } + + @Override + public void resetBuffer() { + fail(); + + } + + @Override + public boolean isCommitted() { + fail(); + return false; + } + + @Override + public void reset() { + fail(); + + } + + @Override + public void setLocale(Locale loc) { + fail(); + + } + + @Override + public Locale getLocale() { + fail(); + return null; + } + + @Override + public void addCookie(Cookie cookie) { + fail(); + + } + + @Override + public boolean containsHeader(String name) { + fail(); + return false; + } + + @Override + public String encodeURL(String url) { + fail(); + return null; + } + + @Override + public String encodeRedirectURL(String url) { + fail(); + return null; + } + + @Override + public String encodeUrl(String url) { + fail(); + return null; + } + + @Override + public String encodeRedirectUrl(String url) { + fail(); + return null; + } + + @Override + public void sendError(int sc, String msg) throws IOException { + fail(); + + } + + @Override + public void sendError(int sc) throws IOException { + fail(); + + } + + @Override + public void sendRedirect(String location) throws IOException { + fail(); + + } + + @Override + public void setDateHeader(String name, long date) { + fail(); + + } + + @Override + public void addDateHeader(String name, long date) { + fail(); + + } + + @Override + public void setHeader(String name, String value) { + fail(); + + } + + @Override + public void addHeader(String name, String value) { + // TODO + } + + @Override + public void setIntHeader(String name, int value) { + fail(); + + } + + @Override + public void addIntHeader(String name, int value) { + fail(); + + } + + @Override + public void setStatus(int sc) { + this.setStatus = sc; + } + + @Override + public void setStatus(int sc, String sm) { + fail(); + + } + + public int getStatus() { + return setStatus; + } + + class OutPutStream extends ServletOutputStream { + List buffer = new ArrayList(); + + @Override + public void write(int b) throws IOException { + buffer.add(new Integer(b)); + } + + public Iterator getBuffer() { + return buffer.iterator(); + } + + public int getSize() { + return buffer.size(); + } + } + + // + class ResultStream extends InputStream { + private final Iterator bufferExcess; + + public ResultStream(OutPutStream buffer) { + super(); + this.bufferExcess = buffer.getBuffer(); + } + + @Override + public int read() throws IOException { + if (bufferExcess.hasNext()) + return bufferExcess.next().intValue(); + return -1; + } + + } + + public InputStream getInputStream() { + + return new ResultStream((OutPutStream) this.outputStream); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java new file mode 100644 index 0000000000..0d4d6856da --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java @@ -0,0 +1,213 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataHttpHandler; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataBatchProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; + +public class IntegrationTestHelper { + public final HttpServletRequestDouble req; + public final HttpServletResponseDouble resp; + private static final String uriPrefix = "http://localhost:8080/Test/Olingo.svc/"; + private static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + public IntegrationTestHelper(EntityManagerFactory localEmf, String urlPath) throws IOException, + ODataException { + this(localEmf, null, urlPath, null, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath) throws IOException, + ODataException { + this(localEmf, ds, urlPath, null, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, String urlPath, StringBuffer requestBody) + throws IOException, ODataException { + this(localEmf, null, urlPath, requestBody, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, String functionPackage) + throws IOException, ODataException { + this(localEmf, ds, urlPath, null, functionPackage, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, StringBuffer requestBody) + throws IOException, ODataException { + this(localEmf, ds, urlPath, requestBody, null, null); + } + + public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath, + final JPAODataPagingProvider provider) throws IOException, ODataException { + this(localEmf, null, urlPath, null, null, provider); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, final String urlPath, JPAODataClaimsProvider claims) + throws IOException, ODataException { + this(localEmf, null, urlPath, null, null, null, null, claims); + } + + public IntegrationTestHelper(final EntityManagerFactory emf, final String urlPath, + final JPAODataPagingProvider provider, final Map> headers) throws IOException, + ODataException { + this(emf, null, urlPath, null, null, provider, headers, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, StringBuffer requestBody, + String functionPackage, JPAODataPagingProvider provider) throws IOException, ODataException { + this(localEmf, ds, urlPath, requestBody, functionPackage, provider, null, null); + } + + public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource ds, final String urlPath, + final StringBuffer requestBody, final String functionPackage, final JPAODataPagingProvider provider, + final Map> headers, final JPAODataClaimsProvider claims) + throws IOException, ODataException { + + super(); + EntityManager em = localEmf.createEntityManager(); + this.req = new HttpServletRequestDouble(uriPrefix + urlPath, requestBody, headers); + this.resp = new HttpServletResponseDouble(); + OData odata = OData.newInstance(); + String[] packages = TestBase.enumPackages; + if (functionPackage != null) + packages = ArrayUtils.add(packages, functionPackage); + + JPAODataSessionContextAccess context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, localEmf, + null, packages), ds, provider, functionPackage); + + ODataHttpHandler handler = odata.createHandler(odata.createServiceMetadata(context.getEdmProvider(), + new ArrayList())); + + handler.register(new JPAODataRequestProcessor(context, claims, em)); + handler.register(new JPAODataBatchProcessor(context, em)); + handler.process(req, resp); + + } + + public HttpServletResponseDouble getResponce() { + return resp; + } + + public int getStatus() { + return resp.getStatus(); + } + + public String getRawResult() throws IOException { + InputStream in = resp.getInputStream(); + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String read; + + while ((read = br.readLine()) != null) { + sb.append(read); + } + br.close(); + return sb.toString(); + } + + public List getRawBatchResult() throws IOException { + List result = new ArrayList<>(); + + InputStream in = resp.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String read; + + while ((read = br.readLine()) != null) { + result.add(read); + } + br.close(); + return result; + } + + public ArrayNode getValues() throws JsonProcessingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = mapper.readTree(getRawResult()); + if (!(node.get("value") instanceof ArrayNode)) + fail("Wrong result type; ArrayNode expected"); + ArrayNode values = (ArrayNode) node.get("value"); + return values; + } + + public ObjectNode getValue() throws JsonProcessingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + JsonNode value = mapper.readTree(getRawResult()); + if (!(value instanceof ObjectNode)) + fail("Wrong result type; ObjectNode expected"); + return (ObjectNode) value; + } + + public void assertStatus(int exp) throws IOException { + assertEquals(getRawResult(), exp, getStatus()); + + } + + public int getBatchResultStatus(int i) throws IOException { + List result = getRawBatchResult(); + int count = 0; + for (String resultLine : result) { + if (resultLine.contains("HTTP/1.1")) { + count += 1; + if (count == i) { + String[] statusElements = resultLine.split(" "); + return Integer.parseInt(statusElements[1]); + } + } + } + return 0; + } + + public JsonNode getBatchResult(int i) throws IOException { + List result = getRawBatchResult(); + int count = 0; + boolean found = false; + + for (String resultLine : result) { + if (resultLine.contains("HTTP/1.1")) { + count += 1; + if (count == i) { + found = true; + } + } + if (found && resultLine.startsWith("{")) { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readTree(resultLine); + } + } + return null; + } + + public byte[] getBinaryResult() throws IOException { + byte[] result = new byte[resp.getBufferSize()]; + InputStream in = resp.getInputStream(); + in.read(result); + return result; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java new file mode 100644 index 0000000000..bd7703ca77 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java @@ -0,0 +1,200 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.server.api.uri.UriResourceProperty; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class JPAEntityTypeDouble implements JPAEntityType { + private final JPAEntityType base; + + public JPAEntityTypeDouble(JPAEntityType base) { + super(); + this.base = base; + } + + @Override + public JPAAssociationAttribute getAssociation(String internalName) throws ODataJPAModelException { + return base.getAssociation(internalName); + } + + @Override + public JPAAssociationPath getAssociationPath(String externalName) throws ODataJPAModelException { + return base.getAssociationPath(externalName); + } + + @Override + public List getAssociationPathList() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAttribute getAttribute(UriResourceProperty uriResourceItem) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAttribute getAttribute(String internalName) throws ODataJPAModelException { + return base.getAttribute(internalName); + } + + @Override + public List getAttributes() throws ODataJPAModelException { + return base.getAttributes(); + } + + @Override + public List getCollectionAttributesPath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAssociationPath getDeclaredAssociation(JPAAssociationPath associationPath) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAssociationPath getDeclaredAssociation(String externalName) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredAssociations() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredAttributes() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredCollectionAttributes() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAPath getPath(String externalName) throws ODataJPAModelException { + return base.getPath(externalName); + } + + @Override + public List getPathList() throws ODataJPAModelException { + return base.getPathList(); + } + + @Override + public Class getTypeClass() { + return base.getTypeClass(); + } + + @Override + public boolean isAbstract() { + fail(); + return false; + } + + @Override + public FullQualifiedName getExternalFQN() { + return base.getExternalFQN(); + } + + @Override + public String getExternalName() { + return base.getExternalName(); + } + + @Override + public String getInternalName() { + return getInternalName(); + } + + @Override + public String getContentType() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAPath getContentTypeAttributePath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getKey() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getKeyPath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public Class getKeyType() { + return base.getKeyType(); + } + + @Override + public List getSearchablePath() throws ODataJPAModelException { + return base.getSearchablePath(); + } + + @Override + public JPAPath getStreamAttributePath() throws ODataJPAModelException { + return base.getStreamAttributePath(); + } + + @Override + public String getTableName() { + return base.getTableName(); + } + + @Override + public boolean hasEtag() throws ODataJPAModelException { + return base.hasEtag(); + } + + @Override + public boolean hasStream() throws ODataJPAModelException { + return base.hasStream(); + } + + @Override + public List searchChildPath(JPAPath selectItemPath) { + return base.searchChildPath(selectItemPath); + } + + @Override + public JPACollectionAttribute getCollectionAttribute(String externalName) throws ODataJPAModelException { + return base.getCollectionAttribute(externalName); + } + + @Override + public List getProtections() throws ODataJPAModelException { + return base.getProtections(); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java new file mode 100644 index 0000000000..9a08deac2b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java @@ -0,0 +1,188 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmAction; +import org.apache.olingo.commons.api.edm.EdmAnnotations; +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmEnumType; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmSchema; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmTypeDefinition; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.etag.ServiceMetadataETagSupport; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class ServiceMetadataDouble implements ServiceMetadata { + private final Edm edm; + + public ServiceMetadataDouble() { + super(); + edm = new EdmDouble(); + } + + public ServiceMetadataDouble(JPAEdmNameBuilder nameBuilder, String typeName) { + super(); + this.nameBuilder = nameBuilder; + this.edm = new EdmDouble(typeName); + } + + private JPAEdmNameBuilder nameBuilder; + + @Override + public Edm getEdm() { + return edm; + } + + @Override + public ODataServiceVersion getDataServiceVersion() { + fail(); + return null; + } + + @Override + public List getReferences() { + fail(); + return null; + } + + @Override + public ServiceMetadataETagSupport getServiceMetadataETagSupport() { + fail(); + return null; + } + + class EdmDouble implements Edm { + private Map typeMap; + + public EdmDouble() { + super(); + typeMap = new HashMap(); + } + + public EdmDouble(String name) { + super(); + typeMap = new HashMap(); + EdmEntityType edmType = new EdmEntityTypeDouble(nameBuilder, name); + typeMap.put(edmType.getFullQualifiedName(), edmType); + } + + @Override + public List getSchemas() { + fail(); + return null; + } + + @Override + public EdmSchema getSchema(String namespace) { + fail(); + return null; + } + + @Override + public EdmEntityContainer getEntityContainer() { + fail(); + return null; + } + + @Override + public EdmEntityContainer getEntityContainer(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmEnumType getEnumType(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmTypeDefinition getTypeDefinition(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityType(FullQualifiedName name) { + return typeMap.get(name); + } + + @Override + public EdmComplexType getComplexType(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmAction getUnboundAction(FullQualifiedName actionName) { + fail(); + return null; + } + + @Override + public EdmAction getBoundAction(FullQualifiedName actionName, FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + fail(); + return null; + } + + @Override + public List getUnboundFunctions(FullQualifiedName functionName) { + fail(); + return null; + } + + @Override + public EdmFunction getUnboundFunction(FullQualifiedName functionName, List parameterNames) { + fail(); + return null; + } + + @Override + public EdmFunction getBoundFunction(FullQualifiedName functionName, FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection, List parameterNames) { + fail(); + return null; + } + + @Override + public EdmTerm getTerm(FullQualifiedName termName) { + fail(); + return null; + } + + @Override + public EdmAnnotations getAnnotationGroup(FullQualifiedName targetName, String qualifier) { + fail(); + return null; + } + + @Override + public EdmAction getBoundActionWithBindingType(FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + return null; + } + + @Override + public List getBoundFunctionsWithBindingType(FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + // TODO Check what this is used for + return null; + } + + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java new file mode 100644 index 0000000000..9dbc14e908 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java @@ -0,0 +1,41 @@ +package com.sap.olingo.jpa.processor.core.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.junit.BeforeClass; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestBase { + + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + public static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" }; + protected static EntityManagerFactory emf; + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + protected static DataSource ds; + + @BeforeClass + public static void setupClass() throws ODataJPAModelException { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_DERBY); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + } + + protected void createHeaders() { + headers = new HashMap<>(); + List languageHeaders = new ArrayList<>(); + languageHeaders.add("de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); + headers.put("accept-language", languageHeaders); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java new file mode 100644 index 0000000000..3a8dd052c3 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java @@ -0,0 +1,91 @@ +package com.sap.olingo.jpa.processor.core.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.persistence.criteria.From; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Root; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.Before; +import org.mockito.Mockito; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.query.JPAAbstractJoinQuery; +import com.sap.olingo.jpa.processor.core.query.JPAJoinQuery; + +public class TestQueryBase extends TestBase { + + protected JPAAbstractJoinQuery cut; + protected JPAEntityType jpaEntityType; + protected HashMap> joinTables; + protected Root root; + protected JPAODataSessionContextAccess context; + protected UriInfo uriInfo; + + public TestQueryBase() { + super(); + } + + @Before + public void setup() throws ODataException { + buildUriInfo("BusinessPartners", "BusinessPartner"); + + helper = new TestHelper(emf, PUNIT_NAME); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + jpaEntityType = helper.getJPAEntityType("BusinessPartners"); + createHeaders(); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages), ds, + null); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables = new HashMap<>(); + joinTables.put(jpaEntityType.getExternalName(), root); + } + + protected EdmType buildUriInfo(final String esName, final String etName) { + uriInfo = Mockito.mock(UriInfo.class); + final EdmEntitySet odataEs = Mockito.mock(EdmEntitySet.class); + final EdmType odataType = Mockito.mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = Mockito.mock(UriResourceEntitySet.class); + Mockito.when(uriInfo.getUriResourceParts()).thenReturn(resources); + Mockito.when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + Mockito.when(esResource.getEntitySet()).thenReturn(odataEs); + Mockito.when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + Mockito.when(esResource.getType()).thenReturn(odataType); + Mockito.when(odataEs.getName()).thenReturn(esName); + Mockito.when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + Mockito.when(odataType.getName()).thenReturn(etName); + resources.add(esResource); + return odataType; + } + + protected void fillJoinTable(Root joinRoot) { + Join join = joinRoot.join("locationName", JoinType.LEFT); + joinTables.put("locationName", join); + join = joinRoot.join("address", JoinType.LEFT); + join = join.join("countryName", JoinType.LEFT); + joinTables.put("countryName", join); + join = joinRoot.join("address", JoinType.LEFT); + join = join.join("regionName", JoinType.LEFT); + joinTables.put("regionName", join); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java new file mode 100644 index 0000000000..7c7d807363 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java @@ -0,0 +1,66 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmStructuredType; +import org.apache.olingo.server.api.deserializer.DeserializerException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriHelper; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; + +public class UriHelperDouble implements UriHelper { + private Map keyPredicates; + private String idPropertyName; + + @Override + public String buildContextURLSelectList(EdmStructuredType type, ExpandOption expand, SelectOption select) + throws SerializerException { + fail(); + return null; + } + + @Override + public String buildContextURLKeyPredicate(List keys) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildCanonicalURL(EdmEntitySet edmEntitySet, Entity entity) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildKeyPredicate(EdmEntityType edmEntityType, Entity entity) throws SerializerException { + + return keyPredicates.get(entity.getProperty(idPropertyName).getValue()); + } + + @Override + public UriResourceEntitySet parseEntityId(Edm edm, String entityId, String rawServiceRoot) + throws DeserializerException { + fail(); + return null; + } + + public Map getKeyPredicates() { + return keyPredicates; + } + + public void setKeyPredicates(Map keyPredicates, String idPropertyName) { + this.keyPredicates = keyPredicates; + this.idPropertyName = idPropertyName; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java new file mode 100644 index 0000000000..411d7e56a4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java @@ -0,0 +1,380 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoAll; +import org.apache.olingo.server.api.uri.UriInfoBatch; +import org.apache.olingo.server.api.uri.UriInfoCrossjoin; +import org.apache.olingo.server.api.uri.UriInfoEntityId; +import org.apache.olingo.server.api.uri.UriInfoKind; +import org.apache.olingo.server.api.uri.UriInfoMetadata; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriInfoService; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceProperty; +import org.apache.olingo.server.api.uri.queryoption.AliasQueryOption; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption; +import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.FormatOption; +import org.apache.olingo.server.api.uri.queryoption.IdOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class UriInfoDouble implements UriInfo { + + private final SelectOption selOpts; + private ExpandOption expandOpts; + private List uriResources; + + public UriInfoDouble(SelectOption selOpts) { + super(); + this.selOpts = selOpts; + this.uriResources = new ArrayList<>(1); + } + + @Override + public FormatOption getFormatOption() { + fail(); + return null; + } + + @Override + public String getFragment() { + fail(); + return null; + } + + @Override + public List getCustomQueryOptions() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + return expandOpts; + } + + @Override + public FilterOption getFilterOption() { + fail(); + return null; + } + + @Override + public IdOption getIdOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + return selOpts; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public SkipTokenOption getSkipTokenOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public List getUriResourceParts() { + return uriResources; + } + + @Override + public String getValueForAlias(String alias) { + fail(); + return null; + } + + @Override + public List getEntitySetNames() { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityTypeCast() { + fail(); + return null; + } + + @Override + public UriInfoKind getKind() { + fail(); + return null; + } + + @Override + public UriInfoService asUriInfoService() { + fail(); + return null; + } + + @Override + public UriInfoAll asUriInfoAll() { + fail(); + return null; + } + + @Override + public UriInfoBatch asUriInfoBatch() { + fail(); + return null; + } + + @Override + public UriInfoCrossjoin asUriInfoCrossjoin() { + fail(); + return null; + } + + @Override + public UriInfoEntityId asUriInfoEntityId() { + fail(); + return null; + } + + @Override + public UriInfoMetadata asUriInfoMetadata() { + fail(); + return null; + } + + @Override + public UriInfoResource asUriInfoResource() { + fail(); + return null; + } + + @Override + public List getSystemQueryOptions() { + fail(); + return null; + } + + @Override + public List getAliases() { + fail(); + return null; + } + + class primitiveDouble implements UriResourcePrimitiveProperty { + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + } + + class complexDouble implements UriResourceComplexProperty { + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexType() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexTypeFilter() { + fail(); + return null; + } + } + + class propertyDouble implements UriResourceProperty { + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + } + + public void setExpandOpts(ExpandOption expandOpts) { + this.expandOpts = expandOpts; + } + + public void setUriResources(List uriResources) { + this.uriResources = uriResources; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + + @Override + public DeltaTokenOption getDeltaTokenOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java new file mode 100644 index 0000000000..b1f3cdda57 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java @@ -0,0 +1,126 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption; +import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.FormatOption; +import org.apache.olingo.server.api.uri.queryoption.IdOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class UriInfoResourceDouble implements UriInfoResource { + private final List resources; + + public UriInfoResourceDouble(UriResourceNavigation target) { + resources = new ArrayList<>(); + resources.add(target); + } + + @Override + public List getCustomQueryOptions() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + fail(); + return null; + } + + @Override + public FilterOption getFilterOption() { + return null; + } + + @Override + public FormatOption getFormatOption() { + fail(); + return null; + } + + @Override + public IdOption getIdOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + fail(); + return null; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public SkipTokenOption getSkipTokenOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public List getUriResourceParts() { + return resources; + } + + @Override + public String getValueForAlias(String alias) { + fail(); + return null; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + + @Override + public DeltaTokenOption getDeltaTokenOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java new file mode 100644 index 0000000000..d927a21c3f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java @@ -0,0 +1,85 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceNavigation; + +public class UriResourceNavigationDouble implements UriResourceNavigation { + private final EdmType type; + private final EdmNavigationProperty property; + + public UriResourceNavigationDouble(EdmEntityType naviTargetEntity) { + this(naviTargetEntity, null); + } + + public UriResourceNavigationDouble(EdmType type, EdmNavigationProperty property) { + super(); + this.type = type; + this.property = property; + } + + @Override + public EdmType getType() { + return type; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + return UriResourceKind.navigationProperty; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmNavigationProperty getProperty() { + return property; + } + + @Override + public List getKeyPredicates() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnCollection() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnEntry() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java new file mode 100644 index 0000000000..0ec62b797f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java @@ -0,0 +1,59 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.Assert.fail; + +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceProperty; + +public class UriResourcePropertyDouble implements UriResourceProperty { + private final EdmProperty property; + + public UriResourcePropertyDouble(EdmProperty property) { + super(); + this.property = property; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmProperty getProperty() { + + return property; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java new file mode 100644 index 0000000000..2b41c76e62 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java @@ -0,0 +1,29 @@ +package com.sap.olingo.jpa.processor.core.testmodel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; + +public class AssertCollection { + + public static void assertListEquals(final List exp, final List act, Class reflection) { + assertEquals(exp.size(), act.size()); + boolean found; + for (final T expItem : exp) { + for (T actItem : act) { + found = EqualsBuilder.reflectionEquals(expItem, actItem, true, reflection); + if (found) { + break; + } + assertTrue("Cloud not find" + expItem.toString(), found); + } + } + } + + private AssertCollection() { + super(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java new file mode 100644 index 0000000000..95db2482ea --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java @@ -0,0 +1,163 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Country; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestAssociations { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private EntityManager em; + private CriteriaBuilder cb; + + @BeforeClass + public static void setupClass() { + Map properties = new HashMap<>(); + properties.put(ENTITY_MANAGER_DATA_SOURCE, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + @Before + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + @Test + public void getBuPaRoles() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("roles").alias("roles")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + BusinessPartnerRole role = (BusinessPartnerRole) result.get(0).get("roles"); + assertNotNull(role); + } + + @Test + public void getBuPaLocation() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("locationName").alias("L")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivisionDescription act = (AdministrativeDivisionDescription) result.get(0).get("L"); + assertNotNull(act); + } + + @Test + public void getRoleBuPa() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartnerRole.class); + + cq.multiselect(root.get("businessPartner").alias("BuPa")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + BusinessPartner bp = (BusinessPartner) result.get(0).get("BuPa"); + assertNotNull(bp); + } + + @Test + public void getBuPaCountryName() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("address").get("countryName").alias("CN")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + Country region = (Country) result.get(0).get("CN"); + assertNotNull(region); + } + + @Test + public void getBuPaRegionName() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("address").get("regionName").alias("RN")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivisionDescription region = (AdministrativeDivisionDescription) result.get(0).get("RN"); + assertNotNull(region); + } + + @Test + public void getAdministrativeDivisionParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + + cq.multiselect(root.get("parent").alias("P")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("P"); + assertNotNull(act); + } + + @Test + public void getAdministrativeDivisionOneParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + root.alias("Source"); + cq.multiselect(root.get("parent").alias("P")); + // cq.select((Selection) root); + cq.where(cb.and( + cb.equal(root.get("codePublisher"), "Eurostat"), + cb.and( + cb.equal(root.get("codeID"), "NUTS3"), + cb.equal(root.get("divisionCode"), "BE251")))); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("P"); + assertNotNull(act); + assertEquals("NUTS2", act.getCodeID()); + assertEquals("BE25", act.getDivisionCode()); + } + + @Test + public void getAdministrativeDivisionChildrenOfOneParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + root.alias("Source"); + cq.multiselect(root.get("children").alias("C")); + cq.where(cb.and( + cb.equal(root.get("codePublisher"), "Eurostat"), + cb.and( + cb.equal(root.get("codeID"), "NUTS2"), + cb.equal(root.get("divisionCode"), "BE25")))); + cq.orderBy(cb.desc(root.get("divisionCode"))); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("C"); + assertNotNull(act); + assertEquals(8, result.size()); + assertEquals("NUTS3", act.getCodeID()); + assertEquals("BE251", act.getDivisionCode()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java new file mode 100644 index 0000000000..16afabd1cf --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java @@ -0,0 +1,239 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.criteria.Subquery; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestCriteriaBuilder { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private EntityManager em; + private CriteriaBuilder cb; + + @BeforeClass + public static void setupClass() { + Map properties = new HashMap<>(); + properties.put(ENTITY_MANAGER_DATA_SOURCE, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + @Before + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + @SuppressWarnings("unchecked") + @Test + public void testSubstringWithExperession() { + CriteriaQuery adminQ = cb.createTupleQuery(); + Root adminRoot1 = adminQ.from(AdministrativeDivisionDescription.class); +// (Expression) cb.sum(jpaOperator.getLeft(), jpaOperator.getRightAsNumber()); +// cb.substring((Expression) (jpaFunction.getParameter(0).get()), start, length); + Path p = adminRoot1.get("name"); + + Expression sum = cb.sum(cb.literal(1), cb.literal(4)); + + adminQ.where(cb.equal(cb.substring((Expression) (p), cb.literal(1), sum), "North")); + adminQ.multiselect(adminRoot1.get("name")); + TypedQuery tq = em.createQuery(adminQ); + tq.getResultList(); + } + + @Ignore // To time consuming + @Test + public void testSubSelect() { + // https://stackoverflow.com/questions/29719321/combining-conditional-expressions-with-and-and-or-predicates-using-the-jpa-c + CriteriaQuery adminQ1 = cb.createTupleQuery(); + Subquery adminQ2 = adminQ1.subquery(Long.class); + Subquery adminQ3 = adminQ2.subquery(Long.class); + Subquery org = adminQ3.subquery(Long.class); + + Root adminRoot1 = adminQ1.from(AdministrativeDivision.class); + Root adminRoot2 = adminQ2.from(AdministrativeDivision.class); + Root adminRoot3 = adminQ3.from(AdministrativeDivision.class); + Root org1 = org.from(Organization.class); + + org.where(cb.and(cb.equal(org1.get("iD"), "3")), createParentOrg(org1, adminRoot3)); + org.select(cb.literal(1L)); + + adminQ3.where(cb.and(createParentAdmin(adminRoot3, adminRoot2), cb.exists(org))); + adminQ3.select(cb.literal(1L)); + + adminQ2.where(cb.and(createParentAdmin(adminRoot2, adminRoot1), cb.exists(adminQ3))); + adminQ2.select(cb.literal(1L)); + + adminQ1.where(cb.exists(adminQ2)); + adminQ1.multiselect(adminRoot1.get("divisionCode")); + + TypedQuery tq = em.createQuery(adminQ1); + tq.getResultList(); + } + + @SuppressWarnings("unchecked") + @Test + public void testSubSelectTopOrderBy() { + // https://stackoverflow.com/questions/9321916/jpa-criteriabuilder-how-to-use-in-comparison-operator + // https://stackoverflow.com/questions/24109412/in-clause-with-a-composite-primary-key-in-jpa-criteria#24265131 + CriteriaQuery roleQ = cb.createTupleQuery(); + Root roleRoot = roleQ.from(BusinessPartnerRole.class); + + Subquery bupaQ = roleQ.subquery(BusinessPartner.class); + @SuppressWarnings("rawtypes") + Root bupaRoot = roleQ.from(BusinessPartner.class); + + bupaQ.select(bupaRoot.get("iD")); +// Expression exp = scheduleRequest.get("createdBy"); +// Predicate predicate = exp.in(myList); +// criteria.where(predicate); + + List ids = new ArrayList<>(); + ids.add("1"); + ids.add("2"); + bupaQ.where(bupaRoot.get("iD").in(ids)); +// bupaQ.select( +// (Expression) cb.construct( +// BusinessPartner.class, +// bupaRoot.get("ID"))); + + // roleQ.where(cb.in(roleRoot.get("businessPartnerID")).value(bupaQ)); + roleQ.where(cb.in(roleRoot.get("businessPartnerID")).value(bupaQ)); + roleQ.multiselect(roleRoot.get("businessPartnerID")); + TypedQuery tq = em.createQuery(roleQ); + tq.getResultList(); + } + + @Test + public void testFilterOnPrimitiveCollectionAttribute() { + CriteriaQuery orgQ = cb.createTupleQuery(); + Root orgRoot = orgQ.from(Organization.class); + orgQ.select(orgRoot.get("iD")); + orgQ.where(cb.like(orgRoot.get("comment"), "%just%")); + TypedQuery tq = em.createQuery(orgQ); + List act = tq.getResultList(); + assertEquals(1, act.size()); + } + + @Test + public void testFilterOnEmbeddedCollectionAttribute() { + CriteriaQuery pQ = cb.createTupleQuery(); + Root pRoot = pQ.from(Person.class); + pQ.select(pRoot.get("iD")); + pQ.where(cb.equal(pRoot.get("inhouseAddress").get("taskID"), "MAIN")); + TypedQuery tq = em.createQuery(pQ); + List act = tq.getResultList(); + assertEquals(1, act.size()); + } + + @Test + public void TestExpandCount() { + CriteriaQuery count = cb.createTupleQuery(); + Root roles = count.from(BusinessPartnerRole.class); + + count.multiselect(roles.get("businessPartnerID"), cb.count(roles).alias("$count")); + count.groupBy(roles.get("businessPartnerID")); + count.orderBy(cb.desc(cb.count(roles))); + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + tq.getFirstResult(); + } + + @Test + public void TestAnd() { + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + + count.multiselect(adminDiv); + Predicate[] restrictions = new Predicate[3]; + restrictions[0] = cb.equal(adminDiv.get("codeID"), "NUTS2"); + restrictions[1] = cb.equal(adminDiv.get("divisionCode"), "BE34"); + restrictions[2] = cb.equal(adminDiv.get("codePublisher"), "Eurostat"); + count.where(cb.and(restrictions)); + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + tq.getFirstResult(); + } + + @Ignore + @Test + public void TestSearchEmbeddedId() { + CriteriaQuery cq = cb.createTupleQuery(); + Root adminDiv = cq.from(AdministrativeDivisionDescription.class); + cq.multiselect(adminDiv); + + Subquery sq = cq.subquery(AdministrativeDivisionDescriptionKey.class); + Root text = sq.from(AdministrativeDivisionDescription.class); + sq.where(cb.function("CONTAINS", Boolean.class, text.get("name"), cb.literal("luettich"))); + Expression exp = text.get("key"); + sq.select(exp); + + cq.where(cb.and(cb.equal(adminDiv.get("key").get("codeID"), "NUTS2"), + cb.in(sq).value(sq))); + TypedQuery tq = em.createQuery(cq); + List act = tq.getResultList(); + System.out.println(act.size()); + } + + @Ignore + @Test + public void TestSearchNoSubquery() { + CriteriaQuery cq = cb.createTupleQuery(); + Root adminDiv = cq.from(AdministrativeDivisionDescription.class); + cq.multiselect(adminDiv); + + // Predicate[] restrictions = new Predicate[2]; + cq.where( + cb.and(cb.equal(cb.conjunction(), + cb.function("CONTAINS", Boolean.class, adminDiv.get("name"), cb.literal("luettich"))), + cb.equal(adminDiv.get("key").get("codeID"), "NUTS2"))); + + TypedQuery tq = em.createQuery(cq); + List act = tq.getResultList(); + System.out.println(act.size()); + } + + private Expression createParentAdmin(Root subQuery, + Root query) { + return cb.and(cb.equal(query.get("codePublisher"), subQuery.get("codePublisher")), + cb.and(cb.equal(query.get("codeID"), subQuery.get("parentCodeID")), + cb.equal(query.get("divisionCode"), subQuery.get("parentDivisionCode")))); + } + + private Predicate createParentOrg(Root org1, Root adminRoot3) { + return cb.and(cb.equal(adminRoot3.get("codePublisher"), org1.get("address").get("regionCodePublisher")), + cb.and(cb.equal(adminRoot3.get("codeID"), org1.get("address").get("regionCodeID")), + cb.equal(adminRoot3.get("divisionCode"), org1.get("address").get("region")))); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java new file mode 100644 index 0000000000..d5d4608c9f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java @@ -0,0 +1,177 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.Assert.assertNotNull; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.ParameterMode; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.StoredProcedureQuery; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestFunctions { + protected static final String PUNIT_NAME = "org.apache.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private static DataSource ds; + + @BeforeClass + public static void setupClass() { + + Map properties = new HashMap<>(); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + + properties.put(ENTITY_MANAGER_DATA_SOURCE, ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + private EntityManager em; + + private CriteriaBuilder cb; + + @Before + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + @Ignore + @Test + public void TestProcedure() throws SQLException { + StoredProcedureQuery pc = em.createStoredProcedureQuery("\"OLINGO\".\"org.apache.olingo.jpa::Siblings\""); + + pc.registerStoredProcedureParameter("CodePublisher", String.class, ParameterMode.IN); + pc.setParameter("CodePublisher", "Eurostat"); + pc.registerStoredProcedureParameter("CodeID", String.class, ParameterMode.IN); + pc.setParameter("CodeID", "NUTS2"); + pc.registerStoredProcedureParameter("DivisionCode", String.class, ParameterMode.IN); + pc.setParameter("DivisionCode", "BE25"); +// pc.setParameter("CodePublisher", "Eurostat"); +// pc.setParameter("CodeID", "NUTS2"); +// pc.setParameter("DivisionCode", "BE25"); + + Connection conn = ds.getConnection(); + DatabaseMetaData meta = conn.getMetaData(); + ResultSet metaR = meta.getProcedures(conn.getCatalog(), "OLINGO", "%"); + + while (metaR.next()) { + String procedureCatalog = metaR.getString(1); + String procedureSchema = metaR.getString(2); + String procedureName = metaR.getString(3); +// reserved for future use +// reserved for future use +// reserved for future use + String remarks = metaR.getString(7); + Short procedureTYpe = metaR.getShort(8); +// String specificName = metaR.getString(9); + + System.out.println("procedureCatalog=" + procedureCatalog); + System.out.println("procedureSchema=" + procedureSchema); + System.out.println("procedureName=" + procedureName); + System.out.println("remarks=" + remarks); + System.out.println("procedureType=" + procedureTYpe); +// System.out.println("specificName=" + specificName); + } + ResultSet rs = meta.getProcedureColumns(conn.getCatalog(), + "OLINGO", "%", "%"); + + while (rs.next()) { + // get stored procedure metadata + String procedureCatalog = rs.getString(1); + String procedureSchema = rs.getString(2); + String procedureName = rs.getString(3); + String columnName = rs.getString(4); + short columnReturn = rs.getShort(5); + int columnDataType = rs.getInt(6); + String columnReturnTypeName = rs.getString(7); + int columnPrecision = rs.getInt(8); + int columnByteLength = rs.getInt(9); + short columnScale = rs.getShort(10); + short columnRadix = rs.getShort(11); + short columnNullable = rs.getShort(12); + String columnRemarks = rs.getString(13); + + System.out.println("stored Procedure name=" + procedureName); + System.out.println("procedureCatalog=" + procedureCatalog); + System.out.println("procedureSchema=" + procedureSchema); + System.out.println("procedureName=" + procedureName); + System.out.println("columnName=" + columnName); + System.out.println("columnReturn=" + columnReturn); + System.out.println("columnDataType=" + columnDataType); + System.out.println("columnReturnTypeName=" + columnReturnTypeName); + System.out.println("columnPrecision=" + columnPrecision); + System.out.println("columnByteLength=" + columnByteLength); + System.out.println("columnScale=" + columnScale); + System.out.println("columnRadix=" + columnRadix); + System.out.println("columnNullable=" + columnNullable); + System.out.println("columnRemarks=" + columnRemarks); + } + conn.close(); + pc.execute(); + List r = pc.getResultList(); + + Object[] one = (Object[]) r.get(0); + assertNotNull(one); + } + + @Ignore + @Test + public void TestScalarFunctionsWhere() { + CreateUDFDerby(); + + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + count.multiselect(adminDiv); + count.where(cb.equal( + cb.function("IS_PRIME", boolean.class, cb.literal(5)), + new Boolean(true))); + // cb.literal + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + assertNotNull(act); + tq.getFirstResult(); + } + + private void CreateUDFDerby() { + EntityTransaction t = em.getTransaction(); + + StringBuffer dropString = new StringBuffer("DROP FUNCTION IS_PRIME"); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("CREATE FUNCTION IS_PRIME(number Integer) RETURNS Integer "); + sqlString.append("PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA "); + sqlString.append("EXTERNAL NAME 'com.sap.olingo.jpa.processor.core.test_udf.isPrime'"); + + t.begin(); + Query d = em.createNativeQuery(dropString.toString()); + Query q = em.createNativeQuery(sqlString.toString()); + d.executeUpdate(); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java new file mode 100644 index 0000000000..e6e71d5cf0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-56232ff7efe285afc4a2893127e9b8339f272b90/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java @@ -0,0 +1,95 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestFunctionsHSQLDB { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private static DataSource ds; + + @BeforeClass + public static void setupClass() { + + Map properties = new HashMap(); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + + properties.put(ENTITY_MANAGER_DATA_SOURCE, ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + private EntityManager em; + + private CriteriaBuilder cb; + + @Before + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + // @Ignore + @Test + public void TestScalarFunctionsWhere() { + CreateUDFHSQLDB(); + + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + count.multiselect(adminDiv); + + count.where(cb.and(cb.greaterThan( + // + cb.function("PopulationDensity", Integer.class, adminDiv.get("area"), adminDiv.get("population")), + new Integer(60))), cb.equal(adminDiv.get("countryCode"), cb.literal("BEL"))); + // cb.literal + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + assertNotNull(act); + tq.getFirstResult(); + } + + private void CreateUDFHSQLDB() { + EntityTransaction t = em.getTransaction(); + + // StringBuffer dropString = new StringBuffer("DROP FUNCTION PopulationDensity"); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("CREATE FUNCTION PopulationDensity (area INT, population BIGINT ) "); + sqlString.append("RETURNS INT "); + sqlString.append("IF area <= 0 THEN RETURN 0;"); + sqlString.append("ELSE RETURN population / area; "); + sqlString.append("END IF"); + + t.begin(); + // Query d = em.createNativeQuery(dropString.toString()); + Query q = em.createNativeQuery(sqlString.toString()); + // d.executeUpdate(); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.json b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.json new file mode 100644 index 0000000000..0f0c8b8284 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87.json @@ -0,0 +1 @@ +{"parentCommitId":"56232ff7efe285afc4a2893127e9b8339f272b90","currentCommitId":"5e77141293d32b015a92e48d099195840f2b2e87","filesBefore":["jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java"],"filesCurrent":["jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/testobjects/ExampleJavaFunctionsReturnsStream.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPADefaultDatabaseProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPA_HSQLDB_DatabaseProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["jpa/odata-jpa-test/src/main/java/com/sap","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-processor/src/test/java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm","jpa/odata-jpa-test/src/test/java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa","jpa/odata-jpa-processor/src/test/java/com/sap/olingo","jpa/odata-jpa-processor/src","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa","jpa/odata-jpa-test/src/test/java/com/sap","jpa/odata-jpa-metadata","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-test/src/test/java/com","jpa/odata-jpa-test/src/main","jpa/odata-jpa-metadata/src/test/java","jpa/odata-jpa-processor/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception","jpa/odata-jpa-test","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test","jpa/odata-jpa-metadata/src/test/java/com","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core","jpa/odata-jpa-processor","jpa/odata-jpa-test/src/main/java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-metadata/src","jpa/odata-jpa-test/src","jpa/odata-jpa-test/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa","jpa","jpa/odata-jpa-processor/src/test/java/com","jpa/odata-jpa-test/src/main/java/com","jpa/odata-jpa-metadata/src/test/java/com/sap","jpa/odata-jpa-test/src/main/java/com/sap/olingo","jpa/odata-jpa-metadata/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor","jpa/odata-jpa-processor/src/test/java/com/sap","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example","jpa/odata-jpa-test/src/test/java/com/sap/olingo","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util"],"repositoryDirectoriesCurrent":["jpa/odata-jpa-test/src/main/java/com/sap","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/testobjects","jpa/odata-jpa-processor/src/test/java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm","jpa/odata-jpa-test/src/test/java","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa","jpa/odata-jpa-processor/src/test/java/com/sap/olingo","jpa/odata-jpa-processor/src","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa","jpa/odata-jpa-test/src/test/java/com/sap","jpa/odata-jpa-metadata","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-test/src/test/java/com","jpa/odata-jpa-test/src/main","jpa/odata-jpa-metadata/src/test/java","jpa/odata-jpa-processor/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception","jpa/odata-jpa-test","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test","jpa/odata-jpa-metadata/src/test/java/com","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel","jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core","jpa/odata-jpa-processor","jpa/odata-jpa-test/src/main/java","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor","jpa/odata-jpa-metadata/src","jpa/odata-jpa-test/src","jpa/odata-jpa-test/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa","jpa","jpa/odata-jpa-processor/src/test/java/com","jpa/odata-jpa-test/src/main/java/com","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database","jpa/odata-jpa-metadata/src/test/java/com/sap","jpa/odata-jpa-test/src/main/java/com/sap/olingo","jpa/odata-jpa-metadata/src/test","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor","jpa/odata-jpa-processor/src/test/java/com/sap","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example","jpa/odata-jpa-test/src/test/java/com/sap/olingo","jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api","jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter","jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java new file mode 100644 index 0000000000..448105698c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestAnnotationPOJO.java @@ -0,0 +1,57 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +public class TestAnnotationPOJO { + private String terms = + "" + + "" + + "" + + "" + + "" + + " " + + " " + + "Terms describing monetary amounts and measured quantities " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "" + + ""; + + @Test + public void TestSimpleXMLConverted() throws JsonParseException, JsonMappingException, IOException { + JacksonXmlModule module = new JacksonXmlModule(); + module.setDefaultUseWrapper(false); + XmlMapper xmlMapper = new XmlMapper(module); + + Edmx act = xmlMapper.readValue(terms, Edmx.class); + assertNotNull(act.getDataService()); + + Schema[] actSchemas = act.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + + List actTerms = actSchemas[0].getTerms(); + assertEquals(3, actTerms.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java new file mode 100644 index 0000000000..7629976745 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestSchemaReader.java @@ -0,0 +1,92 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class TestSchemaReader { + private SchemaReader cut; + + @BeforeEach + public void setup() { + cut = new SchemaReader(); + } + + @Test + public void TestGetNamespaceFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals("Org.OData.Core.V1", schema.getNamespace()); + } + + @Test + public void TestGetAliasFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals("Core", schema.getAlias()); + } + + @Test + public void TestGetTermsFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(15, schema.getTerms().size()); + } + + @Test + public void TestGetTypeDefinitionFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(1, schema.getTypeDefinitions().size()); + assertNotNull(schema.getTypeDefinition("Tag")); + assertEquals("Edm.Boolean", schema.getTypeDefinition("Tag").getUnderlyingType()); + } + + @Test + public void TestGetEnumSchemaFromPath() throws IOException, ODataJPAModelException { + Map act; + act = cut.getSchemas("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + CsdlSchema schema = act.get("Org.OData.Core.V1"); + assertEquals(1, schema.getEnumTypes().size()); + assertNotNull(schema.getEnumType("Permission")); + assertEquals(3, schema.getEnumType("Permission").getMembers().size()); + assertEquals("3", schema.getEnumType("Permission").getMember("ReadWrite").getValue()); + } + + @Test + public void TestThrowsExceptionOnUnknownPath() throws IOException, ODataJPAModelException { + assertThrows(ODataJPAModelException.class, () -> { + cut.getSchemas("annotations/Org.OData.Core.V2.xml"); + }); + } + + @Test + public void TestThrowsExceptionOnEmptyXML() throws IOException, ODataJPAModelException { + + assertThrows(IOException.class, () -> { + cut.getSchemas("annotations/empty.xml"); + }); + } + +// csdlSchema.setEnumTypes(asEnumTypes()); +// csdlSchema.setComplexTypes(asComplexTypes()); +// csdlSchema.setTypeDefinitions(asTypeDefinitions()); +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java new file mode 100644 index 0000000000..bd14bdbeff --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/annotation/TestTermReader.java @@ -0,0 +1,95 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.annotation; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.provider.CsdlTerm; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; + +public class TestTermReader { + private TermReader cut; + + @BeforeEach + public void setup() { + cut = new TermReader(); + } + + @Test + public void TestReadFromResource() throws JsonParseException, JsonMappingException, IOException { + Edmx actEdmx = cut.readFromResource("annotations/Org.OData.Measures.V1.xml"); + assertNotNull(actEdmx); + assertNotNull(actEdmx.getDataService()); + + Schema[] actSchemas = actEdmx.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + assertEquals("Org.OData.Measures.V1", actSchemas[0].getNamespace()); + } + + @Test + public void TestGetTermsOneSchemaFromPath() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + Map terms = act.get("Org.OData.Core.V1"); + assertEquals(15, terms.size()); + } + + @Test + public void TestGetAppliesTo() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.OData.Core.V1.xml"); + assertNotNull(act.get("Org.OData.Core.V1")); + Map terms = act.get("Org.OData.Core.V1"); + CsdlTerm term = terms.get("IsLanguageDependent"); + assertEquals(2, term.getAppliesTo().size()); + assertTrue("Term".equals(term.getAppliesTo().get(0)) || "Term".equals(term.getAppliesTo().get(1))); + assertTrue("Property".equals(term.getAppliesTo().get(0)) || "Property".equals(term.getAppliesTo().get(1))); + } + + @Test + public void TestGetTermsTwoSchemaFromPath() throws JsonParseException, JsonMappingException, IOException { + Map> act; + act = cut.getTerms("annotations/Org.Olingo.Test.V1.xml"); + assertNotNull(act.get("Org.OData.Measures.V1")); + assertNotNull(act.get("Org.OData.Capabilities.V1")); + } + + // TODO This test may not run because of proxy setting problems!! -> find alternative for Integration tests + @Disabled + @Test + public void TestReadFromURI() throws URISyntaxException, JsonParseException, JsonMappingException, + MalformedURLException, IOException { + URI uri = new URI("http://docs.oasis-open.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"); + Edmx actEdmx = cut.readFromURI(uri); + assertNotNull(actEdmx); + assertNotNull(actEdmx.getDataService()); + + Schema[] actSchemas = actEdmx.getDataService().getSchemas(); + assertEquals(1, actSchemas.length); + assertEquals("Org.OData.Core.V1", actSchemas[0].getNamespace()); + } + + // TODO This test may not run because of proxy setting problems!! -> find alternative for Integration tests + @Disabled + @Test + public void TestGetTermsOneSchemaFromURI() throws URISyntaxException, JsonParseException, JsonMappingException, + MalformedURLException, IOException { + URI uri = new URI("http://docs.oasis-open.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"); + Map> act; + act = cut.getTerms(uri); + assertNotNull(act.get("Org.OData.Core.V1")); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java new file mode 100644 index 0000000000..47adb235b2 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAMessageTextBuffer.java @@ -0,0 +1,128 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Locale; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration; + +public class TestODataJPAMessageTextBuffer { + private static String BUNDLE_NAME = "test-i18n"; + private ODataJPAMessageTextBuffer cut; + + @BeforeEach + public void setup() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME); + } + + @Test + public void checkDefaultLocale() { + assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage()); + } + + @Test + public void checkSetLocaleGerman() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY); + assertEquals("de", cut.getLocale().getLanguage()); + } + + @Test + public void checkSetLocaleReset() { + // Set first to German + checkSetLocaleGerman(); + // Then reset to default + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME); + assertEquals(ODataJPAMessageTextBuffer.DEFAULT_LOCALE.getLanguage(), cut.getLocale().getLanguage()); + } + + @Test + public void checkGetDefaultLocaleText() { + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkGetGermanText() { + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, Locale.GERMANY); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + // %1$s + @Test + public void checkGetTextWithParameter() { + String act = cut.getText(this, "SECOND_MESSAGE", "Hugo", "Willi"); + assertEquals("Hugo looks for Willi", act); + } + + @Test + public void checkSetLocalesNull() { + Enumeration locales = null; + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesRestDefaultWithNull() { + // First set to German + checkSetLocaleGerman(); + // Then reset default + Enumeration locales = null; + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesRestDefaultWithEmpty() { + // First set to German + checkSetLocaleGerman(); + // Then reset default + Enumeration locales = new LocaleEnumeration(new ArrayList()); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } + + @Test + public void checkSetLocalesFirstMatches() { + + ArrayList localesList = new ArrayList<>(); + localesList.add(Locale.GERMAN); + localesList.add(Locale.CANADA_FRENCH); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + @Test + public void checkSetLocalesSecondMatches() { + + ArrayList localesList = new ArrayList<>(); + localesList.add(Locale.CANADA_FRENCH); + localesList.add(Locale.GERMAN); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("Ein deutscher Text", act); + } + + @Test + public void checkSetLocalesNonMatches() { + + ArrayList localesList = new ArrayList<>(); + localesList.add(Locale.CANADA_FRENCH); + localesList.add(Locale.SIMPLIFIED_CHINESE); + Enumeration locales = new LocaleEnumeration(localesList); + cut = new ODataJPAMessageTextBuffer(BUNDLE_NAME, locales); + String act = cut.getText(this, "FIRST_MESSAGE"); + assertEquals("An English message", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java new file mode 100644 index 0000000000..86537f89b1 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/exception/TestODataJPAModelException.java @@ -0,0 +1,162 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.LocaleEnumeration; + +public class TestODataJPAModelException { + private static String BUNDLE_NAME = "test-i18n"; + + @Test + public void checkTextInDefaultLocale() { + try { + RaiseExeption(); + } catch (ODataJPAException e) { + assertEquals("An English message", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextInGerman() { + try { + ArrayList localesList = new ArrayList<>(); + localesList.add(Locale.GERMAN); + Enumeration locales = new LocaleEnumeration(localesList); + TestException.setLocales(locales); + RaiseExeption(); + } catch (ODataJPAException e) { + assertEquals("Ein deutscher Text", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextInDefaultLocaleWithParameter() { + try { + RaiseExeptionParam(); + } catch (ODataJPAException e) { + assertEquals("Willi looks for Hugo", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextOnlyCause() { + try { + RaiseExeptionCause(); + } catch (ODataJPAException e) { + assertEquals("Test text from cause", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextIdAndCause() { + try { + RaiseExeptionIDCause(); + } catch (ODataJPAException e) { + assertEquals("An English message", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextIdAndCauseAndParameter() { + try { + RaiseExeptionIDCause("Willi", "Hugo"); + } catch (ODataJPAException e) { + assertEquals("Willi looks for Hugo", e.getMessage()); + return; + } + fail(); + } + + @Test + public void checkTextNullId() { + try { + RaiseEmptyIDExeption(); + } catch (ODataJPAException e) { + assertEquals("No message text found", e.getMessage()); + return; + } + fail(); + } + + private void RaiseExeptionIDCause(String... params) throws TestException { + try { + raiseNullPointer(); + } catch (NullPointerException e) { + if (params.length == 0) + throw new TestException("FIRST_MESSAGE", e); + else + throw new TestException("SECOND_MESSAGE", e, params); + } + } + + private void RaiseExeptionCause() throws ODataJPAException { + try { + raiseNullPointer(); + } catch (NullPointerException e) { + throw new TestException(e); + } + } + + private void raiseNullPointer() throws NullPointerException { + throw new NullPointerException("Test text from cause"); + } + + private void RaiseExeptionParam() throws ODataJPAException { + throw new TestException("SECOND_MESSAGE", "Willi", "Hugo"); + } + + private void RaiseExeption() throws ODataJPAException { + throw new TestException("FIRST_MESSAGE"); + } + + private void RaiseEmptyIDExeption() throws ODataJPAException { + throw new TestException(""); + } + + private class TestException extends ODataJPAException { + + private static final long serialVersionUID = 1L; + + public TestException(String id) { + super(id); + } + + public TestException(String id, String... params) { + super(id, params); + } + + public TestException(Throwable e) { + super(e); + } + + public TestException(String id, Throwable e) { + super(id, e); + } + + public TestException(String id, Throwable e, String[] params) { + super(id, e, params); + } + + @Override + protected String getBundleName() { + return BUNDLE_NAME; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java new file mode 100644 index 0000000000..e8241bd360 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateActionFactory.java @@ -0,0 +1,74 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoActions; + +public class TestIntermediateActionFactory extends TestMappingRoot { + private TestHelper helper; + + private Reflections reflections; + private IntermediateActionFactory cut; + private Set> javaActions; + + @BeforeEach + public void setUp() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + + reflections = mock(Reflections.class); + cut = new IntermediateActionFactory(); + javaActions = new HashSet<>(); + when(reflections.getSubTypesOf(ODataAction.class)).thenReturn(javaActions); + } + + @Test + public void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException { + Reflections r = null; + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), r, helper.schema)); + } + + @Test + public void checkReturnEmptyMapIfNoJavaFunctionsFound() throws ODataJPAModelException { + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), reflections, helper.schema)); + } + + @Test + public void checkReturnMapWithOneIfOneJavaFunctionsFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaOneAction.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(1, act.size()); + } + + @Test + public void checkReturnMapWithTwoIfTwoJavaFunctionsFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaTwoActions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(2, act.size()); + } + + @Test + public void checkReturnMapWithWithJavaFunctionsFromTwoClassesFound() throws ODataJPAModelException { + javaActions.add(ExampleJavaOneAction.class); + javaActions.add(ExampleJavaTwoActions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(3, act.size()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java new file mode 100644 index 0000000000..7e9faabe40 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateCollectionProperty.java @@ -0,0 +1,160 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import javax.persistence.metamodel.ManagedType; +import javax.persistence.metamodel.PluralAttribute; +import javax.persistence.metamodel.Type.PersistenceType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateCollectionProperty extends TestMappingRoot { + private IntermediateCollectionProperty cut; + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + private JPAEdmNameBuilder nameBuilder; + private PluralAttribute jpaAttribute; + private ManagedType managedType; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + jpaAttribute = mock(PluralAttribute.class); + managedType = mock(ManagedType.class); + } + + @SuppressWarnings("unchecked") + @Test + public void checkSimpleCollectionPropertyType() throws ODataJPAModelException { + when(jpaAttribute.getName()).thenReturn("Text"); + @SuppressWarnings("rawtypes") + javax.persistence.metamodel.Type type = mock(javax.persistence.metamodel.Type.class); + when(type.getPersistenceType()).thenReturn(PersistenceType.BASIC); + when(type.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + when(jpaAttribute.getElementType()).thenReturn(type); + when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer>() { + @Override + public ManagedType answer(InvocationOnMock invocation) throws Throwable { + return managedType; + } + }); + when(managedType.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Person.class; + } + }); + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return List.class; + } + }); + cut = new IntermediateCollectionProperty(nameBuilder, jpaAttribute, helper.schema, helper.schema.getEntityType( + Organization.class)); + assertEquals("Edm.String", cut.getEdmItem().getType()); + assertEquals(String.class, cut.getType()); + } + + @Test + public void checkGetProptertyComplexType() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + assertEquals(PUNIT_NAME + ".InhouseAddress", property.getEdmItem().getType()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyDBFieldName() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Organization.class), "comment"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class)); + assertEquals("\"Text\"", property.getDBFieldName()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + + IntermediateSimpleProperty.setPostProcessor(processor); + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Organization.class), "comment"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Organization.class)); + property.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(property, ORG_CANONICAL_NAME); + } + + @Test + public void checkGetPropertyReturnsAnnotation() throws ODataJPAModelException { + + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + Person.class), "inhouseAddress"); + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(Person.class)); + + List annotations = property.getEdmItem().getAnnotations(); + assertEquals(1, property.getEdmItem().getAnnotations().size()); + assertTrue(annotations.get(0).getExpression().isConstant()); + } + + @Test + public void checkGetDeepComplexPropertyReturnsExternalName() throws ODataJPAModelException { + + final IntermediateStructuredType st = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getComplexType("CollectionSecondLevelComplex"), helper.schema); + for (final JPACollectionAttribute collection : st.getDeclaredCollectionAttributes()) { + if (collection.getInternalName().equals("comment")) { + assertEquals("Comment", collection.asAssociation().getAlias()); + } + } + + final IntermediateStructuredType stst = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getComplexType("CollectionFirstLevelComplex"), helper.schema); + for (final JPAPath collection : stst.getCollectionAttributesPath()) { + if (collection.getLeaf().getInternalName().equals("comment")) { + assertEquals("SecondLevel/Comment", collection.getAlias()); + } + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java new file mode 100644 index 0000000000..e17dad0dec --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateComplexType.java @@ -0,0 +1,265 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EmbeddableType; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; + +public class TestIntermediateComplexType extends TestMappingRoot { + private Set> etList; + private IntermediateSchema schema; + + @BeforeEach + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + etList = emf.getMetamodel().getEmbeddables(); + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), mock(Reflections.class)); + + } + + @Test + public void checkComplexTypeCanBeCreated() throws ODataJPAModelException { + + new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType("CommunicationData"), schema); + } + + private EmbeddableType getEmbeddedableType(String typeName) { + for (EmbeddableType embeddableType : etList) { + if (embeddableType.getJavaType().getSimpleName().equals(typeName)) { + return embeddableType; + } + } + return null; + } + + @Test + public void checkGetAllProperties() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals(4, ct.getEdmItem().getProperties().size(), "Wrong number of entities"); + } + + @Test + public void checkGetPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertNotNull(ct.getEdmItem().getProperty("LandlinePhoneNumber")); + } + + @Test + public void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals(ct.getEdmItem().getProperty("LandlinePhoneNumber").getName(), "LandlinePhoneNumber"); + } + + @Test + public void checkGetPropertyIsNullable() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + // In case nullable = true, nullable is not past to $metadata, as this is the default + assertTrue(ct.getEdmItem().getProperty("POBox").isNullable()); + } + + @Test + public void checkGetAllNaviProperties() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals(1, ct.getEdmItem().getNavigationProperties().size(), "Wrong number of entities"); + } + + @Test + public void checkGetNaviPropertyByNameNotNull() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName()); + } + + @Test + public void checkGetNaviPropertyByNameRightEntity() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals("AdministrativeDivision", ct.getEdmItem().getNavigationProperty("AdministrativeDivision").getName()); + } + + @Test + public void checkGetPropertiesSkipIgnored() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "CommunicationData"), schema); + assertEquals(3, ct.getEdmItem().getProperties().size(), "Wrong number of entities"); + } + + @Test + public void checkGetDescriptionPropertyManyToOne() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getProperty("CountryName")); + } + + @Test + public void checkGetDescriptionPropertyManyToMany() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertNotNull(ct.getEdmItem().getProperty("RegionName")); + } + + @Test + public void checkDescriptionPropertyType() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + ct.getEdmItem(); + assertTrue(ct.getProperty("countryName") instanceof IntermediateDescriptionProperty); + } + + @Test + public void checkGetPropertyOfNestedComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotNull(ct.getPath("Created/By")); + } + + @Test + public void checkGetPropertyDBName() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "PostalAddressData"), schema); + assertEquals("\"Address.PostOfficeBox\"", ct.getPath("POBox").getDBFieldName()); + } + + @Test + public void checkGetPropertyDBNameOfNestedComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertEquals("\"CreatedBy\"", ct.getPath("Created/By").getDBFieldName()); + } + + @Test + public void checkGetPropertyWithComplexType() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotNull(ct.getEdmItem().getProperty("Created")); + } + + @Test + public void checkGetPropertiesWithSameComplexTypeNotEqual() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AdministrativeInformation"), schema); + assertNotEquals(ct.getEdmItem().getProperty("Created"), ct.getEdmItem().getProperty("Updated")); + assertNotEquals(ct.getProperty("created"), ct.getProperty("updated")); + } + + @Disabled + @Test + public void checkGetPropertyWithEnumerationType() { + + } + + @Test + public void checkGetProptertyIgnoreTrue() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "DummyEmbeddedToIgnore"), schema); + assertTrue(ct.ignore()); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "ChangeInformation"), schema); + assertFalse(ct.ignore()); + } + + @Test + public void checkOneSimpleProtectedProperty() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "InhouseAddressWithProtection"), schema); + List act = ct.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Building", act.get(0).getAttribute().getExternalName()); + assertEquals("BuildingNumber", act.get(0).getClaimName()); + } + + @Test + public void checkOneComplexProtectedPropertyDeep() throws ODataJPAModelException { + IntermediateComplexType ct = new IntermediateComplexType(new JPAEdmNameBuilder(PUNIT_NAME), getEmbeddedableType( + "AddressDeepProtected"), schema); + List act = ct.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Building", act.get(0).getAttribute().getExternalName()); + assertEquals("BuildingNumber", act.get(0).getClaimName()); + assertEquals(2, act.get(0).getPath().getPath().size()); + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(COMM_CANONICAL_NAME)) { + if (property.getInternalName().equals("landlinePhoneNumber")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)) { + if (property.getInternalName().equals("countryName")) { + property.setIgnore(false); + } + } + } + + @Override + public void provideReferences(IntermediateReferenceList references) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java new file mode 100644 index 0000000000..770a7acdfd --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateContainer.java @@ -0,0 +1,308 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; +import org.apache.olingo.commons.api.edm.provider.CsdlFunctionImport; +import org.apache.olingo.commons.api.edm.provider.CsdlNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.scanners.TypeAnnotationsScanner; +import org.reflections.util.ConfigurationBuilder; +import org.reflections.util.FilterBuilder; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityContainerAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateContainer extends TestMappingRoot { + private static final String PACKAGE1 = "com.sap.olingo.jpa.metadata.core.edm.mapper.impl"; + private static final String PACKAGE2 = "com.sap.olingo.jpa.processor.core.testmodel"; + private HashMap schemas = new HashMap<>(); + private Set> etList; + private IntermediateSchema schema; + + @BeforeEach + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + Reflections r = + new Reflections( + new ConfigurationBuilder() + .forPackages(PACKAGE1, PACKAGE2) + .filterInputsBy(new FilterBuilder().includePackage(PACKAGE1, PACKAGE2)) + .setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner())); + + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + etList = emf.getMetamodel().getEntities(); + schemas.put(PUNIT_NAME, schema); + } + + @Test + public void checkContainerCanBeCreated() throws ODataJPAModelException { + + new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + } + + @Test + public void checkGetName() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + assertEquals("ComSapOlingoJpaContainer", container.getExternalName()); + } + + @Test + public void checkGetNoEntitySets() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + assertEquals(TestDataConstants.NO_ENTITY_SETS, container.getEdmItem().getEntitySets().size()); + } + + @Test + public void checkGetEntitySetName() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) return; + } + fail(); + } + + @Test + public void checkGetEntitySetType() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + assertEquals(new JPAEdmNameBuilder(PUNIT_NAME).buildFQN("BusinessPartner"), entitySet.getTypeFQN()); + return; + } + } + fail(); + } + + @Test + public void checkGetNoNavigationPropertyBindings() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + assertEquals(4, entitySet.getNavigationPropertyBindings().size()); + return; + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPath() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Roles".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsTarget() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Roles".equals(binding.getPath())) { + assertEquals("BusinessPartnerRoles", binding.getTarget()); + return; + } + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPathComplexType() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("Address/AdministrativeDivision".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNavigationPropertyBindingsPathComplexTypeNested() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List entitySets = container.getEdmItem().getEntitySets(); + for (CsdlEntitySet entitySet : entitySets) { + if (entitySet.getName().equals("BusinessPartners")) { + for (CsdlNavigationPropertyBinding binding : entitySet.getNavigationPropertyBindings()) { + if ("AdministrativeInformation/Created/User".equals(binding.getPath())) + return; + } + } + } + fail(); + } + + @Test + public void checkGetNoFunctionImportIfBound() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("CountRoles")) { + fail("Bound function must not generate a function import"); + } + } + } + + @Test + public void checkGetNoFunctionImportIfUnBoundHasImportFalse() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("max")) { + fail("UnBound function must not generate a function import is not annotated"); + } + } + } + + @Test + public void checkGetNoFunctionImportForJavaBasedFunction() throws ODataJPAModelException { + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if ("Sum".equals(funcImport.getName())) + return; + System.out.println(funcImport.getName()); + } + fail("Import not found"); + } + + @Test + public void checkGetFunctionImportIfUnBoundHasImportTrue() throws ODataJPAModelException { + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + List funcImports = container.getEdmItem().getFunctionImports(); + for (CsdlFunctionImport funcImport : funcImports) { + if (funcImport.getName().equals("Olingo V4 ")) { + fail("UnBound function must be generate a function import is annotated"); + } + } + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore()); + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + List act = container.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Capabilities.AsynchronousRequestsSupported", act.get(0).getTerm()); + } + + @Test + public void checkReturnEntitySetBasedOnInternalEntityType() throws ODataJPAModelException { + + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + + IntermediateEntityContainer container = new IntermediateEntityContainer(new JPAEdmNameBuilder(PUNIT_NAME), schemas); + + JPAElement act = container.getEntitySet(et); + assertNotNull(act); + assertEquals("BestOrganizations", act.getExternalName()); + + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntityContainer(IntermediateEntityContainerAccess container) { + + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false"); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(mimeType); + annotation.setTerm("Capabilities.AsynchronousRequestsSupported"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + container.addAnnotations(annotations); + } + } + + private EntityType getEntityType(String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java new file mode 100644 index 0000000000..58fb6e51b7 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDataBaseFunction.java @@ -0,0 +1,252 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlParameter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AssertCollection; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.ChangeInformation; +import com.sap.olingo.jpa.processor.core.testmodel.DateConverter; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateDataBaseFunction extends TestMappingRoot { + private TestHelper helper; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkByEntityAnnotationCreate() throws ODataJPAModelException { + new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper.getStoredProcedure(helper.getEntityType( + BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + } + + @Test + public void checkByEntityAnnotationGetName() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + assertEquals("CountRoles", func.getEdmItem().getName()); + } + + @Test + public void checkByEntityAnnotationGetFunctionName() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + assertEquals("COUNT_ROLES", func.getUserDefinedFunction()); + } + + @Test + public void checkByEntityAnnotationInputParameterBound() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Key"); + param.setType(new FullQualifiedName("com.sap.olingo.jpa.BusinessPartner")); + param.setNullable(false); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameterBoundCompoundKey() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(AdministrativeDivision.class), "SiblingsBound"), + AdministrativeDivision.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Key"); + param.setType(new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision")); + param.setNullable(false); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameter2() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema); + + List expInput = new ArrayList<>(); + CsdlParameter param = new CsdlParameter(); + param.setName("Number"); + param.setType(EdmPrimitiveTypeKind.Decimal.getFullQualifiedName()); + param.setNullable(false); + param.setPrecision(32); + param.setScale(0); + expInput.add(param); + AssertCollection.assertListEquals(expInput, func.getEdmItem().getParameters(), CsdlParameter.class); + } + + @Test + public void checkByEntityAnnotationInputParameterIsEnumeration() throws ODataJPAModelException { + + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(Person.class), "CheckRights"), BusinessPartner.class, helper.schema); + + assertNotNull(func.getEdmItem().getParameters()); + assertEquals(2, func.getEdmItem().getParameters().size()); + assertEquals(PUNIT_NAME + ".AccessRights", func.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + assertEquals("Edm.Int32", func.getEdmItem().getParameters().get(1).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsEmpty() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationIsBound() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertTrue(func.getEdmItem().isBound()); + assertTrue(func.isBound()); + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkByEntityAnnotationResultParameterSimple() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "IsPrime"), BusinessPartner.class, helper.schema); + + assertEquals(EdmPrimitiveTypeKind.Boolean.getFullQualifiedName().getFullQualifiedNameAsString(), func.getEdmItem() + .getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsEntity() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertEquals(PUNIT_NAME + ".Organization", func.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsCollectionFalse() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertTrue(func.getEdmItem().getReturnType().isCollection()); + + func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getEntityType(BusinessPartner.class), helper.schema).get("IsPrime"); + assertFalse(func.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkByEntityAnnotationResultParameterNotGiven() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure( + helper.getEntityType(BusinessPartner.class), "CountRoles"), BusinessPartner.class, helper.schema); + + assertTrue(func.getEdmItem().getReturnType().isCollection()); + assertEquals(PUNIT_NAME + ".BusinessPartner", func.getEdmItem().getReturnType().getType()); + assertEquals(BusinessPartner.class, func.getResultParameter().getType()); + } + + @Test + public void checkByEntityAnnotationResultParameterIsNullable() throws ODataJPAModelException { + IntermediateFunction func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder( + PUNIT_NAME), helper.getEntityType(Organization.class), helper.schema).get("AllCustomersByABC"); + assertTrue(func.getEdmItem().getReturnType().isNullable()); + + func = new IntermediateFunctionFactory().create(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getEntityType(BusinessPartner.class), helper.schema).get("IsPrime"); + assertFalse(func.getEdmItem().getReturnType().isNullable()); + } + + @Test + public void checkByEntityAnnotationResultParameterEnumerationType() throws ODataJPAModelException { + + IntermediateFunction func = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), helper + .getStoredProcedure(helper.getEntityType(Person.class), "ReturnRights"), BusinessPartner.class, helper.schema); + + assertNotNull(func.getEdmItem().getReturnType()); + assertEquals(PUNIT_NAME + ".AccessRights", func.getEdmItem().getReturnType().getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnTypeEmbedded() throws ODataJPAModelException { + EdmFunction func = mock(EdmFunction.class); + EdmFunction.ReturnType retType = mock(EdmFunction.ReturnType.class); + // EdmFunctionParameter[] params = new EdmFunctionParameter[0]; + when(func.returnType()).thenReturn(retType); + when(func.parameter()).thenReturn(new EdmParameter[0]); + when(retType.type()).thenAnswer(new Answer>() { + + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return ChangeInformation.class; + } + }); + + IntermediateFunction act = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), func, + BusinessPartner.class, helper.schema); + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnTypeUnknown() throws ODataJPAModelException { + EdmFunction func = mock(EdmFunction.class); + EdmFunction.ReturnType retType = mock(EdmFunction.ReturnType.class); + // EdmFunctionParameter[] params = new EdmFunctionParameter[0]; + when(func.returnType()).thenReturn(retType); + when(func.parameter()).thenReturn(new EdmParameter[0]); + when(retType.type()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return DateConverter.class; + } + }); + IntermediateFunction act; + try { + act = new IntermediateDataBaseFunction(new JPAEdmNameBuilder(PUNIT_NAME), func, BusinessPartner.class, + helper.schema); + act.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(ODataJPAModelException.MessageKeys.FUNC_RETURN_TYPE_UNKNOWN.getKey(), e.getId()); + return; + } + fail(); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java new file mode 100644 index 0000000000..155822dc05 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateDescriptionProperty.java @@ -0,0 +1,259 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Member; +import java.util.List; + +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.ManagedType; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmDescriptionAssoziation; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; + +public class TestIntermediateDescriptionProperty extends TestMappingRoot { + private TestHelper helper; + private IntermediateDescriptionProperty cut; + private JPAEdmMetadataPostProcessor processor; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + } + + @Test + public void checkProptertyCanBeCreated() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("PostalAddressData"); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "countryName"); + new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema); + } + + @Test + public void checkGetProptertyNameOneToMany() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals("CountryName", cut.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkGetProptertyNameManyToMany() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "regionName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals("RegionName", cut.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkGetProptertyType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals(EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(), + cut.getEdmItem().getType(), "Wrong type"); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + IntermediatePropertyAccess property = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertTrue(cut.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyMaxLength() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + assertEquals(new Integer(100), cut.getEdmItem().getMaxLength()); + } + + @Test + public void checkWrongPathElementThrowsEcxeption() { + + Attribute jpaAttribute = mock(Attribute.class); + EdmDescriptionAssoziation assoziation = prepareCheckPath(jpaAttribute); + + EdmDescriptionAssoziation.valueAssignment[] valueAssignments = new EdmDescriptionAssoziation.valueAssignment[1]; + EdmDescriptionAssoziation.valueAssignment valueAssignment = mock(EdmDescriptionAssoziation.valueAssignment.class); + valueAssignments[0] = valueAssignment; + when(valueAssignment.attribute()).thenReturn("communicationData/dummy"); + when(assoziation.valueAssignments()).thenReturn(valueAssignments); + + try { + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + cut.getEdmItem(); + } catch (ODataJPAModelException e) { + return; + } + fail(); + } + + @Test + public void checkWrongPathStartThrowsEcxeption() { + + Attribute jpaAttribute = mock(Attribute.class); + EdmDescriptionAssoziation assoziation = prepareCheckPath(jpaAttribute); + + EdmDescriptionAssoziation.valueAssignment[] valueAssignments = new EdmDescriptionAssoziation.valueAssignment[1]; + EdmDescriptionAssoziation.valueAssignment valueAssignment = mock(EdmDescriptionAssoziation.valueAssignment.class); + valueAssignments[0] = valueAssignment; + when(valueAssignment.attribute()).thenReturn("communicationDummy/dummy"); + when(assoziation.valueAssignments()).thenReturn(valueAssignments); + + try { + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + cut.getEdmItem(); + } catch (ODataJPAModelException e) { + return; + } + fail(); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private EdmDescriptionAssoziation prepareCheckPath(Attribute jpaAttribute) { + AnnotatedMember jpaField = mock(AnnotatedMember.class); + ManagedType jpaManagedType = mock(ManagedType.class); + EdmDescriptionAssoziation assoziation = mock(EdmDescriptionAssoziation.class); + + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BusinessPartner.class; + } + }); + when(jpaAttribute.getJavaMember()).thenReturn(jpaField); + when(jpaAttribute.getName()).thenReturn("dummy"); + when(jpaAttribute.getDeclaringType()).thenReturn(jpaManagedType); + when(jpaManagedType.getJavaType()).thenReturn(BusinessPartner.class); + + when(jpaField.getAnnotation(EdmDescriptionAssoziation.class)).thenReturn(assoziation); + + when(assoziation.descriptionAttribute()).thenReturn("country"); + when(assoziation.languageAttribute()).thenReturn("language"); + when(assoziation.localeAttribute()).thenReturn(""); + return assoziation; + } + + @Test + public void checkAnnotations() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), + "locationName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + List annotations = cut.getEdmItem().getAnnotations(); + assertEquals(1, annotations.size()); + assertEquals("Core.IsLanguageDependent", annotations.get(0).getTerm()); + assertEquals(ConstantExpressionType.Bool, annotations.get(0).getExpression().asConstant().getType()); + assertEquals("true", annotations.get(0).getExpression().asConstant().getValue()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + // PostProcessorSpy spy = new PostProcessorSpy(); + IntermediateModelElement.setPostProcessor(processor); + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + + cut.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(cut, ADDR_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + cut = new IntermediateDescriptionProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, + helper.schema); + + assertEquals("CountryDescription", cut.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEmbeddedableType("PostalAddressData"), + "countryName"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("CountryDescription", property.getExternalName(), "Wrong name"); + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADDR_CANONICAL_NAME)) { + if (property.getInternalName().equals("countryName")) { + property.setExternalName("CountryDescription"); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private interface AnnotatedMember extends Member, AnnotatedElement { + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java new file mode 100644 index 0000000000..f0f8db827f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntitySet.java @@ -0,0 +1,148 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.CsdlEntitySet; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntitySetAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; + +public class TestIntermediateEntitySet extends TestMappingRoot { + private IntermediateSchema schema; + private Set> etList; + private JPAEdmNameBuilder namebuilder; + + @BeforeEach + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + etList = emf.getMetamodel().getEntities(); + namebuilder = new JPAEdmNameBuilder(PUNIT_NAME); + schema = new IntermediateSchema(namebuilder, emf.getMetamodel(), r); + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessor()); + IntermediateEntityType et = new IntermediateEntityType(namebuilder, getEntityType( + "AdministrativeDivisionDescription"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + List act = set.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Capabilities.TopSupported", act.get(0).getTerm()); + } + + @Test + public void checkODataEntityTypeDiffers() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + + JPAEntityType odataEt = set.getODataEntityType(); + assertEquals("BusinessPartner", odataEt.getExternalName()); + } + + @Test + public void checkODataEntityTypeSame() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + + JPAEntityType odataEt = set.getODataEntityType(); + assertEquals("Organization", odataEt.getExternalName()); + } + + @Test + public void checkEdmItemContainsODataEntityType() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + CsdlEntitySet act = set.getEdmItem(); + assertEquals(namebuilder.buildFQN("BusinessPartner").getFullQualifiedNameAsString(), act.getType()); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessor()); + IntermediateEntityType et = new IntermediateEntityType(namebuilder, getEntityType("BusinessPartner"), schema); + IntermediateEntitySet set = new IntermediateEntitySet(namebuilder, et); + set.getEdmItem(); // Trigger build of EdmEntitySet + + assertEquals("BusinessPartnerList", set.getExternalName(), "Wrong name"); + } + + private class PostProcessor extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(final IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(final IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(final IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntitySet(final IntermediateEntitySetAccess entitySet) { + + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.Bool, "false"); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(mimeType); + annotation.setTerm("Capabilities.TopSupported"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + entitySet.addAnnotations(annotations); + + if ("BusinessPartners".equals(entitySet.getExternalName())) { + entitySet.setExternalName("BusinessPartnerList"); + } + } + } + + private EntityType getEntityType(final String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java new file mode 100644 index 0000000000..378cc5e92f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEntityType.java @@ -0,0 +1,586 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlAnnotation; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlCollection; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlConstantExpression.ConstantExpressionType; +import org.apache.olingo.commons.api.edm.provider.annotation.CsdlExpression; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateEntityType extends TestMappingRoot { + private Set> etList; + private IntermediateSchema schema; + + @BeforeEach + public void setup() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new DefaultEdmPostProcessor()); + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + etList = emf.getMetamodel().getEntities(); + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + } + + @Test + public void checkEntityTypeCanBeCreated() throws ODataJPAModelException { + + new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType("BusinessPartner"), schema); + } + + @Test + public void checkEntityTypeIgnoreSet() throws ODataJPAModelException { + + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "DummyToBeIgnored"), schema); + et.getEdmItem(); + assertTrue(et.ignore()); + } + + @Test + public void checkGetAllProperties() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals(TestDataConstants.NO_DEC_ATTRIBUTES_BUISNESS_PARTNER, et.getEdmItem() + .getProperties() + .size(), "Wrong number of entities"); + } + + @Test + public void checkGetPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNotNull(et.getEdmItem().getProperty("Type")); + } + + @Test + public void checkGetPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Type", et.getEdmItem().getProperty("Type").getName()); + } + + @Test + public void checkGetPropertyByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("ID", et.getEdmItem().getProperty("ID").getName()); + } + + @Test + public void checkGetPathByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("ID", et.getPath("ID").getLeaf().getExternalName()); + } + + @Test + public void checkGetPathByNameIgnore() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNull(et.getPath("CustomString2")); + } + + @Test + public void checkGetPathByNameIgnoreCompexType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNull(et.getPath("Address/RegionCodePublisher")); + } + + @Test + public void checkGetInheritedAttributeByNameCorrectEntityID() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Person"), schema); + assertEquals("ID", et.getPath("ID").getLeaf().getExternalName()); + } + + @Test + public void checkGetAllNaviProperties() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals(1, et.getEdmItem().getNavigationProperties().size(), "Wrong number of entities"); + } + + @Test + public void checkGetNaviPropertyByNameNotNull() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertNotNull(et.getEdmItem().getNavigationProperty("Roles")); + } + + @Test + public void checkGetNaviPropertyByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Roles", et.getEdmItem().getNavigationProperty("Roles").getName()); + } + + @Test + public void checkGetAssoziationOfComplexTypeByNameCorrectEntity() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Address/AdministrativeDivision", et.getAssociationPath("Address/AdministrativeDivision").getAlias()); + } + + @Test + public void checkGetAssoziationOfComplexTypeByNameJoinColumns() throws ODataJPAModelException { + int actCount = 0; + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + for (JPAOnConditionItem item : et.getAssociationPath("Address/AdministrativeDivision").getJoinColumnsList()) { + if (item.getLeftPath().getAlias().equals("Address/Region")) { + assertTrue(item.getRightPath().getAlias().equals("DivisionCode")); + actCount++; + } + if (item.getLeftPath().getAlias().equals("Address/RegionCodeID")) { + assertTrue(item.getRightPath().getAlias().equals("CodeID")); + actCount++; + } + if (item.getLeftPath().getAlias().equals("Address/RegionCodePublisher")) { + assertTrue(item.getRightPath().getAlias().equals("CodePublisher")); + actCount++; + } + } + assertEquals(3, actCount, "Not all join columns found"); + } + + @Test + public void checkGetPropertiesSkipIgnored() throws ODataJPAModelException { + PostProcessorSetIgnore pPDouble = new PostProcessorSetIgnore(); + IntermediateModelElement.setPostProcessor(pPDouble); + + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals(TestDataConstants.NO_DEC_ATTRIBUTES_BUISNESS_PARTNER - 1, et.getEdmItem() + .getProperties().size(), "Wrong number of entities"); + } + + @Test + public void checkGetIsAbstract() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertTrue(et.getEdmItem().isAbstract()); + } + + @Test + public void checkGetIsNotAbstract() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertFalse(et.getEdmItem().isAbstract()); + } + + @Test + public void checkGetHasBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals(PUNIT_NAME + ".BusinessPartner", et.getEdmItem().getBaseType()); + } + + @Test + public void checkGetKeyProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerRole"), schema); + assertEquals(2, et.getEdmItem().getKey().size(), "Wrong number of key propeties"); + } + + @Test + public void checkGetAllAttributes() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerRole"), schema); + assertEquals(2, et.getPathList().size(), "Wrong number of entities"); + } + + @Test + public void checkGetAllAttributesWithBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + int exp = TestDataConstants.NO_ATTRIBUTES_BUISNESS_PARTNER + + TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + + TestDataConstants.NO_ATTRIBUTES_COMMUNICATION_DATA + + 2 * TestDataConstants.NO_ATTRIBUTES_CHANGE_INFO + + TestDataConstants.NO_ATTRIBUTES_ORGANIZATION; + assertEquals(exp, et.getPathList().size(), "Wrong number of entities"); + } + + @Test + public void checkGetAllAttributesWithBaseTypeFields() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + + assertNotNull(et.getPath("Type")); + assertNotNull(et.getPath("Name1")); + assertNotNull(et.getPath("Address" + JPAPath.PATH_SEPERATOR + "Region")); + assertNotNull(et.getPath("AdministrativeInformation" + JPAPath.PATH_SEPERATOR + + "Created" + JPAPath.PATH_SEPERATOR + "By")); + } + + @Test + public void checkGetAllAttributeIDWithBaseType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals("ID", et.getPath("ID").getAlias()); + } + + @Test + public void checkGetKeyAttributeFromEmbeddedId() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + + assertNotNull(et.getAttribute("codePublisher")); + assertEquals("CodePublisher", et.getAttribute("codePublisher").getExternalName()); + } + + @Test + public void checkGetKeyWithBaseType() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals(1, et.getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(5, et.getEdmItem().getProperties().size()); + } + + @Test + public void checkEmbeddedIdResovedKey() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(4, et.getEdmItem().getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedKeyInternal() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(4, et.getKey().size()); + } + + @Test + public void checkEmbeddedIdResovedPath() throws ODataJPAModelException { + JPAStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(5, et.getPathList().size()); + } + + @Test + public void checkEmbeddedIdResovedPathCodeId() throws ODataJPAModelException { + JPAStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals(2, et.getPath("CodeID").getPath().size()); + } + + @Test + public void checkHasStreamNoProperties() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + assertEquals(2, et.getEdmItem().getProperties().size()); + } + + @Test + public void checkHasStreamTrue() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + assertTrue(et.getEdmItem().hasStream()); + } + + @Test + public void checkHasStreamFalse() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertFalse(et.getEdmItem().hasStream()); + } + + @Test + public void checkHasETagTrue() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertTrue(et.hasEtag()); + } + + @Test + public void checkHasETagTrueIfInherited() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertTrue(et.hasEtag()); + } + + @Test + public void checkHasETagFalse() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivision"), schema); + assertFalse(et.hasEtag()); + } + + @Test + public void checkIgnoreIfAsEntitySet() throws ODataJPAModelException { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BestOrganization"), schema); + assertTrue(et.ignore()); + } + + @Test + public void checkAnnotationSet() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(new PostProcessorSetIgnore()); + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonImage"), schema); + List act = et.getEdmItem().getAnnotations(); + assertEquals(1, act.size()); + assertEquals("Core.AcceptableMediaTypes", act.get(0).getTerm()); + } + + @Test + public void checkGetProptertyByDBFieldName() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartner"), schema); + assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName()); + } + + @Test + public void checkGetProptertyByDBFieldNameFromSuperType() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Organization"), schema); + assertEquals("Type", et.getPropertyByDBField("\"Type\"").getExternalName()); + } + + @Test + public void checkGetProptertyByDBFieldNameFromEmbedded() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "AdministrativeDivisionDescription"), schema); + assertEquals("CodeID", et.getPropertyByDBField("\"CodeID\"").getExternalName()); + } + + @Test + public void checkAllPathContainsComplexCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Collection"), schema); + final List act = et.getPathList(); + + assertEquals(11, act.size()); + assertNotNull(et.getPath("Complex/Address")); + assertTrue(et.getPath("Complex/Address").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "Complex/Address").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(2, actIntermediate.asAssociation().getPath().size()); + + for (JPAPath p : act) { + if (p.getPath().size() > 1 + && p.getPath().get(0).getExternalName().equals("Complex") + && p.getPath().get(1).getExternalName().equals("Address")) { + assertTrue(p.getPath().get(1) instanceof IntermediateCollectionProperty); + final IntermediateCollectionProperty actProperty = (IntermediateCollectionProperty) p.getPath().get(1); + assertNotNull(actProperty.asAssociation()); + assertEquals(et, actProperty.asAssociation().getSourceType()); + break; + } + } + } + + @Test + public void checkAllPathContainsPrimitiveCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "Collection"), schema); + final List act = et.getPathList(); + + assertEquals(11, act.size()); + assertNotNull(et.getPath("Complex/Comment")); + assertTrue(et.getPath("Complex/Comment").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "Complex/Comment").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals("Complex/Comment", actIntermediate.asAssociation().getAlias()); + + for (JPAPath p : act) { + if (p.getPath().size() > 1 + && p.getPath().get(0).getExternalName().equals("Complex") + && p.getPath().get(1).getExternalName().equals("Comment")) { + assertTrue(p.getPath().get(1) instanceof IntermediateCollectionProperty); + final IntermediateCollectionProperty actProperty = (IntermediateCollectionProperty) p.getPath().get(1); + assertNotNull(actProperty.asAssociation()); + assertEquals(et, actProperty.asAssociation().getSourceType()); + break; + } + } + } + + @Test + public void checkAllPathContainsDeepComplexWithPrimitiveCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "CollectionDeep"), schema); + final List act = et.getPathList(); + + assertEquals(8, act.size()); + assertNotNull(et.getPath("FirstLevel/SecondLevel/Comment")); + assertTrue(et.getPath("FirstLevel/SecondLevel/Comment").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "FirstLevel/SecondLevel/Comment").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(3, actIntermediate.asAssociation().getPath().size()); + assertEquals("FirstLevel/SecondLevel/Comment", actIntermediate.asAssociation().getAlias()); + } + + @Test + public void checkAllPathContainsDeepComplexWithComplexCollcetion() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "CollectionDeep"), schema); + + assertNotNull(et.getPath("FirstLevel/SecondLevel/Address")); + assertTrue(et.getPath("FirstLevel/SecondLevel/Address").getLeaf().isCollection()); + final IntermediateCollectionProperty actIntermediate = (IntermediateCollectionProperty) et.getPath( + "FirstLevel/SecondLevel/Address").getLeaf(); + assertTrue(actIntermediate.asAssociation().getSourceType() instanceof JPAEntityType); + assertEquals(3, actIntermediate.asAssociation().getPath().size()); + assertEquals("FirstLevel/SecondLevel/Address", actIntermediate.asAssociation().getAlias()); + for (JPAPath path : et.getPathList()) { + String[] pathElements = path.getAlias().split("/"); + assertEquals(pathElements.length, path.getPath().size()); + } + } + + @Test + public void checkOneSimpleProtectedProperty() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "BusinessPartnerProtected"), schema); + List act = et.getProtections(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("Username", act.get(0).getAttribute().getExternalName()); + assertEquals("UserId", act.get(0).getClaimName()); + } + + @Test + public void checkComplexAndInheritedProtectedProperty() throws ODataJPAModelException { + IntermediateStructuredType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), getEntityType( + "PersonDeepProtected"), schema); + + List act = et.getProtections(); + assertNotNull(act); + assertInherited(act); + assertComplexAnnotated(act, "Creator", "Created"); + assertComplexAnnotated(act, "Updator", "Updated"); + assertComplexDeep(act); + assertEquals(4, act.size()); + } + + private void assertComplexDeep(List act) { + for (final JPAProtectionInfo info : act) { + if (info.getClaimName().equals("BuildingNumber")) { + assertEquals("Building", info.getAttribute().getExternalName()); + assertEquals(3, info.getPath().getPath().size()); + assertEquals("InhouseAddress/InhouseAddress/Building", info.getPath().getAlias()); + return; + } + } + fail("Deep protected complex attribute not found"); + + } + + private void assertComplexAnnotated(List act, final String expClaimName, + final String pathElement) { + for (final JPAProtectionInfo info : act) { + if (info.getClaimName().equals(expClaimName)) { + assertEquals("By", info.getAttribute().getExternalName()); + assertEquals(3, info.getPath().getPath().size()); + assertEquals("ProtectedAdminInfo/" + pathElement + "/By", info.getPath().getAlias()); + return; + } + } + fail("Complex attribute not found for: " + expClaimName); + } + + private void assertInherited(List act) { + for (final JPAProtectionInfo info : act) { + if (info.getAttribute().getExternalName().equals("Username")) { + assertEquals("UserId", info.getClaimName()); + assertEquals(1, info.getPath().getPath().size()); + assertEquals("Username", info.getPath().getAlias()); + return; + } + } + fail("Inherited not found"); + } + + private class PostProcessorSetIgnore extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("communicationData")) { + property.setIgnore(true); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) { + if (entity.getExternalName().equals("PersonImage")) { + List items = new ArrayList<>(); + CsdlCollection exp = new CsdlCollection(); + exp.setItems(items); + CsdlConstantExpression mimeType = new CsdlConstantExpression(ConstantExpressionType.String, "ogg"); + items.add(mimeType); + CsdlAnnotation annotation = new CsdlAnnotation(); + annotation.setExpression(exp); + annotation.setTerm("Core.AcceptableMediaTypes"); + List annotations = new ArrayList<>(); + annotations.add(annotation); + entity.addAnnotations(annotations); + } + } + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private EntityType getEntityType(String typeName) { + for (EntityType entityType : etList) { + if (entityType.getJavaType().getSimpleName().equals(typeName)) { + return entityType; + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java new file mode 100644 index 0000000000..2cd0707952 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateEnumerationType.java @@ -0,0 +1,157 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.DayOfWeek; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.FileAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongMember; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.WrongType; + +public class TestIntermediateEnumerationType extends TestMappingRoot { + + private IntermediateEnumerationType cut; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void checkCsdlEnumTypeAccessable() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertNotNull(cut.getEdmItem()); + } + + @Test + public void checkNameProvided() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("DayOfWeek", cut.getEdmItem().getName()); + } + + @Test + public void checkIsFlagProvidesFalse() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertFalse(cut.getEdmItem().isFlags()); + } + + @Test + public void checkIsFlagProvidesTrue() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertTrue(cut.getEdmItem().isFlags()); + } + + @Test + public void checkUnderlyingTypeIntAsDefault() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals(EdmPrimitiveTypeKind.Int32.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem() + .getUnderlyingType()); + } + + @Test + public void checkUnderlyingTypeFromConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals(EdmPrimitiveTypeKind.Int16.getFullQualifiedName().getFullQualifiedNameAsString(), cut.getEdmItem() + .getUnderlyingType()); + } + + @Test + public void checkReturnsRightNumberOfMember4() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals(4, cut.getEdmItem().getMembers().size()); + } + + @Test + public void checkReturnsRightNumberOfMember7() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals(7, cut.getEdmItem().getMembers().size()); + } + + @Test + public void checkReturnsRightNameForMembersOfDayOfWeek() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("MONDAY", cut.getEdmItem().getMembers().get(0).getName()); + assertEquals("SUNDAY", cut.getEdmItem().getMembers().get(6).getName()); + } + + @Test + public void checkReturnsRightValueForMembersOfDayOfWeek() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + cut.getEdmItem(); + assertEquals("0", cut.getEdmItem().getMembers().get(0).getValue()); + assertEquals("6", cut.getEdmItem().getMembers().get(6).getValue()); + } + + @Test + public void checkReturnsRightNameForMembersOfFileAccess() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals("Read", cut.getEdmItem().getMembers().get(0).getName()); + assertEquals("Delete", cut.getEdmItem().getMembers().get(3).getName()); + } + + @Test + public void checkReturnsRightValueForMembersOfFileAccess() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + cut.getEdmItem(); + assertEquals("1", cut.getEdmItem().getMembers().get(0).getValue()); + assertEquals("8", cut.getEdmItem().getMembers().get(3).getValue()); + } + + @Test + public void checkThrowsErrorOnIsFlagTrueAndNegativeValue() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), WrongMember.class); + assertThrows(ODataJPAModelException.class, () -> { + cut.getEdmItem(); + }); + } + + @Test + public void checkThrowsErrorOnNotSupportedUnderlyingType() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), WrongType.class); + assertThrows(ODataJPAModelException.class, () -> { + cut.getEdmItem(); + }); + } + + @Test + public void checkOrdinalMemberProvidedFromStringWOConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertEquals(DayOfWeek.SUNDAY, cut.enumOf("SUNDAY")); + } + + @Test + public void checkOrdinalMemberProvidedFromNumberWOConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), DayOfWeek.class); + assertEquals(DayOfWeek.TUESDAY, cut.enumOf(1)); + } + + @Test + public void checkOrdinalMemberProvidedFromStringWithConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + assertEquals(FileAccess.Create, cut.enumOf("Create")); + } + + @Test + public void checkOrdinalMemberProvidedFromNumberWithConverter() throws ODataJPAModelException { + cut = new IntermediateEnumerationType(new JPAEdmNameBuilder(PUNIT_NAME), FileAccess.class); + assertEquals(FileAccess.Write, cut.enumOf((short) 2)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java new file mode 100644 index 0000000000..c427cbf1b9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateFunctionFactory.java @@ -0,0 +1,74 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoFunctions; + +public class TestIntermediateFunctionFactory extends TestMappingRoot { + private TestHelper helper; + + private Reflections reflections; + private IntermediateFunctionFactory cut; + private Set> javaFunctions; + + @BeforeEach + public void setUp() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + + reflections = mock(Reflections.class); + cut = new IntermediateFunctionFactory(); + javaFunctions = new HashSet<>(); + when(reflections.getSubTypesOf(ODataFunction.class)).thenReturn(javaFunctions); + } + + @Test + public void checkReturnEmptyMapIfReflectionsNull() throws ODataJPAModelException { + Reflections r = null; + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), r, helper.schema)); + } + + @Test + public void checkReturnEmptyMapIfNoJavaFunctionsFound() throws ODataJPAModelException { + assertNotNull(cut.create(new JPAEdmNameBuilder(PUNIT_NAME), reflections, helper.schema)); + } + + @Test + public void checkReturnMapWithOneIfOneJavaFunctionsFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaOneFunction.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(1, act.size()); + } + + @Test + public void checkReturnMapWithTwoIfTwoJavaFunctionsFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaTwoFunctions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(2, act.size()); + } + + @Test + public void checkReturnMapWithWithJavaFunctionsFromTwoClassesFound() throws ODataJPAModelException { + javaFunctions.add(ExampleJavaOneFunction.class); + javaFunctions.add(ExampleJavaTwoFunctions.class); + Map act = cut.create(new JPAEdmNameBuilder(PUNIT_NAME), + reflections, helper.schema); + assertEquals(3, act.size()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java new file mode 100644 index 0000000000..53ffa603d0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaAction.java @@ -0,0 +1,372 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; + +import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaActions; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor; + +public class TestIntermediateJavaAction extends TestMappingRoot { + private TestHelper helper; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkInternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("unboundWithImport", act.getInternalName()); + } + + @Test + public void checkInternalNameGiven() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("unboundWithImport", act.getInternalName()); + } + + @Test + public void checkExternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertEquals("UnboundWithImport", act.getExternalName()); + } + + @Test + public void checkReturnsFalseForIsBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertFalse(act.getEdmItem().isBound()); + } + + @Test + public void checkReturnsTrueForIsBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnsEntitySetPathForBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithEntitySetPath"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals("Person/Roles", act.getEdmItem().getEntitySetPath()); + } + + @Test + public void checkReturnsGivenEntitySetTypeIfBound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertTrue(act.getEdmItem().isBound()); + assertEquals(PUNIT_NAME + ".Person", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + assertEquals("Edm.Decimal", act.getEdmItem().getParameters().get(1).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkReturnsExternalName() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertEquals("BoundNoImport", act.getEdmItem().getName()); + } + + @Test + public void checkReturnsTrueForHasActionImportIfUnbound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsFalseForHasActionImportIfNotSet() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertFalse(act.hasImport()); + } + + @Test + public void checkReturnsReturnTypeConvertedPrimitiveReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getReturnType()); + assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsReturnTypeNullForVoid() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getEdmItem()); + assertNull(act.getEdmItem().getReturnType()); + } + + @Test + public void checkReturnsReturnTypeEmbeddableType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddable"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEntity"); + + assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration"); + + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsReturnTypeCollectionOfPrimitive() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnCollection"); + + assertEquals("Edm.String", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsReturnTypeCollectionOfEmbeddable() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEmbeddableCollection"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsReturnTypeFacetForNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundReturnFacet"); + assertFalse(act.getEdmItem().getReturnType().isNullable()); + assertEquals(Integer.valueOf(20), act.getEdmItem().getReturnType().getPrecision()); + assertEquals(Integer.valueOf(5), act.getEdmItem().getReturnType().getScale()); + } + + @Test + public void checkReturnsReturnTypeFacetForNonNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNull(act.getEdmItem().getReturnType().getPrecision()); + assertNull(act.getEdmItem().getReturnType().getScale()); + assertNull(act.getEdmItem().getReturnType().getMaxLength()); + } + + @Test + public void checkReturnsReturnTypeFacetForStringsAndGeo() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation"); + + assertEquals(Integer.valueOf(60), act.getEdmItem().getReturnType().getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString()); + } + + @Test + public void checkReturnsParameterConvertPrimitiveTypes() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType()); + assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType()); + } + + @Test + public void checkReturnsParameterFacetForNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundNoImport"); + + assertNotNull(act.getParameter()); + assertEquals(Integer.valueOf(34), act.getParameter().get(1).getPrecision()); + assertEquals(Integer.valueOf(10), act.getParameter().get(1).getScale()); + + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(Integer.valueOf(34), act.getEdmItem().getParameters().get(1).getPrecision()); + assertEquals(Integer.valueOf(10), act.getEdmItem().getParameters().get(1).getScale()); + } + + @Test + public void checkReturnsParameterFacetForNonNumbers() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + + assertNotNull(act.getEdmItem().getParameters()); + assertNull(act.getEdmItem().getParameters().get(1).getPrecision()); + assertNull(act.getEdmItem().getParameters().get(1).getScale()); + assertNull(act.getEdmItem().getParameters().get(1).getMaxLength()); + } + + @Test + public void checkReturnsParameterFacetForStringsAndGeo() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "calculateLocation"); + + assertNotNull(act.getParameter()); + assertEquals(Integer.valueOf(100), act.getParameter().get(0).getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getParameter().get(0).getSrid().getDimension()); + assertEquals("4326", act.getParameter().get(0).getSrid().toString()); + + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(Integer.valueOf(100), act.getEdmItem().getParameters().get(0).getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getParameters().get(0).getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getParameters().get(0).getSrid().toString()); + } + + @Test + public void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnEnumeration"); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkProvidesAllParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + List actParams = act.getParameter(); + assertEquals(2, actParams.size()); + } + + @Test + public void checkProvidesParameterByDeclaired() throws ODataJPAModelException, NoSuchMethodException, + SecurityException { + + Method m = ExampleJavaActions.class.getMethod("unboundWithImport", short.class, int.class); + Parameter[] params = m.getParameters(); + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + assertNotNull(act.getParameter(params[0])); + assertEquals("A", act.getParameter(params[0]).getName()); + assertNotNull(act.getParameter(params[1])); + assertEquals("B", act.getParameter(params[1]).getName()); + } + + @Test + public void checkExceptConstructorWithoutParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "unboundWithImport"); + act.getEdmItem(); + assertNotNull(act.getConstructor()); + } + + @Test + public void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaEmConstructor.class, "mul"); + + assertNotNull(act.getConstructor()); + assertEquals(1, act.getConstructor().getParameterTypes().length); + } + + @Test + public void checkThrowsExcpetionForNonPrimitiveParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorNonPrimitiveParameter"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExceptionIfCollectionAndReturnTypeEmpty() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "returnCollectionWithoutReturnType"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExcpetionOnPrivateConstructor() throws ODataJPAModelException { + assertThrows(ODataJPAModelException.class, () -> { + createAction(ExampleJavaPrivateConstructor.class, "mul"); + }); + } + + @Test + public void checkThrowsExcpetionOnNoConstructorAsSpecified() throws ODataJPAModelException { + assertThrows(ODataJPAModelException.class, () -> { + createAction(ExampleJavaTwoParameterConstructor.class, "mul"); + }); + } + + @Test + public void checkThrowsExcpetionOnIsBoundWithoutEntityTypeParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithOutBindingParameter"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExcpetionOnIsBoundWithoutParameter() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundWithOutParameter"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExcpetionOnIsBoundBindingParameterNotFirst() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "boundBindingParameterSecondParameter"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExcpetionOnEntitySetGivenUnbound() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorUnboundWithEntitySetPath"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkThrowsExcpetionOnEntitySetGivenNoEntityReturnType() throws ODataJPAModelException { + IntermediateJavaAction act = createAction(ExampleJavaActions.class, "errorPrimitiveTypeWithEntitySetPath"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + private IntermediateJavaAction createAction(Class clazz, String method) + throws ODataJPAModelException { + for (Method m : Arrays.asList(clazz.getMethods())) { + EdmAction actionDescribtion = m.getAnnotation(EdmAction.class); + if (actionDescribtion != null && method.equals(m.getName())) { + return new IntermediateJavaAction(new JPAEdmNameBuilder(PUNIT_NAME), actionDescribtion, m, helper.schema); + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java new file mode 100644 index 0000000000..baf7d0130a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateJavaFunction.java @@ -0,0 +1,266 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Method; +import java.util.Arrays; + +import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension; +import org.apache.olingo.commons.api.edm.provider.CsdlReturnType; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaEmConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaFunctions; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaFunctionsReturnsStream; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaOneFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaPrivateConstructor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects.ExampleJavaTwoParameterConstructor; + +public class TestIntermediateJavaFunction extends TestMappingRoot { + private TestHelper helper; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkInternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertEquals("sum", act.getInternalName()); + } + + @Test + public void checkExternalNameEqualMethodName() throws ODataJPAModelException { + IntermediateFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertEquals("Sum", act.getExternalName()); + } + + @Test + public void checkReturnsConvertedPrimitiveReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getReturnType()); + assertEquals("Edm.Int32", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsConvertedPrimitiveParameterTypes() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertNotNull(act.getEdmItem().getParameters()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + assertEquals("Edm.Int16", act.getEdmItem().getParameter("A").getType()); + assertEquals("Edm.Int32", act.getEdmItem().getParameter("B").getType()); + } + + @Test + public void checkThrowsExcpetionForNonPrimitiveParameter() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "errorNonPrimitiveParameter"); + + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkReturnsFalseForIsBound() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertNotNull(act.getEdmItem()); + assertEquals(false, act.getEdmItem().isBound()); + } + + @Test + public void checkReturnsTrueForHasFunctionImport() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaOneFunction.class, "sum"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsAnnotatedName() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertEquals("Add", act.getExternalName()); + } + + @Test + public void checkIgnoresGivenIsBound() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertFalse(act.getEdmItem().isBound()); + assertFalse(act.isBound()); + } + + @Test + public void checkIgnoresGivenHasFunctionImport() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + + assertTrue(act.hasImport()); + } + + @Test + public void checkReturnsEnumerationTypeAsParameter() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType"); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getEdmItem().getParameters().get(0).getTypeFQN() + .getFullQualifiedNameAsString()); + + assertEquals("com.sap.olingo.jpa.AccessRights", act.getParameter("arg0").getTypeFQN() + .getFullQualifiedNameAsString()); + } + + @Test + public void checkIgnoresParameterAsPartFromEdmFunction() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "div"); + + assertNotNull(act.getEdmItem()); + assertEquals(2, act.getEdmItem().getParameters().size()); + assertNotNull(act.getEdmItem().getParameter("A")); + assertNotNull(act.getEdmItem().getParameter("B")); + } + + @Test + public void checkThrowsExceptionIfAnnotatedReturnTypeNEDeclairedType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "errorReturnType"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkReturnsFacetForNumbersOfReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "now"); + assertFalse(act.getEdmItem().getReturnType().isNullable()); + assertEquals(Integer.valueOf(9), act.getEdmItem().getReturnType().getPrecision()); + assertEquals(Integer.valueOf(3), act.getEdmItem().getReturnType().getScale()); + } + + @Test + public void checkReturnsFacetForStringsAndGeoOfReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "determineLocation"); + assertEquals(Integer.valueOf(60), act.getEdmItem().getReturnType().getMaxLength()); + assertEquals(Dimension.GEOGRAPHY, act.getEdmItem().getReturnType().getSrid().getDimension()); + assertEquals("4326", act.getEdmItem().getReturnType().getSrid().toString()); + } + + @Test + public void checkReturnsIsCollectionIfDefinedReturnTypeIsSubclassOfCollection() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnCollection"); + + assertTrue(act.getEdmItem().getReturnType().isCollection()); + assertEquals("Edm.String", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkThrowsExceptionIfCollectionAndReturnTypeEmpty() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, + "returnCollectionWithoutReturnType"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkReturnsEmbeddableTypeAsReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddable"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEmbeddableCollectionTypeAsReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEmbeddableCollection"); + + assertEquals("com.sap.olingo.jpa.ChangeInformation", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkReturnsEntityTypeAsReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEntity"); + assertEquals("com.sap.olingo.jpa.Person", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationTypeAsReturnType() throws ODataJPAModelException { + + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationType"); + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + } + + @Test + public void checkReturnsEnumerationCollectionTypeAsReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "returnEnumerationCollection"); + + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", act.getEdmItem().getReturnType().getType()); + assertTrue(act.getEdmItem().getReturnType().isCollection()); + } + + @Test + public void checkThrowsExcpetionOnNotSupportedReturnType() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "wrongReturnType"); + assertThrows(ODataJPAModelException.class, () -> { + act.getEdmItem(); + }); + } + + @Test + public void checkExceptConstructorWithoutParameter() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctions.class, "sum"); + act.getEdmItem(); + } + + @Test + public void checkExceptConstructorWithEntityManagerParameter() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaEmConstructor.class, "sum"); + act.getEdmItem(); + } + + @Test + public void checkThrowsExcpetionOnPrivateConstructor() throws ODataJPAModelException { + assertThrows(ODataJPAModelException.class, () -> { + createFunction(ExampleJavaPrivateConstructor.class, "sum"); + }); + } + + @Test + public void checkThrowsExcpetionOnNoConstructorAsSpecified() throws ODataJPAModelException { + assertThrows(ODataJPAModelException.class, () -> { + createFunction(ExampleJavaTwoParameterConstructor.class, "sum"); + }); + } + + @Test + public void checkStream() throws ODataJPAModelException { + final IntermediateJavaFunction act = createFunction(ExampleJavaFunctionsReturnsStream.class, "simpleStream"); + final CsdlReturnType actReturn = act.getEdmItem().getReturnType(); + actReturn.getType(); + } + + private IntermediateJavaFunction createFunction(Class clazz, String method) + throws ODataJPAModelException { + for (Method m : Arrays.asList(clazz.getMethods())) { + EdmFunction functionDescribtion = m.getAnnotation(EdmFunction.class); + if (functionDescribtion != null && method.equals(m.getName())) { + return new IntermediateJavaFunction(new JPAEdmNameBuilder(PUNIT_NAME), functionDescribtion, m, helper.schema); + } + } + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java new file mode 100644 index 0000000000..f8c0cc6100 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateNavigationProperty.java @@ -0,0 +1,469 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.EntityType; + +import org.apache.olingo.commons.api.edm.provider.CsdlOnDelete; +import org.apache.olingo.commons.api.edm.provider.CsdlOnDeleteAction; +import org.apache.olingo.commons.api.edm.provider.CsdlReferentialConstraint; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored; +import com.sap.olingo.jpa.processor.core.testmodel.JoinSource; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestIntermediateNavigationProperty extends TestMappingRoot { + private IntermediateSchema schema; + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + @BeforeEach + public void setup() throws ODataJPAModelException { + final Reflections r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class }))); + + schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + } + + @Test + public void checkNaviProptertyCanBeCreated() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), schema.getStructuredType(jpaAttribute), + jpaAttribute, schema); + } + + @Test + public void checkGetName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("Roles", property.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkGetType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals(PUNIT_NAME + ".BusinessPartnerRole", property.getEdmItem().getType(), "Wrong name"); + } + + @Test + public void checkGetIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetIgnoreTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(DummyToBeIgnored.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + assertTrue(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetPropertyOnDelete() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals(CsdlOnDeleteAction.Cascade, property.getEdmItem().getOnDelete().getAction()); + } + + @Test + public void checkGetProptertyFacetsNullableFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + + assertFalse(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsCollectionTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsColletionFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + + assertFalse(property.getEdmItem().isCollection()); + } + + @Test + public void checkGetJoinColumnsSize1BP() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals(1, property.getJoinColumns().size()); + } + + @Test + public void checkGetPartnerAdmin_Parent() throws ODataJPAModelException { + EntityType et = helper.getEntityType(AdministrativeDivision.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "parent"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Children", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerAdmin_Children() throws ODataJPAModelException { + EntityType et = helper.getEntityType(AdministrativeDivision.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "children"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Parent", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerBP_Roles() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("BusinessPartner", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetPartnerRole_BP() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals("Roles", property.getEdmItem().getPartner()); + } + + @Test + public void checkGetJoinColumnFilledCompletely() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartner.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + + IntermediateJoinColumn act = property.getJoinColumns().get(0); + assertEquals("\"BusinessPartnerID\"", act.getName()); + assertEquals("\"ID\"", act.getReferencedColumnName()); + } + + @Test + public void checkGetJoinColumnFilledCompletelyInvert() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + + IntermediateJoinColumn act = property.getJoinColumns().get(0); + assertEquals("\"BusinessPartnerID\"", act.getName()); + assertEquals("\"ID\"", act.getReferencedColumnName()); + } + + @Test + public void checkGetJoinColumnsSize1Roles() throws ODataJPAModelException { + EntityType et = helper.getEntityType(BusinessPartnerRole.class); + + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(et.getJavaType()), jpaAttribute, schema); + assertEquals(1, property.getJoinColumns().size()); + } + + @Test + public void checkGetJoinColumnsSize2() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("PostalAddressData"); + Attribute jpaAttribute = helper.getDeclaredAttribute(et, "administrativeDivision"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getComplexType(et.getJavaType()), jpaAttribute, schema); + List columns = property.getJoinColumns(); + assertEquals(3, columns.size()); + } + + @Test + public void checkGetReferentialConstraintSize() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + assertEquals(1, property.getProperty().getReferentialConstraints().size()); + } + + @Test + public void checkGetReferentialConstraintBuPaRole() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + for (CsdlReferentialConstraint c : constraints) { + assertEquals("ID", c.getProperty()); + assertEquals("BusinessPartnerID", c.getReferencedProperty()); + } + } + + @Test + public void checkGetReferentialConstraintRoleBuPa() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartnerRole.class), + "businessPartner"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartnerRole.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + for (CsdlReferentialConstraint c : constraints) { + assertEquals("BusinessPartnerID", c.getProperty()); + assertEquals("ID", c.getReferencedProperty()); + } + } + + @Test + public void checkGetReferentialConstraintViaEmbeddedId() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "allDescriptions"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema); + List constraints = property.getProperty().getReferentialConstraints(); + + assertEquals(3, constraints.size()); + for (CsdlReferentialConstraint c : constraints) { + assertEquals(c.getReferencedProperty(), c.getProperty()); + } + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + IntermediateModelElement.setPostProcessor(processor); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType( + BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + property.getEdmItem(); + verify(processor, atLeastOnce()).processNavigationProperty(property, BUPA_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("RoleAssignment", property.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(BusinessPartner.class), "roles"); + JPAAssociationAttribute property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getStructuredType(jpaAttribute), jpaAttribute, schema); + + assertEquals("RoleAssignment", property.getExternalName(), "Wrong name"); + } + + @Test + public void checkPostProcessorSetOnDelete() throws ODataJPAModelException { + PostProcessorOneDelete pPDouble = new PostProcessorOneDelete(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "children"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(AdministrativeDivision.class), jpaAttribute, schema); + + assertEquals(CsdlOnDeleteAction.None, property.getProperty().getOnDelete().getAction()); + } + + @Test + public void checkGetJoinTable() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNotNull(property.getJoinTable()); + } + + @Test + public void checkGetJoinTableName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertEquals("\"SupportRelationship\"", property.getJoinTable().getTableName()); + } + + @Test + public void checkGetNullIfNoJoinTableGiven() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(AdministrativeDivision.class), + "parent"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNull(property.getJoinTable()); + } + + @Test + public void checkGetJoinTableJoinColumns() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + } + + @Test + public void checkGetJoinTableEntityType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Person.class), + "supportedOrganizations"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertNotNull(property.getJoinTable().getEntityType()); + } + + @Test + public void checkGetJoinTableJoinColumnsNotMapped() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(JoinSource.class), + "oneToMany"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(JoinSource.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + assertNotNull(property.getJoinTable()); + IntermediateJoinTable act = (IntermediateJoinTable) property.getJoinTable(); + for (JPAOnConditionItem item : act.getJoinColumns()) { + assertNotNull(item.getLeftPath()); + assertNotNull(item.getRightPath()); + } + } + + @Test + public void checkGetJoinTableJoinColumnsMapped() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(Organization.class), + "supportEngineers"); + IntermediateNavigationProperty property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + schema.getEntityType(BusinessPartner.class), jpaAttribute, schema); + + assertFalse(property.getJoinColumns().isEmpty()); + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + BUPA_CANONICAL_NAME)) { + if (property.getInternalName().equals("roles")) { + property.setExternalName("RoleAssignment"); + } + } + } + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + + } + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } + + private class PostProcessorOneDelete extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals(ADMIN_CANONICAL_NAME)) { + if (property.getInternalName().equals("children")) { + CsdlOnDelete oD = new CsdlOnDelete(); + oD.setAction(CsdlOnDeleteAction.None); + property.setOnDelete(oD); + } + } + } + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java new file mode 100644 index 0000000000..7a11e639ce --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateReferences.java @@ -0,0 +1,153 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; + +import java.net.URISyntaxException; +import java.util.List; + +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList.IntermediateReferenceAccess; + +public class TestIntermediateReferences extends TestMappingRoot { + private IntermediateReferences cut; + + @BeforeEach + public void setup() throws ODataJPAModelException { + cut = new IntermediateReferences(); + } + + @Test + public void checkAddOnlyURI() throws ODataJPAModelException, URISyntaxException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Core.V1.xml"; + cut.addReference(uri); + List act = cut.getEdmReferences(); + assertEquals(1, act.size()); + assertEquals(act.get(0).getUri().toString(), uri); + } + + @Test + public void checkAddURIandPath() throws ODataJPAModelException, URISyntaxException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + List act = cut.getEdmReferences(); + assertEquals(1, act.size()); + assertEquals(uri, act.get(0).getUri().toString()); + } + + @Test + public void checkConvertedToEdmx() throws ODataJPAModelException { + JPAServiceDocument serviceDocument; + serviceDocument = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), new PostProcessor(), null); + assertEquals(1, serviceDocument.getReferences().size()); + + EdmxReference ref = serviceDocument.getReferences().get(0); + assertEquals(1, ref.getIncludes().size()); + } + + @Test + public void checkGetOneSchema() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", ""); + + assertEquals(1, cut.getSchemas().size()); + } + + @Test + public void checkGetTwoSchemas() throws ODataJPAModelException { + String uri = "http://org.example/odata/odata/v4.0/os/vocabularies/Org.Olingo.Test.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.Olingo.Test.V1.xml"); + ref.addInclude("Org.Olingo.Test.V1.xml", ""); + + assertEquals(2, cut.getSchemas().size()); + } + + @Test + public void checkGetComplexType() throws ODataJPAModelException { + String uri = "http://org.example/odata/odata/v4.0/os/vocabularies/Org.Olingo.Test.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.Olingo.Test.V1.xml"); + ref.addInclude("Org.Olingo.Test.V1.xml", ""); + + for (CsdlSchema schema : cut.getSchemas()) { + if (schema.getNamespace().equals("Org.OData.Capabilities.V1")) { + assertNotNull(schema.getComplexType("UpdateRestrictionsType")); + return; + } + } + fail(); + } + + @Test + public void checkGetTermByNamespace() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", ""); + FullQualifiedName fqn = new FullQualifiedName("Org.OData.Measures.V1", "ISOCurrency"); + assertNotNull(cut.getTerm(fqn)); + } + + @Test + public void checkGetTermByAlias() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Measures", "ISOCurrency"); + assertNotNull(cut.getTerm(fqn)); + } + + @Test + public void checkReturnNullOnUnknowTerm() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Measures", "Dummy"); + assertNull(cut.getTerm(fqn)); + } + + @Test + public void checkReturnNullOnUnknowNamespace() throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess ref = cut.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + ref.addInclude("Org.OData.Measures.V1", "Measures"); + FullQualifiedName fqn = new FullQualifiedName("Dummy", "ISOCurrency"); + assertNull(cut.getTerm(fqn)); + } + + class PostProcessor extends JPAEdmMetadataPostProcessor { + @Override + public void processNavigationProperty(final IntermediateNavigationPropertyAccess property, + final String jpaManagedTypeClassName) { + + } + + @Override + public void processProperty(final IntermediatePropertyAccess property, final String jpaManagedTypeClassName) { + + } + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + + @Override + public void provideReferences(final IntermediateReferenceList references) throws ODataJPAModelException { + String uri = "http://docs.oasisopen.org/odata/odata/v4.0/os/vocabularies/Org.OData.Measures.V1.xml"; + IntermediateReferenceAccess reference = references.addReference(uri, "annotations/Org.OData.Measures.V1.xml"); + reference.addInclude("Org.OData.Core.V1", "Core"); + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java new file mode 100644 index 0000000000..2cfeaeaf26 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSchema.java @@ -0,0 +1,80 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashSet; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.reflections.Reflections; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmEnumeration; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRights; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; + +public class TestIntermediateSchema extends TestMappingRoot { + private Reflections r; + + @BeforeEach + public void setup() { + r = mock(Reflections.class); + when(r.getTypesAnnotatedWith(EdmEnumeration.class)).thenReturn(new HashSet<>(Arrays.asList(new Class[] { + ABCClassifiaction.class, AccessRights.class }))); + } + + @Test + public void checkSchemaCanBeCreated() throws ODataJPAModelException { + + new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + } + + @Test + public void checkSchemaGetAllEntityTypes() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals(TestDataConstants.NO_ENTITY_TYPES, schema.getEdmItem().getEntityTypes().size(), + "Wrong number of entities"); + } + + @Test + public void checkSchemaGetEntityTypeByNameNotNull() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertNotNull(schema.getEdmItem().getEntityType("BusinessPartner")); + } + + @Test + public void checkSchemaGetEntityTypeByNameRightEntity() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("BusinessPartner", schema.getEdmItem().getEntityType("BusinessPartner").getName()); + } + + @Test + public void checkSchemaGetAllComplexTypes() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + // ChangeInformation,CommunicationData,AdministrativeInformation,PostalAddressData + assertEquals(15, schema.getEdmItem().getComplexTypes().size(), "Wrong number of complex types"); + } + + @Test + public void checkSchemaGetComplexTypeByNameNotNull() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertNotNull(schema.getEdmItem().getComplexType("CommunicationData")); + } + + @Test + public void checkSchemaGetComplexTypeByNameRightEntity() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals("CommunicationData", schema.getEdmItem().getComplexType("CommunicationData").getName()); + } + + @Test + public void checkSchemaGetAllFunctions() throws ODataJPAModelException { + IntermediateSchema schema = new IntermediateSchema(new JPAEdmNameBuilder(PUNIT_NAME), emf.getMetamodel(), r); + assertEquals(10, schema.getEdmItem().getFunctions().size(), "Wrong number of entities"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java new file mode 100644 index 0000000000..3d769742c9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateServiceDocument.java @@ -0,0 +1,83 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmBindingTarget; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.provider.CsdlEntityContainer; +import org.apache.olingo.commons.api.edm.provider.CsdlSchema; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class TestIntermediateServiceDocument extends TestMappingRoot { + + @Test + public void checkServiceDocumentCanBeCreated() throws ODataJPAModelException { + new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + } + + @Test + public void checkServiceDocumentGetSchemaList() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertEquals(1, svc.getEdmSchemas().size(), "Wrong number of schemas"); + } + + @Test + public void checkServiceDocumentGetContainer() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertNotNull(svc.getEdmEntityContainer(), "Entity Container not found"); + } + + @Test + public void checkServiceDocumentGetContainerFromSchema() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + List schemas = svc.getEdmSchemas(); + CsdlSchema schema = schemas.get(0); + assertNotNull(schema.getEntityContainer(), "Entity Container not found"); + } + + @Test + public void checkServiceDocumentGetEntitySetsFromContainer() throws ODataJPAModelException { + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + CsdlEntityContainer container = svc.getEdmEntityContainer(); + assertNotNull(container.getEntitySets(), "Entity Container not found"); + } + + @Test + public void checkHasEtagReturnsTrueOnVersion() throws ODataJPAModelException { + EdmBindingTarget target = mock(EdmBindingTarget.class); + EdmEntityType et = mock(EdmEntityType.class); + when(target.getEntityType()).thenReturn(et); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "BusinessPartner")); + + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, + new String[] { "com.sap.olingo.jpa.processor.core.testmodel" }); + assertTrue(svc.hasETag(target)); + } + + @Test + public void checkHasEtagReturnsFalseWithoutVersion() throws ODataJPAModelException { + EdmBindingTarget target = mock(EdmBindingTarget.class); + EdmEntityType et = mock(EdmEntityType.class); + when(target.getEntityType()).thenReturn(et); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName(PUNIT_NAME, "Country")); + + JPAServiceDocument svc = new IntermediateServiceDocument(PUNIT_NAME, emf.getMetamodel(), null, null); + assertFalse(svc.hasETag(target)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java new file mode 100644 index 0000000000..fb1559e2e2 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateSimpleProperty.java @@ -0,0 +1,587 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Member; +import java.sql.Date; +import java.sql.Timestamp; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.Attribute.PersistentAttributeType; +import javax.persistence.metamodel.EmbeddableType; +import javax.persistence.metamodel.ManagedType; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtectedBy; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmProtections; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateEntityTypeAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateNavigationPropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediatePropertyAccess; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.IntermediateReferenceList; +import com.sap.olingo.jpa.metadata.core.edm.mapper.util.MemberDouble; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerProtected; +import com.sap.olingo.jpa.processor.core.testmodel.Comment; +import com.sap.olingo.jpa.processor.core.testmodel.DummyToBeIgnored; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.testmodel.PersonImage; + +public class TestIntermediateSimpleProperty extends TestMappingRoot { + private TestHelper helper; + private JPAEdmMetadataPostProcessor processor; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + processor = mock(JPAEdmMetadataPostProcessor.class); + } + + @Test + public void checkProptertyCanBeCreated() throws ODataJPAModelException { + EmbeddableType et = helper.getEmbeddedableType("CommunicationData"); + Attribute jpaAttribute = helper.getAttribute(et, "landlinePhoneNumber"); + new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), jpaAttribute, helper.schema); + } + + @Test + public void checkGetProptertyName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("Type", property.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkGetProptertyDBFieldName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("\"Type\"", property.getDBFieldName(), "Wrong name"); + } + + @Test + public void checkGetProptertySimpleType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(EdmPrimitiveTypeKind.String.getFullQualifiedName().getFullQualifiedNameAsString(), + property.getEdmItem().getType(), "Wrong type"); + } + + @Test + public void checkGetProptertyComplexType() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), + "communicationData"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(PUNIT_NAME + ".CommunicationData", property.getEdmItem().getType(), "Wrong type"); + } + + @Test + public void checkGetProptertyEnumTypeWithoutConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("com.sap.olingo.jpa.ABCClassifiaction", property.getEdmItem().getType(), "Wrong type"); + } + + @Test + public void checkGetProptertyEnumTypeWithoutConverterMustNotHaveMapper() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Organization.class), "aBCClass"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMapping()); + } + + @Test + public void checkGetProptertyEnumTypeWithConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "accessRights"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("com.sap.olingo.jpa.AccessRights", property.getEdmItem().getType(), "Wrong type"); + } + + @Test + public void checkGetProptertyIgnoreFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.ignore()); + } + + @Test + public void checkGetProptertyIgnoreTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.ignore()); + } + + @Test + public void checkGetProptertyFacetsNullableTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsNullableTrueComplex() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEmbeddedableType("PostalAddressData"), "POBox"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyFacetsNullableFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.getEdmItem().isNullable()); + } + + @Test + public void checkGetProptertyIsETagTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "eTag"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.isEtag()); + } + + @Test + public void checkGetProptertyIsETagFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertFalse(property.isEtag()); + } + + @Test + public void checkGetProptertyMaxLength() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "type"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(1), property.getEdmItem().getMaxLength()); + } + + @Test + public void checkGetProptertyMaxLengthNullForClob() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getComplexType("DummyEmbeddedToIgnore"), "command"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMaxLength()); + } + + @Test + public void checkGetProptertyPrecisionDecimal() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(16), property.getEdmItem().getPrecision()); + } + + @Test + public void checkGetProptertyScaleDecimal() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customNum1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(5), property.getEdmItem().getScale()); + } + + @Test + public void checkGetProptertyPrecisionTime() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(new Integer(3), property.getEdmItem().getPrecision()); + } + + @Test + public void checkGetProptertyMapper() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNotNull(property.getEdmItem().getMapping()); + assertEquals(Timestamp.class, property.getEdmItem().getMapping().getMappedJavaClass()); + } + + @Test + public void checkGetProptertyMapperWithConverter() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "birthDay"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNotNull(property.getEdmItem().getMapping()); + assertEquals(Date.class, property.getEdmItem().getMapping().getMappedJavaClass()); + } + + @Test + public void checkGetNoProptertyMapperForClob() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Comment.class), "text"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertNull(property.getEdmItem().getMapping()); + } + + @Test + public void checkPostProcessorCalled() throws ODataJPAModelException { + IntermediateSimpleProperty.setPostProcessor(processor); + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "creationDateTime"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + property.getEdmItem(); + verify(processor, atLeastOnce()).processProperty(property, BUPA_CANONICAL_NAME); + } + + @Test + public void checkPostProcessorNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateSimpleProperty.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("ContactPersonName", property.getEdmItem().getName(), "Wrong name"); + } + + @Test + public void checkPostProcessorExternalNameChanged() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartner.class), "customString1"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertEquals("ContactPersonName", property.getExternalName(), "Wrong name"); + } + + @Test + public void checkConverterGetConverterReturned() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "birthDay"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNotNull(property.getConverter()); + } + + @Test + public void checkConverterGetConverterNotReturned() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(Person.class), "customString1"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNull(property.getConverter()); + } + + @Test + public void checkConverterGetConverterNotReturnedDiffernt() throws ODataJPAModelException { + PostProcessorSetName pPDouble = new PostProcessorSetName(); + IntermediateModelElement.setPostProcessor(pPDouble); + + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(DummyToBeIgnored.class), "uuid"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertNull(property.getConverter()); + } + + @Test + public void checkGetProptertyDefaultValue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEmbeddedableType("PostalAddressData"), + "regionCodePublisher"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals("ISO", property.getEdmItem().getDefaultValue()); + } + + @Test + public void checkGetPropertyIsStream() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(PersonImage.class), + "image"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertTrue(property.isStream()); + } + + @Test + public void checkGetTypeBoxedForPrimitive() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class), + "population"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(Long.class, property.getType()); + } + + @Test + public void checkGetTypeBoxed() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(AdministrativeDivision.class), + "area"); + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + assertEquals(Integer.class, property.getType()); + } + + @Test + public void checkThrowsAnExceptionTimestampWithoutPrecision() throws ODataJPAModelException { + // If Precision missing EdmDateTimeOffset.internalValueToString throws an exception => pre-check + final Attribute jpaAttribute = mock(Attribute.class); + final ManagedType jpaManagedType = mock(ManagedType.class); + when(jpaAttribute.getName()).thenReturn("start"); + when(jpaAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.BASIC); + when(jpaAttribute.getDeclaringType()).thenAnswer(new Answer>() { + @Override + public ManagedType answer(InvocationOnMock invocation) throws Throwable { + return jpaManagedType; + } + }); + when(jpaAttribute.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Timestamp.class; + } + }); + when(jpaManagedType.getJavaType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return DummyToBeIgnored.class; + } + }); + + Column column = mock(Column.class); + AnnotatedElement annotations = mock(AnnotatedElement.class, withSettings().extraInterfaces(Member.class)); + when(annotations.getAnnotation(Column.class)).thenReturn(column); + when(jpaAttribute.getJavaMember()).thenReturn((Member) annotations); + when(column.name()).thenReturn("Test"); + + IntermediateSimpleProperty property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, + helper.schema); + + assertThrows(ODataJPAModelException.class, () -> { + property.getEdmItem(); + }); + } + + @Test + public void checkGetProptertyHasProtectionFalse() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), "eTag"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertFalse(property.hasProtection()); + } + + @Test + public void checkGetProptertyHasProtectionTrue() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "username"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertTrue(property.hasProtection()); + } + + @Test + public void checkGetProptertyProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "username"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("Username", actPath.get(0)); + } + + @Test + public void checkGetProptertyNotProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), "eTag"); + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + assertTrue(property.getProtectionClaimNames().isEmpty()); + assertTrue(property.getProtectionPath("Username").isEmpty()); + } + + @Test + public void checkGetComplexProptertyProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtectedBy annotation = Mockito.mock(EdmProtectedBy.class); + when(annotation.name()).thenReturn("UserId"); + when(annotation.path()).thenReturn("created/by"); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtectedBy.class, annotation); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + } + + @Test + public void checkGetComplexProptertyTwoProtectedAttributeClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtections protections = Mockito.mock(EdmProtections.class); + EdmProtectedBy protectedBy1 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy1.name()).thenReturn("UserId"); + when(protectedBy1.path()).thenReturn("created/by"); + + EdmProtectedBy protectedBy2 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy2.name()).thenReturn("UserId"); + when(protectedBy2.path()).thenReturn("updated/by"); + + when(protections.value()).thenReturn(new EdmProtectedBy[] { protectedBy1, protectedBy2 }); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtections.class, protections); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + assertEquals("UserId", property.getProtectionClaimNames().toArray(new String[] {})[0]); + assertNotNull(property.getProtectionPath("UserId")); + + List actPath = property.getProtectionPath("UserId"); + assertEquals(2, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + assertEquals("AdministrativeInformation/Updated/By", actPath.get(1)); + } + + @Test + public void checkGetComplexProptertyTwoProtectedAttributeTwoClaimName() throws ODataJPAModelException { + Attribute jpaAttribute = helper.getAttribute(helper.getEntityType(BusinessPartnerProtected.class), + "administrativeInformation"); + + EdmProtections protections = Mockito.mock(EdmProtections.class); + EdmProtectedBy protectedBy1 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy1.name()).thenReturn("UserId"); + when(protectedBy1.path()).thenReturn("created/by"); + + EdmProtectedBy protectedBy2 = Mockito.mock(EdmProtectedBy.class); + when(protectedBy2.name()).thenReturn("Date"); + when(protectedBy2.path()).thenReturn("created/at"); + + when(protections.value()).thenReturn(new EdmProtectedBy[] { protectedBy1, protectedBy2 }); + + MemberDouble memberSpy = new MemberDouble(jpaAttribute.getJavaMember()); + memberSpy.addAnnotation(EdmProtections.class, protections); + Attribute attributeSpy = Mockito.spy(jpaAttribute); + when(attributeSpy.getJavaMember()).thenReturn(memberSpy); + + IntermediatePropertyAccess property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + attributeSpy, helper.schema); + + assertTrue(property.getProtectionClaimNames().contains("UserId")); + List actPath = property.getProtectionPath("UserId"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/By", actPath.get(0)); + + assertTrue(property.getProtectionClaimNames().contains("Date")); + actPath = property.getProtectionPath("Date"); + assertEquals(1, actPath.size()); + assertEquals("AdministrativeInformation/Created/At", actPath.get(0)); + } + + @Disabled + @Test + public void checkGetSRID() { + // Test for spatial data missing + } + + private class PostProcessorSetName extends JPAEdmMetadataPostProcessor { + + @Override + public void processProperty(IntermediatePropertyAccess property, String jpaManagedTypeClassName) { + if (jpaManagedTypeClassName.equals( + "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner")) { + if (property.getInternalName().equals("customString1")) { + property.setExternalName("ContactPersonName"); + } + } + } + + @Override + public void processNavigationProperty(IntermediateNavigationPropertyAccess property, + String jpaManagedTypeClassName) {} + + @Override + public void provideReferences(IntermediateReferenceList references) throws ODataJPAModelException {} + + @Override + public void processEntityType(IntermediateEntityTypeAccess entity) {} + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java new file mode 100644 index 0000000000..6b11f212b3 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestIntermediateWrongAnnotation.java @@ -0,0 +1,108 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_MISSING_PROTECTION_PATH; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.COMPLEX_PROPERTY_WRONG_PROTECTION_PATH; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_COLLECTION; +import static com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException.MessageKeys.NOT_SUPPORTED_PROTECTED_NAVIGATION; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EntityType; +import javax.persistence.metamodel.PluralAttribute; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.errormodel.CollectionAttributeProtected; +import com.sap.olingo.jpa.processor.core.errormodel.ComplextProtectedNoPath; +import com.sap.olingo.jpa.processor.core.errormodel.ComplextProtectedWrongPath; +import com.sap.olingo.jpa.processor.core.errormodel.NavigationAttributeProtected; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestIntermediateWrongAnnotation { + private TestHelper helper; + protected static final String PUNIT_NAME = "error"; + protected static EntityManagerFactory emf; + + @BeforeEach + public void setup() throws ODataJPAModelException { + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + } + + @Test + public void checkErrorOnProtectedCollectionAttribute() { + PluralAttribute jpaAttribute = helper.getCollectionAttribute(helper.getEntityType( + CollectionAttributeProtected.class), "inhouseAddress"); + + try { + IntermediateCollectionProperty property = new IntermediateCollectionProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema, helper.schema.getEntityType(CollectionAttributeProtected.class)); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(NOT_SUPPORTED_PROTECTED_COLLECTION.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedNavigationAttribute() { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(NavigationAttributeProtected.class), + "teams"); + + try { + IntermediateModelElement property = new IntermediateNavigationProperty(new JPAEdmNameBuilder(PUNIT_NAME), + helper.schema.getEntityType(NavigationAttributeProtected.class), jpaAttribute, helper.schema); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(NOT_SUPPORTED_PROTECTED_NAVIGATION.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedComplexAttributeMissingPath() { + Attribute jpaAttribute = helper.getDeclaredAttribute(helper.getEntityType(ComplextProtectedNoPath.class), + "administrativeInformation"); + + try { + IntermediateModelElement property = new IntermediateSimpleProperty(new JPAEdmNameBuilder(PUNIT_NAME), + jpaAttribute, helper.schema); + + property.getEdmItem(); + } catch (ODataJPAModelException e) { + assertEquals(COMPLEX_PROPERTY_MISSING_PROTECTION_PATH.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } + + @Test + public void checkErrorOnProtectedComplexAttributeWrongPath() { + // ComplextProtectedWrongPath + final EntityType jpaEt = helper.getEntityType(ComplextProtectedWrongPath.class); + try { + IntermediateEntityType et = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), jpaEt, helper.schema); + et.getEdmItem(); + et.getProtections(); + } catch (ODataJPAModelException e) { + assertEquals(COMPLEX_PROPERTY_WRONG_PROTECTION_PATH.name(), e.getId()); + assertFalse(e.getMessage().isEmpty()); + return; + } + fail("Missing exception"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java new file mode 100644 index 0000000000..0e88c05642 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAEdmNameBuilder.java @@ -0,0 +1,29 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class TestJPAEdmNameBuilder { + private JPAEdmNameBuilder cut; + + @BeforeEach + public void setup() throws ODataJPAModelException { + + } + + @Test + public void CheckBuildContainerNameSimple() { + cut = new JPAEdmNameBuilder("cdw"); + assertEquals("CdwContainer", cut.buildContainerName()); + } + + @Test + public void CheckBuildContainerNameComplex() { + cut = new JPAEdmNameBuilder("org.apache.olingo.jpa"); + assertEquals("OrgApacheOlingoJpaContainer", cut.buildContainerName()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java new file mode 100644 index 0000000000..b4cc4bf979 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestJPAPath.java @@ -0,0 +1,89 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAPath extends TestMappingRoot { + private JPAEntityType organization; + // private JPAStructuredType postalAddress; + private TestHelper helper; + + @BeforeEach + public void setup() throws ODataJPAModelException { + helper = new TestHelper(emf.getMetamodel(), PUNIT_NAME); + organization = new IntermediateEntityType(new JPAEdmNameBuilder(PUNIT_NAME), helper.getEntityType( + Organization.class), helper.schema); + } + + @Test + public void checkOnePathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals("Name1", cut.getAlias()); + } + + @Test + public void checkOnePathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals(1, cut.getPath().size()); + } + + @Test + public void checkOnePathElementElement() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Name1"); + assertEquals("name1", cut.getPath().get(0).getInternalName()); + } + + @Test + public void checkOnePathElementFromSuperTypeAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Type"); + assertEquals("Type", cut.getAlias()); + } + + @Test + public void checkTwoPathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals("Address/Country", cut.getAlias()); + } + + @Test + public void checkTwoPathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals(2, cut.getPath().size()); + } + + @Test + public void checkTwoPathElementPathElements() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("Address/Country"); + assertEquals("address", cut.getPath().get(0).getInternalName()); + assertEquals("country", cut.getPath().get(1).getInternalName()); + } + + @Test + public void checkThreePathElementAlias() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals("AdministrativeInformation/Created/By", cut.getAlias()); + } + + @Test + public void checkThreePathElementPathSize() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals(3, cut.getPath().size()); + } + + @Test + public void checkThreePathElementPathElements() throws ODataApplicationException, ODataJPAModelException { + JPAPath cut = organization.getPath("AdministrativeInformation/Created/By"); + assertEquals("administrativeInformation", cut.getPath().get(0).getInternalName()); + assertEquals("created", cut.getPath().get(1).getInternalName()); + assertEquals("by", cut.getPath().get(2).getInternalName()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java new file mode 100644 index 0000000000..6fe72f1b8c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/impl/TestMappingRoot.java @@ -0,0 +1,25 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.impl; + +import javax.persistence.EntityManagerFactory; + +import org.junit.jupiter.api.BeforeAll; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestMappingRoot { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + public static final String BUPA_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner"; + public static final String ORG_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.Organization"; + public static final String ADDR_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData"; + public static final String COMM_CANONICAL_NAME = "com.sap.olingo.jpa.processor.core.testmodel.CommunicationData"; + public static final String ADMIN_CANONICAL_NAME = + "com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision"; + + @BeforeAll + public static void setupClass() { + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/testobjects/ExampleJavaFunctionsReturnsStream.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/testobjects/ExampleJavaFunctionsReturnsStream.java new file mode 100644 index 0000000000..4c51066aac --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-metadata/src/test/java/com/sap/olingo/jpa/metadata/core/edm/mapper/testobjects/ExampleJavaFunctionsReturnsStream.java @@ -0,0 +1,16 @@ +package com.sap.olingo.jpa.metadata.core.edm.mapper.testobjects; + +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunction.ReturnType; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmMediaStream; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.extention.ODataFunction; + +public class ExampleJavaFunctionsReturnsStream implements ODataFunction { + + @EdmFunction(hasFunctionImport = true, returnType = @ReturnType(stream = @EdmMediaStream( + contentType = "audio/x-wav")), name = "") + public byte[] simpleStream(@EdmParameter(name = "A") short a, @EdmParameter(name = "B") int b) { + return new byte[0]; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java new file mode 100644 index 0000000000..61a2ec93e0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAClaimsPairTest.java @@ -0,0 +1,35 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class JPAClaimsPairTest { + + @Test + public void checkCreateIntegerPairOnlyMin() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7); + assertEquals((Integer) 7, cut.min); + } + + @Test + public void checkCreateIntegerPairNoUpperBoundry() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7); + assertFalse(cut.hasUpperBoundary); + } + + @Test + public void checkCreateIntegerPair() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7, 10); + assertEquals((Integer) 7, cut.min); + assertEquals((Integer) 10, cut.max); + } + + @Test + public void checkCreateIntegerPairUpperBoundry() { + final JPAClaimsPair cut = new JPAClaimsPair<>(7, 10); + assertTrue(cut.hasUpperBoundary); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java new file mode 100644 index 0000000000..b3e11f1cca --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataBatchProcessorTest.java @@ -0,0 +1,116 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.OptimisticLockException; +import javax.persistence.RollbackException; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.batch.BatchFacade; +import org.eclipse.persistence.jpa.jpql.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; + +public class JPAODataBatchProcessorTest { + private JPAODataBatchProcessor cut; + + @Mock + private EntityManager em; + @Mock + private EntityTransaction transaction; + @Mock + private OData odata; + @Mock + private ServiceMetadata serviceMetadata; + @Mock + private BatchFacade facade; + @Mock + private ODataRequest request; + @Mock + private ODataResponse response; + @Mock + private RollbackException e; + @Mock + private JPAODataSessionContextAccess context; + @Mock + private JPACUDRequestHandler cudHandler; + + private List requests; + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + cut = new JPAODataBatchProcessor(context, em); + cut.init(odata, serviceMetadata); + requests = new ArrayList<>(); + requests.add(request); + when(context.getDebugger()).thenReturn(new JPAEmptyDebugger()); + when(context.getCUDRequestHandler()).thenReturn(cudHandler); + } + + @Test + public void whenNotOptimisticLockRollBackExceptionThenThrowODataJPAProcessorExceptionWithHttpCode500() + throws ODataApplicationException, ODataLibraryException { + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + doThrow(e).when(transaction).commit(); + + try { + cut.processChangeSet(facade, requests); + Assert.fail("Should have thrown ODataJPAProcessorException!"); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + } + + } + + @Test + public void whenOptimisticLockRollBackExceptionThenThrowODataJPAProcessorExceptionWithHttpCode412() + throws ODataApplicationException, ODataLibraryException { + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + doThrow(e).when(transaction).commit(); + when(e.getCause()).thenReturn(new OptimisticLockException()); + + try { + cut.processChangeSet(facade, requests); + Assert.fail("Should have thrown ODataJPAProcessorException!"); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.PRECONDITION_FAILED.getStatusCode(), e.getStatusCode()); + } + } + + @Test + public void whenProcessChangeSetCallValidateChangesOnSccess() throws ODataApplicationException, + ODataLibraryException { + cut = new JPAODataBatchProcessor(context, em); + + when(em.getTransaction()).thenReturn(transaction); + when(response.getStatusCode()).thenReturn(HttpStatusCode.OK.getStatusCode()); + when(facade.handleODataRequest(request)).thenReturn(response); + + cut.processChangeSet(facade, requests); + verify(cudHandler, times(1)).validateChanges(em); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java new file mode 100644 index 0000000000..f7683f78d9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataClaimsProviderTest.java @@ -0,0 +1,58 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class JPAODataClaimsProviderTest { + + private JPAODataClaimsProvider cut; + + @BeforeEach + public void setup() { + cut = new JPAODataClaimsProvider(); + } + + @Test + public void checkAddSinglePairReturnsOne() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(1, claims.size()); + } + + @Test + public void checkAddThreeSinglePairsReturnsThree() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + cut.add("Test", new JPAClaimsPair<>("Willi")); + cut.add("Test", new JPAClaimsPair<>("Walter")); + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(3, claims.size()); + } + + @Test + public void checkNotProvidedAttributeReturnsEmptyList() { + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(0, claims.size()); + } + + @Test + public void checkAddTwoAttributesSinglePairs() { + cut.add("Test", new JPAClaimsPair<>("Hugo")); + cut.add("Dummy", new JPAClaimsPair<>("Willi")); + + List> claims = cut.get("Test"); + assertNotNull(claims); + assertEquals(1, claims.size()); + + claims = cut.get("Dummy"); + assertNotNull(claims); + assertEquals(1, claims.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java new file mode 100644 index 0000000000..1d37ca8595 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/JPAODataContextAccessDouble.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.sql.SQLException; +import java.util.List; + +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.server.api.debug.DebugSupport; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseProcessorFactory; + +public class JPAODataContextAccessDouble implements JPAODataSessionContextAccess { + private final JPAEdmProvider edmProvider; + private final DataSource ds; + private final JPAODataDatabaseOperations context; + private final String[] packageNames; + private final JPAODataPagingProvider pagingProvider; + + public JPAODataContextAccessDouble(final JPAEdmProvider edmProvider, final DataSource ds, + final JPAODataPagingProvider provider, final String... packages) { + super(); + this.edmProvider = edmProvider; + this.ds = ds; + this.context = new JPADefaultDatabaseProcessor(); + this.packageNames = packages; + this.pagingProvider = provider; + } + + @Override + public List getReferences() { + fail(); + return null; + } + + @Override + public DebugSupport getDebugSupport() { + fail(); + return null; + } + + @Override + public JPAODataDatabaseOperations getOperationConverter() { + return context; + } + + @Override + public JPAEdmProvider getEdmProvider() { + return edmProvider; + } + + @Override + public JPAODataDatabaseProcessor getDatabaseProcessor() { + try { + return new JPAODataDatabaseProcessorFactory().create(ds); + } catch (SQLException e) { + fail(); + } + return null; + } + + @Override + public JPAServiceDebugger getDebugger() { + return new JPAEmptyDebugger(); + } + + @Override + public JPACUDRequestHandler getCUDRequestHandler() { + fail(); + return null; + } + + @Override + public String[] getPackageName() { + return packageNames; + } + + @Override + public JPAODataPagingProvider getPagingProvider() { + return pagingProvider; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java new file mode 100644 index 0000000000..3aece4eb66 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/TestBatchRequests.java @@ -0,0 +1,115 @@ +package com.sap.olingo.jpa.processor.core.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.util.List; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestBatchRequests extends TestBase { + + @Test + public void testOneGetRequestGetResponce() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + List act = helper.getRawBatchResult(); + assertNotNull(act); + } + + @Test + public void testOneGetRequestCheckStatus() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + assertEquals(200, helper.getBatchResultStatus(1)); + } + + @Test + public void testOneGetRequestCheckValue() throws IOException, ODataException { + StringBuffer requestBody = createBodyOneGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + JsonNode value = helper.getBatchResult(1); + assertEquals("3", value.get("ID").asText()); + } + + @Test + public void testTwoGetRequestSecondFailCheckStatus() throws IOException, ODataException { + StringBuffer requestBody = createBodyTwoGetOneFail(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + assertEquals(404, helper.getBatchResultStatus(2)); + } + + @Test + public void testTwoGetRequestCheckValue() throws IOException, ODataException { + StringBuffer requestBody = createBodyTwoGet(); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "$batch", requestBody); + JsonNode value = helper.getBatchResult(2); + assertEquals("5", value.get("ID").asText()); + } + + private StringBuffer createBodyTwoGetOneFail() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET AdministrativeDivision HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } + + private StringBuffer createBodyTwoGet() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('5') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } + + private StringBuffer createBodyOneGet() { + StringBuffer requestBody = new StringBuffer("--abc123\r\n"); + requestBody.append("Content-Type: application/http\r\n"); + requestBody.append("Content-Transfer-Encoding: binary\r\n"); + requestBody.append("\r\n"); + requestBody.append("GET Organizations('3') HTTP/1.1\r\n"); + requestBody.append("Content-Type: application/json\r\n"); + requestBody.append("\r\n"); + requestBody.append("\r\n"); + requestBody.append("--abc123--"); + return requestBody; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java new file mode 100644 index 0000000000..4badc6b30d --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/api/example/JPAExamplePagingProviderTest.java @@ -0,0 +1,298 @@ +package com.sap.olingo.jpa.processor.core.api.example; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.queryoption.OrderByItem; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; +import org.apache.olingo.server.api.uri.queryoption.TopOption; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.api.JPAODataPage; +import com.sap.olingo.jpa.processor.core.query.JPACountQuery; + +public class JPAExamplePagingProviderTest { + private JPACountQuery countQuery; + + @BeforeEach + public void setup() throws ODataApplicationException { + countQuery = mock(JPACountQuery.class); + when(countQuery.countResults()).thenReturn(10L); + } + + @Test + public void testReturnDefaultTopSkipPageSize2() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(2, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSize5() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(5, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSizeOther() throws ODataApplicationException { + final UriInfo info = buildUriInfo("AdministrativeDivisions", "AdministrativeDivision"); + final JPAExamplePagingProvider cut = createOrgCut(5); + when(countQuery.countResults()).thenReturn(12L); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(10, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnDefaultTopSkipPageSize5NextPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertEquals(5, act.getSkip()); + assertEquals(5, act.getTop()); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnNullIfEntitySetIsUnknown() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createPersonCut(5); + final JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertNull(act); + } + + @Test + public void testReturnNullIfEntitySetIsUnknownButMaxpagesizeHeader() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createPersonCut(5); + final JPAODataPage act = cut.getFirstPage(info, 3, countQuery, null); + + assertNull(act); + } + + @Test + public void testReturnRespectMaxpagesizeHeader() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + final JPAODataPage act = cut.getFirstPage(info, 3, countQuery, null); + + assertEquals(0, act.getSkip()); + assertEquals(3, act.getTop()); + assertNotNull(toODataString((String) act.getSkiptoken())); + assertEquals(info, act.getUriInfo()); + } + + @Test + public void testReturnSkiptokenNullAtLastPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNull(act.getSkiptoken()); + } + + @Test + public void testReturnSkiptokenNullOnlyOnePage() throws ODataApplicationException { + final UriInfo info = buildUriInfo("AdministrativeDivisions", "AdministrativeDivision"); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertNull(act.getSkiptoken()); + } + + @Test + public void testReturnSkiptokenIfNotLastPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNotNull(toODataString((String) act.getSkiptoken())); + } + + @Test + public void testReturnThirdPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final JPAExamplePagingProvider cut = createOrgCut(2); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertNotNull(toODataString((String) act.getSkiptoken())); + } + + @Test + public void testRespectTopSkipOfUriFirstPageLowerMaxSize() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(10); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(2, act.getSkip()); + assertEquals(7, act.getTop()); + } + + @Test + public void testRespectTopSkipOfUriFirstPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + + assertEquals(2, act.getSkip()); + assertEquals(5, act.getTop()); + } + + @Test + public void testRespectTopSkipOfUriNextPage() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + addTopSkipToUri(info); + final JPAExamplePagingProvider cut = createOrgCut(5); + JPAODataPage act = cut.getFirstPage(info, null, countQuery, null); + act = cut.getNextPage(toODataString((String) act.getSkiptoken())); + + assertEquals(7, act.getSkip()); + assertEquals(2, act.getTop()); + } + + @Test + public void testBufferFilled() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final Map sizes = new HashMap<>(); + sizes.put("Organizations", 2); + + final JPAExamplePagingProvider cut = new JPAExamplePagingProvider(sizes, 2); + final JPAODataPage first = cut.getFirstPage(info, null, countQuery, null); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + final JPAODataPage second = cut.getNextPage((String) first.getSkiptoken()); + assertNotNull(cut.getNextPage((String) second.getSkiptoken())); + final JPAODataPage third = cut.getNextPage((String) second.getSkiptoken()); + assertNotNull(cut.getNextPage((String) third.getSkiptoken())); + assertNull(cut.getNextPage((String) first.getSkiptoken())); + } + + @Test + public void testBufferNotFilled() throws ODataApplicationException { + final UriInfo info = buildUriInfo(); + final Map sizes = new HashMap<>(); + sizes.put("Organizations", 2); + + final JPAExamplePagingProvider cut = new JPAExamplePagingProvider(sizes, 10); + final JPAODataPage first = cut.getFirstPage(info, null, countQuery, null); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + final JPAODataPage second = cut.getNextPage((String) first.getSkiptoken()); + assertNotNull(cut.getNextPage((String) second.getSkiptoken())); + final JPAODataPage third = cut.getNextPage((String) second.getSkiptoken()); + assertNotNull(cut.getNextPage((String) third.getSkiptoken())); + assertNotNull(cut.getNextPage((String) first.getSkiptoken())); + } + + private UriInfo buildUriInfo() { + return buildUriInfo("Organizations", "Organization"); + } + + private UriInfo buildUriInfo(final String esName, final String etName) { + final UriInfo uriInfo = mock(UriInfo.class); + final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class); + final EdmEntitySet es = mock(EdmEntitySet.class); + final EdmType type = mock(EdmType.class); + final OrderByOption order = mock(OrderByOption.class); + final OrderByItem orderItem = mock(OrderByItem.class); + final Member orderExpression = mock(Member.class); + final UriInfoResource orderResourcePath = mock(UriInfoResource.class); + final UriResourcePrimitiveProperty orderResourcePathItem = mock(UriResourcePrimitiveProperty.class); + final EdmProperty orderProperty = mock(EdmProperty.class); + final List orderItems = new ArrayList<>(); + final List orderResourcePathItems = new ArrayList<>(); + + orderItems.add(orderItem); + orderResourcePathItems.add(orderResourcePathItem); + when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet); + when(uriEs.getEntitySet()).thenReturn(es); + when(uriEs.getType()).thenReturn(type); + when(es.getName()).thenReturn(esName); + when(type.getNamespace()).thenReturn("com.sap.olingo.jpa"); + when(type.getName()).thenReturn(etName); + when(order.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY); + when(orderItem.isDescending()).thenReturn(true); + when(orderItem.getExpression()).thenReturn(orderExpression); + when(orderExpression.getResourcePath()).thenReturn(orderResourcePath); + when(orderResourcePath.getUriResourceParts()).thenReturn(orderResourcePathItems); + when(orderResourcePathItem.getProperty()).thenReturn(orderProperty); + when(orderProperty.getName()).thenReturn("ID"); + when(order.getOrders()).thenReturn(orderItems); + final List resourceParts = new ArrayList<>(); + resourceParts.add(uriEs); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriInfo.getOrderByOption()).thenReturn(order); + return uriInfo; + } + + private void addTopSkipToUri(final UriInfo info) { + final SkipOption skipOption = mock(SkipOption.class); + final TopOption topOption = mock(TopOption.class); + + when(skipOption.getValue()).thenReturn(2); + when(topOption.getValue()).thenReturn(7); + when(info.getSkipOption()).thenReturn(skipOption); + when(info.getTopOption()).thenReturn(topOption); + + } + + private JPAExamplePagingProvider createOrgCut(final int size) { + final Map sizes = new HashMap<>(); + sizes.put("Organizations", size); + sizes.put("AdministrativeDivisions", 10); + return new JPAExamplePagingProvider(sizes); + } + + private JPAExamplePagingProvider createPersonCut(final int size) { + final Map sizes = new HashMap<>(); + sizes.put("Persons", size); + return new JPAExamplePagingProvider(sizes); + } + + private String toODataString(final String skiptoken) { + return "'" + skiptoken + "'"; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPADefaultDatabaseProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPADefaultDatabaseProcessor.java new file mode 100644 index 0000000000..cdcb081578 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPADefaultDatabaseProcessor.java @@ -0,0 +1,138 @@ +package com.sap.olingo.jpa.processor.core.database; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Predicate; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.processor.core.exception.ODataJPADBAdaptorException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAFilterException; +import com.sap.olingo.jpa.processor.core.filter.JPAAggregationOperation; +import com.sap.olingo.jpa.processor.core.filter.JPAArithmeticOperator; +import com.sap.olingo.jpa.processor.core.filter.JPABooleanOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAComparisonOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAEnumerationBasedOperator; +import com.sap.olingo.jpa.processor.core.filter.JPAMethodCall; +import com.sap.olingo.jpa.processor.core.filter.JPAUnaryBooleanOperator; + +public class TestJPADefaultDatabaseProcessor { + private JPADefaultDatabaseProcessor cut; + + @BeforeEach + public void setup() { + cut = new JPADefaultDatabaseProcessor(); + } + + @Test + public void testNotSupportedConvertBooleanOperator() throws ODataApplicationException { + final JPABooleanOperator operator = mock(JPABooleanOperator.class); + when(operator.getName()).thenReturn("Hugo"); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @Test + public void testNotSupportedConvertAggregationOperator() throws ODataApplicationException { + final JPAAggregationOperation operator = mock(JPAAggregationOperation.class); + when(operator.getName()).thenReturn("Hugo"); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @Test + public void testNotSupportedConvertArithmeticOperator() throws ODataApplicationException { + final JPAArithmeticOperator operator = mock(JPAArithmeticOperator.class); + when(operator.getName()).thenReturn("Hugo"); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @Test + public void testNotSupportedConvertMethodCall() throws ODataApplicationException { + final JPAMethodCall operator = mock(JPAMethodCall.class); + when(operator.getName()).thenReturn("Hugo"); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @Test + public void testNotSupportedConvertUnaryBooleanOperator() throws ODataApplicationException { + final JPAUnaryBooleanOperator operator = mock(JPAUnaryBooleanOperator.class); + when(operator.getName()).thenReturn("Hugo"); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @Test + public void testNotSupportedConvertComparisonOperatorOthersThenHAS() throws ODataApplicationException { + @SuppressWarnings("unchecked") + final JPAComparisonOperator operator = mock(JPAComparisonOperator.class); + when(operator.getName()).thenReturn("Hugo"); + when(operator.getOperator()).then(new Answer() { + @Override + public BinaryOperatorKind answer(InvocationOnMock invocation) throws Throwable { + return BinaryOperatorKind.SUB; + } + }); + assertThrows(ODataJPAFilterException.class, () -> { + cut.convert(operator); + }); + } + + @SuppressWarnings("unchecked") + @Test + public void testSupportedConvertComparisonOperatorOperatorHAS() throws ODataApplicationException { + final CriteriaBuilder cb = mock(CriteriaBuilder.class); + Expression cbResult = mock(Expression.class); + Predicate cbPredicate = mock(Predicate.class); + final JPAComparisonOperator operator = mock(JPAComparisonOperator.class); + final Expression left = mock(Expression.class); + final JPAEnumerationBasedOperator right = mock(JPAEnumerationBasedOperator.class); + + when(operator.getName()).thenReturn("Hugo"); + when(operator.getOperator()).then(new Answer() { + @Override + public BinaryOperatorKind answer(InvocationOnMock invocation) throws Throwable { + return BinaryOperatorKind.HAS; + } + }); + when(operator.getRight()).thenReturn(right); + when(right.getValue()).thenReturn(5L); + when(operator.getLeft()).thenReturn(left); + + when(cb.quot(left, 5L)).thenAnswer(new Answer>() { + @Override + public Expression answer(InvocationOnMock invocation) throws Throwable { + return cbResult; + } + }); + when(cb.mod(cbResult, 2)).thenReturn(cbResult); + when(cb.equal(cbResult, 1)).thenReturn(cbPredicate); + cut.setCriterialBuilder(cb); + final Expression act = cut.convert(operator); + assertNotNull(act); + } + + @Test + public void testNotSupportedSearch() throws ODataApplicationException { + assertThrows(ODataJPADBAdaptorException.class, () -> { + cut.createSearchWhereClause(null, null, null, null, null); + }); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPA_HSQLDB_DatabaseProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPA_HSQLDB_DatabaseProcessor.java new file mode 100644 index 0000000000..78ed651637 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/database/TestJPA_HSQLDB_DatabaseProcessor.java @@ -0,0 +1,443 @@ +package com.sap.olingo.jpa.processor.core.database; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmParameter; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.commons.core.edm.primitivetype.EdmString; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceCount; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.internal.matchers.Equals; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPA_HSQLDB_DatabaseProcessor { + private JPAODataDatabaseProcessor cut; + private EntityManager em; + private UriResourceEntitySet uriEntitySet; + private JPADataBaseFunction jpaFunction; + private UriResourceFunction uriFunction; + private EdmEntityType edmEntityType; + private EdmFunction edmFunction; + private EdmParameter edmElement; + private List uriResourceParts; + private List uriParameters; + private JPAOperationResultParameter returnParameter; + private List parameterList; + private JPAParameter firstParameter; + private UriParameter firstUriParameter; + private Query functionQuery; + + @BeforeEach + public void steup() { + em = mock(EntityManager.class); + functionQuery = mock(Query.class); + uriResourceParts = new ArrayList<>(); + uriFunction = mock(UriResourceFunction.class); + uriEntitySet = mock(UriResourceEntitySet.class); + edmFunction = mock(EdmFunction.class); + edmElement = mock(EdmParameter.class); + edmEntityType = mock(EdmEntityType.class); + uriResourceParts.add(uriFunction); + uriParameters = new ArrayList<>(); + firstUriParameter = mock(UriParameter.class); + + jpaFunction = mock(JPADataBaseFunction.class); + returnParameter = mock(JPAOperationResultParameter.class); + parameterList = new ArrayList<>(); + firstParameter = mock(JPAParameter.class); + + when(em.createNativeQuery(any(), eq(BusinessPartner.class))).thenReturn(functionQuery); + when(em.createNativeQuery(any())).thenReturn(functionQuery); + when(uriEntitySet.getEntityType()).thenReturn(edmEntityType); + when(uriEntitySet.getKind()).thenReturn(UriResourceKind.entitySet); + when(uriEntitySet.getKeyPredicates()).thenReturn(uriParameters); + when(uriFunction.getParameters()).thenReturn(uriParameters); + when(jpaFunction.getResultParameter()).thenReturn(returnParameter); + when(uriFunction.getFunction()).thenReturn(edmFunction); + when(uriFunction.getKind()).thenReturn(UriResourceKind.function); + when(edmFunction.getParameter(firstParameter.getName())).thenReturn(edmElement); + + cut = new JPA_HSQLDB_DatabaseProcessor(); + } + + @Test + public void testUnboundFunctionWithOneParameterReturnsBuPas() throws ODataApplicationException, + ODataJPAModelException { + + createFunctionWithOneParameter(); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT * FROM TABLE (Example(?1))")), eq( + BusinessPartner.class)); + verify(functionQuery, times(1)).setParameter(1, "5"); + assertNotNull(act); + assertEquals(2, act.size()); + } + + @Test + public void testUnboundFunctionWithTwoParameterReturnsBuPas() throws ODataApplicationException, + ODataJPAModelException { + + createFunctionWithOneParameter(); + addSecondParameter(); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT * FROM TABLE (Example(?1,?2))")), eq( + BusinessPartner.class)); + verify(functionQuery, times(1)).setParameter(1, "5"); + verify(functionQuery, times(1)).setParameter(2, "3"); + assertNotNull(act); + assertEquals(2, act.size()); + } + + @Test + public void testUnboundFunctionWithOneParameterCount() throws ODataApplicationException, + ODataJPAModelException { + + createFunctionWithOneParameter(); + + final UriResourceCount uriResourceCount = mock(UriResourceCount.class); + uriResourceParts.add(uriResourceCount); + when(uriResourceCount.getKind()).thenReturn(UriResourceKind.count); + when(functionQuery.getSingleResult()).thenReturn(5L); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT COUNT(*) FROM TABLE (Example(?1))"))); + verify(functionQuery, times(1)).setParameter(1, "5"); + verify(functionQuery, times(0)).getResultList(); + verify(functionQuery, times(1)).getSingleResult(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals(5L, act.get(0)); + } + + @Test + public void testUnboundRaisesExceptionOnMissingParameter() throws ODataJPAModelException { + + createFunctionWithOneParameter(); + when(uriFunction.getParameters()).thenReturn(new ArrayList<>()); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testUnboundConvertsExceptionOnParameterProblem() throws ODataJPAModelException { + + createFunctionWithOneParameter(); + when(jpaFunction.getParameter()).thenThrow(ODataJPAModelException.class); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testAbortsOnNotImplementedChaning() throws ODataJPAModelException { + + createFunctionWithOneParameter(); + + final UriResourceCount uriResourceCount = mock(UriResourceCount.class); + uriResourceParts.add(uriResourceCount); + when(uriResourceCount.getKind()).thenReturn(UriResourceKind.value); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(e.getStatusCode(), HttpStatusCode.NOT_IMPLEMENTED.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testBoundFunctionWithOneParameterReturnsBuPas() throws ODataApplicationException, + ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT * FROM TABLE (Example(?1))")), eq( + BusinessPartner.class)); + verify(functionQuery, times(1)).setParameter(1, "5"); + assertNotNull(act); + assertEquals(2, act.size()); + } + + @Test + public void testBoundFunctionWithTwoParameterReturnsBuPas() throws ODataApplicationException, + ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + addSecondBoundParameter(); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT * FROM TABLE (Example(?1,?2))")), eq( + BusinessPartner.class)); + verify(functionQuery, times(1)).setParameter(1, "5"); + verify(functionQuery, times(1)).setParameter(2, "3"); + assertNotNull(act); + assertEquals(2, act.size()); + } + + @Test + public void testBoundFunctionWithOneParameterCount() throws ODataApplicationException, + ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + + final UriResourceCount uriResourceCount = mock(UriResourceCount.class); + uriResourceParts.add(uriResourceCount); + when(uriResourceCount.getKind()).thenReturn(UriResourceKind.count); + when(functionQuery.getSingleResult()).thenReturn(5L); + + final List act = cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + + verify(em, times(1)).createNativeQuery((String) argThat(new Equals("SELECT COUNT(*) FROM TABLE (Example(?1))"))); + verify(functionQuery, times(1)).setParameter(1, "5"); + verify(functionQuery, times(0)).getResultList(); + verify(functionQuery, times(1)).getSingleResult(); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals(5L, act.get(0)); + } + + @Test + public void testBoundRaisesExceptionOnMissingParameter() throws ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + when(uriEntitySet.getKeyPredicates()).thenReturn(new ArrayList<>()); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testBoundConvertsExceptionOnParameterProblem() throws ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + when(jpaFunction.getParameter()).thenThrow(ODataJPAModelException.class); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testCheckRaisesExceptionOnIsBound() throws ODataJPAModelException { + + createBoundFunctionWithOneParameter(); + when(jpaFunction.isBound()).thenThrow(ODataJPAModelException.class); + + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @Test + public void testCheckRaiseExceptionOnProblemValueToString() throws ODataJPAModelException, EdmPrimitiveTypeException { + + createBoundFunctionWithOneParameter(); + + final EdmPrimitiveType edmType = mock(EdmPrimitiveType.class); + when(edmElement.getType()).thenReturn(edmType); + when(edmType.valueOfString(any(), any(), any(), any(), any(), any(), any())) + .thenThrow(EdmPrimitiveTypeException.class); + try { + cut.executeFunctionQuery(uriResourceParts, jpaFunction, em); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail("Missing exception"); + } + + @SuppressWarnings("unchecked") + @Test + public void testAbortsOnSearchRequest() { + final CriteriaBuilder cb = mock(CriteriaBuilder.class); + final CriteriaQuery cq = mock(CriteriaQuery.class); + final Root root = mock(Root.class); + final JPAEntityType entityType = mock(JPAEntityType.class); + final SearchOption searchOption = mock(SearchOption.class); + try { + cut.createSearchWhereClause(cb, cq, root, entityType, searchOption); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + return; + } + fail("Message not thrown"); + } + + private void addSecondParameter() { + final JPAParameter secondParameter = mock(JPAParameter.class); + final UriParameter secondUriParameter = mock(UriParameter.class); + final EdmParameter edmSecondElement = mock(EdmParameter.class); + + parameterList.add(secondParameter); + uriParameters.add(secondUriParameter); + when(secondUriParameter.getText()).thenReturn("3"); + when(secondParameter.getName()).thenReturn("B"); + when(secondUriParameter.getName()).thenReturn("B"); + when(edmFunction.getParameter(eq("B"))).thenReturn(edmSecondElement); + when(edmSecondElement.getType()).thenReturn(EdmString.getInstance()); + when(secondParameter.getMaxLength()).thenReturn(10); + when(secondParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + } + + private void createFunctionWithOneParameter() throws ODataJPAModelException { + when(returnParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BusinessPartner.class; + } + }); + when(jpaFunction.getDBName()).thenReturn("Example"); + when(jpaFunction.getParameter()).thenReturn(parameterList); + + parameterList.add(firstParameter); + when(firstParameter.getName()).thenReturn("A"); + + uriParameters.add(firstUriParameter); + when(firstUriParameter.getName()).thenReturn("A"); + when(edmFunction.getParameter(eq("A"))).thenReturn(edmElement); + when(firstUriParameter.getText()).thenReturn("5"); + when(edmElement.getType()).thenReturn(EdmString.getInstance()); + when(firstParameter.getMaxLength()).thenReturn(10); + when(firstParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + when(functionQuery.getResultList()).thenReturn(Arrays.asList(new BusinessPartner[] { new Organization(), + new Organization() })); + } + + private void createBoundFunctionWithOneParameter() throws ODataJPAModelException { + + uriResourceParts.add(0, uriEntitySet); + when(uriFunction.getParameters()).thenReturn(new ArrayList<>()); + when(jpaFunction.isBound()).thenReturn(Boolean.TRUE); + when(returnParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BusinessPartner.class; + } + }); + + when(jpaFunction.getDBName()).thenReturn("Example"); + when(jpaFunction.getParameter()).thenReturn(parameterList); + + parameterList.add(firstParameter); + when(firstParameter.getName()).thenReturn("A"); + + uriParameters.add(firstUriParameter); + when(firstUriParameter.getName()).thenReturn("A"); + when(edmEntityType.getProperty(eq("A"))).thenReturn(edmElement); + when(firstUriParameter.getText()).thenReturn("5"); + when(edmElement.getType()).thenReturn(EdmString.getInstance()); + when(firstParameter.getMaxLength()).thenReturn(10); + when(firstParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + when(functionQuery.getResultList()).thenReturn(Arrays.asList(new BusinessPartner[] { new Organization(), + new Organization() })); + } + + private void addSecondBoundParameter() { + final JPAParameter secondParameter = mock(JPAParameter.class); + final UriParameter secondUriParameter = mock(UriParameter.class); + final EdmParameter edmSecondElement = mock(EdmParameter.class); + + parameterList.add(secondParameter); + uriParameters.add(secondUriParameter); + when(secondUriParameter.getText()).thenReturn("3"); + when(secondParameter.getName()).thenReturn("B"); + when(secondUriParameter.getName()).thenReturn("B"); + when(edmEntityType.getProperty(eq("B"))).thenReturn(edmSecondElement); + when(edmSecondElement.getType()).thenReturn(EdmString.getInstance()); + when(secondParameter.getMaxLength()).thenReturn(10); + when(secondParameter.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java new file mode 100644 index 0000000000..bb0b94a7df --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/exception/TestODataJPAProcessorException.java @@ -0,0 +1,89 @@ +package com.sap.olingo.jpa.processor.core.exception; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAMessageKey; + +public class TestODataJPAProcessorException { + // private static String BUNDLE_NAME = "exceptions-i18n"; + + public static enum MessageKeys implements ODataJPAMessageKey { + RESULT_NOT_FOUND; + + @Override + public String getKey() { + return name(); + } + + } + + @Test + public void checkSimpleRaiseExeption() { + try { + RaiseExeption(); + } catch (ODataApplicationException e) { + assertEquals("No result was fond by Serializer", e.getMessage()); + assertEquals(400, e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void checkSimpleViaMessageKeyRaiseExeption() { + try { + RaiseExeptionParam(); + } catch (ODataApplicationException e) { + assertEquals("Unable to convert value 'Willi' of parameter 'Hugo'", e.getMessage()); + assertEquals(500, e.getStatusCode()); + return; + } + fail(); + } + + private void RaiseExeptionParam() throws ODataJPAProcessException { + throw new ODataJPADBAdaptorException(ODataJPADBAdaptorException.MessageKeys.PARAMETER_CONVERSION_ERROR, + HttpStatusCode.INTERNAL_SERVER_ERROR, "Willi", "Hugo"); + } + + private void RaiseExeption() throws ODataJPAProcessException { + throw new ODataJPASerializerException(ODataJPASerializerException.MessageKeys.RESULT_NOT_FOUND, + HttpStatusCode.BAD_REQUEST); + } + +// private class TestException extends ODataJPAProcessException { +// private static final long serialVersionUID = 1L; +// +// public TestException(Throwable e, final HttpStatusCode statusCode) { +// super(e, statusCode); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, +// final Throwable cause, final String... params) { +// super(messageKey.getKey(), statusCode, cause, params); +// } +// +// public TestException(final String id, final HttpStatusCode statusCode) { +// super(id, statusCode); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, +// final String... params) { +// super(messageKey.getKey(), statusCode, params); +// } +// +// public TestException(final MessageKeys messageKey, final HttpStatusCode statusCode, final Throwable e) { +// super(messageKey.getKey(), statusCode, e); +// } +// +// @Override +// protected String getBundleName() { +// return BUNDLE_NAME; +// } +// } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java new file mode 100644 index 0000000000..5872f06288 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAArithmeticOperator.java @@ -0,0 +1,205 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigDecimal; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; + +public class TestJPAArithmeticOperator { + private CriteriaBuilder cb; + + private JPAOperationConverter converter; + private Path expression; + + @SuppressWarnings("unchecked") + @BeforeEach + public void setUp() throws Exception { + converter = mock(JPAOperationConverter.class); + cb = mock(CriteriaBuilder.class); + expression = mock(Path.class); + } + + @Test + public void testMemberLiteralGetLeft_Member() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPALiteralOperator right = mock(JPALiteralOperator.class); + + when(right.get()).thenReturn(5); + when(left.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + } + + @Test + public void testLiteralMemberGetLeft_Member() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + + when(left.get()).thenReturn(5); + when(right.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetLeftLiteralLiteral_Left() throws ODataApplicationException { + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + Integer leftValue = new Integer(5); + + final Expression result = mock(Expression.class); + + when(left.get()).thenReturn(leftValue); + when(right.get()).thenReturn(10); + + when(cb.literal(leftValue)).thenAnswer(new Answer>() { + @Override + public Expression answer(InvocationOnMock invocation) throws Throwable { + invocation.getArguments(); + return result; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + Expression act = cut.getLeft(cb); + assertEquals(result, act); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetLeftMemberMember_Left() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPAMemberOperator left = mock(JPAMemberOperator.class); + + final Path expressionRight = mock(Path.class); + + when(right.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expressionRight; + } + }); + when(left.get()).thenAnswer(new Answer>() { + @Override + public Path answer(InvocationOnMock invocation) throws Throwable { + return expression; + } + }); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(expression, cut.getLeft(cb)); + + } + + @Test + public void testMemberLiteralGetRightAsNumber_Right() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(right.get(attribute)).thenReturn(new BigDecimal("5.1")); + when(left.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testLiteralMemberGetRightAsNumber_Left() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(left.get(attribute)).thenReturn(new BigDecimal("5.1")); + when(right.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("5.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testLiteralLiteralGetRightAsNumber_Right() throws ODataApplicationException { + JPALiteralOperator right = mock(JPALiteralOperator.class); + JPALiteralOperator left = mock(JPALiteralOperator.class); + + when(left.get()).thenReturn(new BigDecimal("5.1")); + when(right.get()).thenReturn(new BigDecimal("10.1")); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + assertEquals(new BigDecimal("10.1"), cut.getRightAsNumber(cb)); + } + + @Test + public void testGetMemberMemberGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPAAttribute attribute = mock(JPAAttribute.class); + + when(left.determineAttribute()).thenReturn(attribute); + when(right.determineAttribute()).thenReturn(attribute); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } + + @Test + public void testGetBooleanMemberGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator right = mock(JPAMemberOperator.class); + JPABooleanOperatorImp left = mock(JPABooleanOperatorImp.class); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } + + @Test + public void testGetMemberBooleanGetRightAsNumber_Exeption() throws ODataApplicationException { + JPAMemberOperator left = mock(JPAMemberOperator.class); + JPABooleanOperatorImp right = mock(JPABooleanOperatorImp.class); + + JPAArithmeticOperator cut = new JPAArithmeticOperatorImp(converter, BinaryOperatorKind.ADD, left, right); + try { + cut.getRightAsNumber(cb); + } catch (ODataApplicationException e) { + return; + } + fail("Exception expecetd"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java new file mode 100644 index 0000000000..2eb7838862 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPACustomScalarFunctions.java @@ -0,0 +1,152 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPACustomScalarFunctions { + + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + protected static DataSource ds; + + @BeforeAll + public static void setupClass() throws ODataJPAModelException { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + CreateDenfityFunction(); + } + + @AfterAll + public static void tearDownClass() throws ODataJPAModelException { + DropDenfityFunction(); + } + + @Test + public void testFilterOnFunction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) gt 1"); + helper.assertStatus(200); + } + + @Test + public void testFilterOnFunctionAndProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=$it/Area,Population=$it/Population) mul 1000000 gt 1000 and ParentDivisionCode eq 'BE255'&orderBy=DivisionCode)"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + assertEquals("35002", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterOnFunctionAndMultiply() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area,Population=Population) mul 1000000 gt 100"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(59, orgs.size()); + } + + @Test + public void testFilterOnFunctionWithFixedValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=13079087,Population=$it/Population) mul 1000000 gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(29, orgs.size()); + } + + @Test + public void testFilterOnFunctionComuteValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Area=Area div 1000000,Population=Population) gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterOnFunctionMixParamOrder() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=com.sap.olingo.jpa.PopulationDensity(Population=Population,Area=Area) mul 1000000 gt 1000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + private static void CreateDenfityFunction() { + EntityManager em = emf.createEntityManager(); + EntityTransaction t = em.getTransaction(); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append( + "CREATE FUNCTION \"OLINGO\".\"PopulationDensity\" (UnitArea INT, Population BIGINT ) "); + sqlString.append("RETURNS DOUBLE "); + sqlString.append("BEGIN ATOMIC "); // + sqlString.append(" DECLARE aDouble DOUBLE; "); // + sqlString.append(" DECLARE pDouble DOUBLE; "); + sqlString.append(" SET aDouble = UnitArea; "); + sqlString.append(" SET pDouble = Population; "); + sqlString.append(" IF UnitArea <= 0 THEN RETURN 0; "); + sqlString.append(" ELSE RETURN pDouble / aDouble; "); // * 1000000 + sqlString.append(" END IF; "); // + sqlString.append("END"); + + t.begin(); + Query q = em.createNativeQuery(sqlString.toString()); + q.executeUpdate(); + t.commit(); + } + + private static void DropDenfityFunction() { + EntityManager em = emf.createEntityManager(); + EntityTransaction t = em.getTransaction(); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("DROP FUNCTION \"OLINGO\".\"PopulationDensity\""); + + t.begin(); + Query q = em.createNativeQuery(sqlString.toString()); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java new file mode 100644 index 0000000000..bab14bb695 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAFunctionOperator.java @@ -0,0 +1,96 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; + +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; + +public class TestJPAFunctionOperator { + private CriteriaBuilder cb; + private JPAFunctionOperator cut; + private UriResourceFunction uriFunction; + private JPAVisitor jpaVisitor; + private JPADataBaseFunction jpaFunction; + private JPAOperationResultParameter jpaResultParam; + private List uriParams; + + @BeforeEach + public void setUp() throws Exception { + + cb = mock(CriteriaBuilder.class); + jpaVisitor = mock(JPAVisitor.class); + when(jpaVisitor.getCriteriaBuilder()).thenReturn(cb); + uriFunction = mock(UriResourceFunction.class); + jpaFunction = mock(JPADataBaseFunction.class); + jpaResultParam = mock(JPAOperationResultParameter.class); + when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam); + List resources = new ArrayList<>(); + resources.add(uriFunction); + + uriParams = new ArrayList<>(); + + cut = new JPAFunctionOperator(jpaVisitor, uriParams, jpaFunction); + } + + @SuppressWarnings("unchecked") + @Test + public void testReturnsExpression() throws ODataApplicationException { + + final Expression[] jpaParameter = new Expression[0]; + + when(jpaFunction.getDBName()).thenReturn("Test"); + doReturn(new Integer(5).getClass()).when(jpaResultParam).getType(); + when(cb.function(jpaFunction.getDBName(), jpaResultParam.getType(), jpaParameter)).thenReturn(mock( + Expression.class)); + when(jpaFunction.getResultParameter()).thenReturn(jpaResultParam); + Expression act = cut.get(); + assertNotNull(act); + } + + @Test + public void testAbortOnNonFunctionReturnsCollection() { + + when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings"); + when(jpaResultParam.isCollection()).thenReturn(true); + + try { + cut.get(); + } catch (ODataApplicationException e) { + return; + } + fail("Function provided not checked"); + } + + @Test + public void testAbortOnNonScalarFunction() { + + when(jpaFunction.getDBName()).thenReturn("org.apache.olingo.jpa::Siblings"); + when(jpaResultParam.isCollection()).thenReturn(false); + doReturn(AdministrativeDivision.class).when(jpaResultParam).getType(); + + try { + cut.get(); + } catch (ODataApplicationException e) { + return; + } + fail("Function provided not checked"); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java new file mode 100644 index 0000000000..266c857cc5 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAOperationConverter.java @@ -0,0 +1,175 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; + +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; + +public class TestJPAOperationConverter { + private CriteriaBuilder cb; + + private Expression expressionLeft; + private Expression expressionRight; + private JPAOperationConverter cut; + private JPAODataDatabaseOperations extension; + + @SuppressWarnings("unchecked") + @BeforeEach + public void setUp() throws Exception { + cb = mock(CriteriaBuilder.class); + extension = mock(JPAODataDatabaseOperations.class); + cut = new JPAOperationConverter(cb, extension); + expressionLeft = mock(Path.class); + expressionRight = mock(Path.class); + } + + @Test + public void testAddMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.sum(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testAddMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.ADD); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.sum(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testSubMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.diff(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testSubMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.SUB); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.diff(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testDivMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.quot(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testDivMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.DIV); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.quot(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testMulMemberMember() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPAMemberOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsExpression()).thenReturn(expressionRight); + when(cb.prod(expressionLeft, expressionRight)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testMulMemberLiteral() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + @SuppressWarnings("unchecked") + Expression result = mock(Path.class); + when(operator.getRight()).thenReturn(mock(JPALiteralOperator.class)); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.MUL); + when(operator.getLeft(cb)).thenReturn(expressionLeft); + when(operator.getRightAsNumber(cb)).thenReturn(5); + when(cb.prod(expressionLeft, 5)).thenReturn(result); + + Expression act = cut.convert(operator); + assertEquals(result, act); + } + + @Test + public void testUnknownOperation_CallExtension() throws ODataApplicationException { + JPAArithmeticOperator operator = mock(JPAArithmeticOperatorImp.class); + when(operator.getOperator()).thenReturn(BinaryOperatorKind.AND); + when(extension.convert(operator)).thenThrow(new ODataApplicationException(null, HttpStatusCode.NOT_IMPLEMENTED + .getStatusCode(), null)); + + try { + cut.convert(operator); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + return; + } + fail("Exception expecetd"); + } +} + +//case MOD: \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java new file mode 100644 index 0000000000..b938590713 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAQueryWhereClause.java @@ -0,0 +1,911 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryWhereClause extends TestBase { + + @Test + public void testFilterOneEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID eq '3'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("3", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneDescriptionEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=LocationName eq 'Deutschland'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("10", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneDescriptionEqualsFieldNotSelected() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=LocationName eq 'Deutschland'&$select=ID"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("10", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEnumEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=ABCClass eq com.sap.olingo.jpa.ABCClassifiaction'A'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("1", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEqualsTwoProperties() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode eq CountryCode"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterOneEqualsInvert() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter='3' eq ID"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("3", orgs.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneNotEqual() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID ne '3'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(9, orgs.size()); + } + + @Test + public void testFilterOneEnumNotEqual() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights ne com.sap.olingo.jpa.AccessRights'Write'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("97", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneEnumEqualMultipleValues() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights eq com.sap.olingo.jpa.AccessRights'Read,Delete'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("97", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneGreaterEqualsString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID ge '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); // '10' is smaller than '5' when comparing strings! + } + + @Test + public void testFilterOneLowerThanTwoProperties() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode lt CountryCode"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(244, orgs.size()); + } + + @Test + public void testFilterOneGreaterThanString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID gt '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); // '10' is smaller than '5' when comparing strings! + } + + @Test + public void testFilterOneLowerThanString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID lt '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + } + + @Test + public void testFilterOneLowerEqualsString() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$filter=ID le '5'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(6, orgs.size()); + } + + @Test + public void testFilterOneGreaterEqualsNumber() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "AdministrativeDivisions?$filter=Area ge 119330610"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Disabled // TODO Clarify if GT, LE .. not supported by OData or "only" by Olingo + @Test + public void testFilterOneEnumGreaterThan() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights gt com.sap.olingo.jpa.AccessRights'Read'"); + helper.assertStatus(200); + + ArrayNode persons = helper.getValues(); + assertEquals(1, persons.size()); + assertEquals("99", persons.get(0).get("ID").asText()); + } + + @Test + public void testFilterOneAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterOneOrEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=ID eq '5' or ID eq '10'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterOneNotLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=not (Area lt 50000000)"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(24, orgs.size()); + } + + @Test + public void testFilterTwoAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and CodeID eq 'NUTS2' and DivisionCode eq 'BE25'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("BEL", orgs.get(0).get("CountryCode").asText()); + } + + @Test + public void testFilterAndOrEqualsParenthesis() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and (DivisionCode eq 'BE25' or DivisionCode eq 'BE24')&$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + assertEquals("BE25", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndOrEqualsNoParenthesis() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and DivisionCode eq 'BE25' or CodeID eq '3166-1'&$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + assertEquals("USA", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithFunction1() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(tolower(DivisionCode),tolower('BE1'))&$orderby=DivisionCode asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithFunction2() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and contains(DivisionCode,'BE1')&$orderby=DivisionCode asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAndWithComparisonContainingFunction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodePublisher eq 'Eurostat' and tolower(DivisionCode) eq tolower('BE1')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + assertEquals("BE1", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testFilterAddGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area add 7000000 ge 50000000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(31, orgs.size()); + } + + @Test + public void testFilterSubGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area sub 7000000 ge 60000000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(15, orgs.size()); + } + + @Test + public void testFilterDivGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area gt 0 and Area div Population ge 6000"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(9, orgs.size()); + } + + @Test + public void testFilterMulGreater() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area mul Population gt 0"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(64, orgs.size()); + } + + @Test + public void testFilterMod() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Area gt 0 and Area mod 3578335 eq 0"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterLength() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=length(Name) eq 10"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterNow() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AdministrativeInformation/Created/At lt now()"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testFilterContains() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=contains(CodeID,'166')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(110, orgs.size()); + } + + @Test + public void testFilterEndswith() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=endswith(CodeID,'166-1')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterStartswith() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=startswith(DivisionCode,'DE-')"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(16, orgs.size()); + } + + @Test + public void testFilterIndexOf() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=indexof(DivisionCode,'3') eq 4"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterSubstringStartIndex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,6) eq 'Dakota'"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterSubstringStartEndIndex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,5) eq 'North'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterSubstringLengthCalculated() throws IOException, ODataException { + // substring(CompanyName, 1 add 4, 2 mul 3) + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,0,1 add 4) eq 'North'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Disabled // Usage of mult currently creates parser error: The types 'Edm.Double' and '[Int64, Int32, Int16, Byte, + // SByte]' are not compatible. + @Test + public void testFilterSubstringStartCalculated() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and substring(Name,2 mul 3) eq 'Dakota'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterToLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(Name) eq 'brandenburg'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterToUpper() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and toupper(Name) eq 'HESSEN'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterToUpperInvers() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=toupper('nuts1') eq CodeID"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(19, orgs.size()); + } + + @Test + public void testFilterTrim() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and trim(Name) eq 'Sachsen'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterConcat() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=concat(concat(LastName,','),FirstName) eq 'Mustermann,Max'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Roles/any(d:d/RoleCategory eq 'A')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueNotAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=not (Roles/any(d:d/RoleCategory eq 'A'))"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(7, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAnyMultiParameter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/any(d:d/RoleCategory eq 'A' and d/BusinessPartnerID eq '1')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAnyNoRestriction() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Roles/any()"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToManyValueAll() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/all(d:d/RoleCategory eq 'A')"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterCountNavigationProperty() throws IOException, ODataException { + // https://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301 + // Example 43: return all Categories with less than 10 products + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Roles/$count eq 2"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterCountNavigationPropertyMultipleHops() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=AdministrativeInformation/Created/User/Roles/$count ge 2"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToOneValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(11, orgs.size()); + } + + @Test + public void testFilterNavigationPropertyToOneValueAndEquals() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE34'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyToOneValueTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/Parent/CodeID eq 'NUTS1' and DivisionCode eq 'BE212'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyToOneValueViaComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LastName eq 'Mustermann'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionViaComplexTypeWOSubselectSelectAll() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Address/RegionName eq 'Kalifornien'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionViaComplexTypeWOSubselectSelectId() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Address/RegionName eq 'Kalifornien'&$select=ID"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect1() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyDescriptionToOneValueViaComplexTypeWSubselect2() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=AdministrativeInformation/Created/User/LocationName eq 'Schweiz'&$select=ID"); + + helper.assertStatus(200); + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + }; + + @Test + public void testFilterNavigationPropertyAndExandThatNavigationProperty() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=Parent/DivisionCode eq 'BE2'&$expand=Parent"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(5, admin.size()); + assertNotNull(admin.get(3).findValue("Parent")); + assertFalse(admin.get(3).findValue("Parent") instanceof NullNode); + assertEquals("BE2", admin.get(3).findValue("Parent").get("DivisionCode").asText()); + }; + + @Test + public void testFilterNavigationPropertyViaJoinTableSubtype() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=SupportedOrganizations/any()"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Disabled // EclipsLinkProblem see https://bugs.eclipse.org/bugs/show_bug.cgi?id=529565 + @Test + public void testFilterNavigationPropertyViaJoinTableCountSubType() throws IOException, // NOSONAR + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=SupportedOrganizations/$count gt 1"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Test + public void testFilterMappedNavigationPropertyViaJoinTableSubtype() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=Name1&$filter=SupportEngineers/any(d:d/LastName eq 'Doe')"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(1, admin.size()); + assertEquals("First Org.", admin.get(0).findValue("Name1").asText()); + + }; + + @Test + public void testFilterNavigationPropertyViaJoinTableCount() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=Teams/$count eq 0&$select=ID"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(1, admin.size()); + assertEquals("98", admin.get(0).findValue("ID").asText()); + + }; + + @Test + public void testFilterMappedNavigationPropertyViaJoinTableFilter() throws IOException, + ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Teams?$select=Name&$filter=Member/any(d:d/LastName eq 'Mustermann')"); + + helper.assertStatus(200); + ArrayNode admin = helper.getValues(); + assertEquals(2, admin.size()); + }; + + @Test + public void testFilterWithAllExpand() throws ODataException, IOException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$filter=Name1 eq 'Third Org.'&$expand=Roles"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + assertEquals(3, org.get(0).get("Roles").size()); + } + + @Test + public void testFilterSubstringStartEndIndexToLower() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions?$filter=Language eq 'de' and tolower(substring(Name,0,5)) eq 'north'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testFilterOneHas() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$filter=AccessRights has com.sap.olingo.jpa.AccessRights'Read'"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testFilterNavigationTarget() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode result = (ObjectNode) div.get("value").get(0); + assertNotNull(result); + assertEquals("BE21", result.get("DivisionCode").asText()); + } + + @Test + public void testFilterCollectionSinplePropertyThrowsError() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=contains(Comment, 'just')"); + + helper.assertStatus(400); // Olingo rejects a bunch of functions. + } + + @Test + public void testFilterCollectionPropertyAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID&$filter=Comment/any(s:contains(s, 'just'))"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + } + + @Test + public void testFilterCollectionPropertyDeepSimpleCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Comment/$count eq 2&$select=ID"); + + helper.assertStatus(200); + ArrayNode deep = helper.getValues(); + assertNotNull(deep); + assertEquals(1, deep.size()); + } + + @Test + public void testFilterCollectionPropertyDeepComplexCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/$count eq 2&$select=ID"); + + helper.assertStatus(200); + ArrayNode deep = helper.getValues(); + assertNotNull(deep); + assertEquals(1, deep.size()); + } + + @Test + public void testFilterCollectionPropertyAsPartOfComplexAny() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$filter=FirstLevel/SecondLevel/Address/any(s:s/TaskID eq 'DEV')"); + + helper.assertStatus(200); + ArrayNode org = helper.getValues(); + assertNotNull(org); + assertEquals(1, org.size()); + } + + @Test + public void testFilterCollectionOnPropertyWithNavigation() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')/InhouseAddress?$filter=TaskID eq 'DEV'"); + + helper.assertStatus(200); + ArrayNode addr = helper.getValues(); + assertNotNull(addr); + assertEquals(1, addr.size()); + } + + @Test + public void testFilterCollectionPropertyWithOutNavigationThrowsError() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=InhouseAddress/TaskID eq 'DEV'"); + + helper.assertStatus(400); // The URI is malformed + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java new file mode 100644 index 0000000000..ae93f38177 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestJPAVisitor.java @@ -0,0 +1,82 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; + +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.database.JPAODataDatabaseOperations; +import com.sap.olingo.jpa.processor.core.query.JPAAbstractQuery; + +public class TestJPAVisitor { + + private JPAFilterComplierAccess compiler; + private JPAAbstractQuery query; + private JPAExpressionVisitor cut; + private JPAODataDatabaseOperations extension; + private JPAOperationConverter converter; + + @BeforeEach + public void setUp() { + extension = mock(JPAODataDatabaseOperations.class); + converter = new JPAOperationConverter(mock(CriteriaBuilder.class), extension); + compiler = mock(JPAFilterComplierAccess.class); + query = mock(JPAAbstractQuery.class); + + when(compiler.getConverter()).thenReturn(converter); + when(compiler.getParent()).thenReturn(query); + when(compiler.getDebugger()).thenReturn(mock(JPAServiceDebugger.class)); + when(query.getDebugger()).thenReturn(mock(JPAServiceDebugger.class)); + + cut = new JPAVisitor(compiler); + } + +//return new JPAFunctionOperator(jpaFunction, odataParams, this.jpaComplier.getParent().getRoot(), jpaComplier.getConverter().cb); + + @Test + public void createFunctionOperation() throws ExpressionVisitException, ODataApplicationException { + +// final UriResource resource = member.getResourcePath().getUriResourceParts().get(0); + Member member = mock(Member.class); + UriInfoResource info = mock(UriInfoResource.class); + UriResourceFunction uriFunction = mock(UriResourceFunction.class); + + List resources = new ArrayList<>(); + resources.add(uriFunction); + + when(member.getResourcePath()).thenReturn(info); + when(info.getUriResourceParts()).thenReturn(resources); +// final JPAFunction jpaFunction = this.jpaComplier.getSd().getFunction(((UriResourceFunction) resource).getFunction()); + JPAServiceDocument sd = mock(JPAServiceDocument.class); + JPADataBaseFunction jpaFunction = mock(JPADataBaseFunction.class); + EdmFunction edmFunction = mock(EdmFunction.class); + + when(uriFunction.getFunction()).thenReturn(edmFunction); + when(compiler.getSd()).thenReturn(sd); + when(sd.getFunction(edmFunction)).thenReturn(jpaFunction); + when(uriFunction.getParameters()).thenReturn(new ArrayList()); + + if (!(cut.visitMember(member) instanceof JPAFunctionOperator)) { + fail(); + } + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java new file mode 100644 index 0000000000..0bb04bee57 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/filter/TestRetrieveSingleEntity.java @@ -0,0 +1,49 @@ +package com.sap.olingo.jpa.processor.core.filter; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestRetrieveSingleEntity extends TestBase { + + @Test + public void testRetrieveWithOneKey() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("3", org.get("ID").asText()); + } + + @Test + public void testRetrieveWithTwoKeys() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("1", org.get("BusinessPartnerID").asText()); + assertEquals("A", org.get("RoleCategory").asText()); + } + + @Test + public void testRetrieveWithEmbeddedKey() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='en')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("en", org.get("Language").asText()); + assertEquals("NUTS1", org.get("CodeID").asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java new file mode 100644 index 0000000000..cc9e9f2252 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACUDRequestHelper.java @@ -0,0 +1,574 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.AttributeConverter; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlProperty; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.query.EdmEntitySetInfo; +import com.sap.olingo.jpa.processor.core.testmodel.ABCClassifiaction; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRights; +import com.sap.olingo.jpa.processor.core.testmodel.AccessRightsConverter; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DateConverter; + +public class TestJPACUDRequestHelper { + private JPAConversionHelper cut; + + @BeforeEach + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Test + public void testInstanceNull() { + + try { + cut.buildGetterMap(null); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testInstanceWithoutGetter() throws ODataJPAProcessorException { + + Map act = cut.buildGetterMap(new DateConverter()); + assertNotNull(act); + assertEquals(1, act.size()); + assertNotNull(act.get("class")); + } + + @Test + public void testInstanceWithGetter() throws ODataJPAProcessorException { + BusinessPartnerRole role = new BusinessPartnerRole(); + role.setBusinessPartnerID("ID"); + + Map act = cut.buildGetterMap(role); + assertNotNull(act); + assertEquals(5, act.size()); + assertEquals("ID", act.get("businessPartnerID")); + } + + @Test + public void testSameInstanceWhenReadingTwice() throws ODataJPAProcessorException { + BusinessPartnerRole role = new BusinessPartnerRole(); + + Map exp = cut.buildGetterMap(role); + Map act = cut.buildGetterMap(role); + + assertTrue(exp == act); + } + + @Disabled + @Test + public void testDifferentInstanceWhenReadingDifferentInstance() throws ODataJPAProcessorException { + + Map exp = cut.buildGetterMap(new BusinessPartnerRole("100", "A")); + Map act = cut.buildGetterMap(new BusinessPartnerRole("100", "A")); + + assertFalse(exp == act); + } + + @Test + public void testConvertEmptyInputStream() throws UnsupportedEncodingException { + final ODataRequest request = mock(ODataRequest.class); + final EdmEntitySetInfo etsInfo = mock(EdmEntitySetInfo.class); + final EdmEntitySet ets = mock(EdmEntitySet.class); + + final InputStream is = new ByteArrayInputStream("".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + when(etsInfo.getTargetEdmEntitySet()).thenReturn(ets); + + try { + cut.convertInputStream(OData.newInstance(), request, ContentType.APPLICATION_JSON, etsInfo); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertInputStream() throws UnsupportedEncodingException, ODataJPAProcessorException, + EdmPrimitiveTypeException { + + final ODataRequest request = mock(ODataRequest.class); + final EdmEntitySetInfo edmEntitySetInfo = mock(EdmEntitySetInfo.class); + final EdmEntitySet edmEntitySet = mock(EdmEntitySet.class); + final EdmEntityType edmEntityType = mock(EdmEntityType.class); + final EdmProperty edmPropertyId = mock(EdmProperty.class); + final EdmPrimitiveType edmTypeId = mock(EdmPrimitiveType.class); + + FullQualifiedName fqn = new FullQualifiedName("test", "Organisation"); + FullQualifiedName fqnString = new FullQualifiedName("test", "Organisation"); + + List propertyNames = new ArrayList<>(); + propertyNames.add("ID"); + + when(edmTypeId.getFullQualifiedName()).thenReturn(fqnString); + when(edmTypeId.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + when(edmTypeId.getName()).thenReturn("String"); + when(edmTypeId.valueOfString(ArgumentMatchers.anyString(), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyInt(), + ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), + (Class) ArgumentMatchers.any())).thenReturn("35"); + + when(edmEntitySet.getEntityType()).thenReturn(edmEntityType); + when(edmEntityType.getFullQualifiedName()).thenReturn(fqn); + when(edmEntityType.getPropertyNames()).thenReturn(propertyNames); + when(edmEntityType.getProperty("ID")).thenReturn(edmPropertyId); + when(edmPropertyId.getName()).thenReturn("ID"); + when(edmPropertyId.getType()).thenReturn(edmTypeId); + when(edmEntitySetInfo.getEdmEntitySet()).thenReturn(edmEntitySet); + when(edmEntitySetInfo.getTargetEdmEntitySet()).thenReturn(edmEntitySet); + InputStream is = new ByteArrayInputStream("{\"ID\" : \"35\"}".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + + Entity act = cut.convertInputStream(OData.newInstance(), request, ContentType.APPLICATION_JSON, edmEntitySetInfo); + assertEquals("35", act.getProperty("ID").getValue()); + } + + @Test + public void testConvertPropertiesEmptyList() throws ODataJPAProcessException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(0, act.size()); + } + + @Test + public void testConvertPropertiesUnknownValueType() { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + + when(propertyID.getValueType()).thenReturn(ValueType.COLLECTION_ENTITY); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + try { + cut.convertProperties(OData.newInstance(), st, odataProperties); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertPropertiesConvertException() throws ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("iD"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + when(st.getPath(ArgumentMatchers.anyString())).thenThrow(new ODataJPAModelException(new NullPointerException())); + try { + cut.convertProperties(OData.newInstance(), st, odataProperties); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertPropertiesOnePrimitiveProperty() throws ODataJPAProcessException, ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ID")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("iD"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return String.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("35", act.get("iD")); + } + + @Test + public void testConvertPropertiesOneEnumPropertyWithoutConverter() throws ODataJPAProcessException, + ODataJPAModelException { + + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ABCClass")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("aBCClass"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return ABCClassifiaction.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(attribute.isEnum()).thenReturn(true); + when(propertyID.getValueType()).thenReturn(ValueType.ENUM); + when(propertyID.getName()).thenReturn("ABCClass"); + when(propertyID.getValue()).thenReturn(1); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals(ABCClassifiaction.B, act.get("aBCClass")); + } + + @Test + public void testConvertPropertiesOneEnumPropertyWithConverter() throws ODataJPAProcessException, + ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath path = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("AccessRights")).thenReturn(path); + when(path.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("accessRights"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return AccessRights.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(attribute.getConverter()).thenAnswer(new Answer>() { + @Override + public AttributeConverter answer(InvocationOnMock invocation) throws Throwable { + return new AccessRightsConverter(); + } + }); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.ENUM); + when(propertyID.getName()).thenReturn("AccessRights"); + when(propertyID.getValue()).thenReturn((short) 8); + odataProperties.add(propertyID); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(1, act.size()); + AccessRights[] actProperty = (AccessRights[]) act.get("accessRights"); + assertArrayEquals(new Object[] { AccessRights.Delete }, actProperty); + } + + @Test + public void testConvertPropertiesOneComplexProperty() throws ODataJPAProcessException, ODataJPAModelException { + List odataProperties = new ArrayList<>(); + JPAStructuredType st = mock(JPAStructuredType.class); + Property propertyID = mock(Property.class); + JPAAttribute attribute = mock(JPAAttribute.class); + JPAPath pathID = mock(JPAPath.class); + CsdlProperty edmProperty = mock(CsdlProperty.class); + + when(st.getPath("ID")).thenReturn(pathID); + when(pathID.getLeaf()).thenReturn(attribute); + when(attribute.getInternalName()).thenReturn("iD"); + + Answer a = (new Answer() { + @Override + public Object answer(InvocationOnMock invocation) { + return String.class; + } + }); + when(attribute.getType()).thenAnswer(a); + when(attribute.getProperty()).thenReturn(edmProperty); + when(edmProperty.getMaxLength()).thenReturn(100); + when(propertyID.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.getValue()).thenReturn("35"); + odataProperties.add(propertyID); + + ComplexValue cv = new ComplexValue(); + List addressPathElements = new ArrayList<>(); + JPAElement addressElement = mock(JPAElement.class); + addressPathElements.add(addressElement); + when(addressElement.getInternalName()).thenReturn("address"); + + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(cv); + odataProperties.add(propertyAddress); + JPAPath pathAddress = mock(JPAPath.class); + when(st.getPath("Address")).thenReturn(pathAddress); + when(pathAddress.getPath()).thenReturn(addressPathElements); + JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + + assertNotNull(act); + assertEquals(2, act.size()); + assertTrue(act.get("address") instanceof Map); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesOneComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final List addressProperties = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + final ComplexValue cv1 = mock(ComplexValue.class); + + final Property propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(32); + addressProperties.add(propertyNumber); + when(cv1.getValue()).thenReturn(addressProperties); + + odataComment.add(cv1); + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(1, ((List>) act.get("address")).size()); + Map actAddr = (Map) ((List) act.get("address")).get(0); + assertEquals(32, actAddr.get("number")); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesTwoComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + List addressProperties = new ArrayList<>(); + final ComplexValue cv1 = mock(ComplexValue.class); + Property propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(32); + addressProperties.add(propertyNumber); + when(cv1.getValue()).thenReturn(addressProperties); + + addressProperties = new ArrayList<>(); + final ComplexValue cv2 = mock(ComplexValue.class); + propertyNumber = mock(Property.class); + when(propertyNumber.getValueType()).thenReturn(ValueType.PRIMITIVE); + when(propertyNumber.getName()).thenReturn("Number"); + when(propertyNumber.getValue()).thenReturn(16); + addressProperties.add(propertyNumber); + when(cv2.getValue()).thenReturn(addressProperties); + + odataComment.add(cv1); + odataComment.add(cv2); + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(2, ((List>) act.get("address")).size()); + Map actAddr1 = (Map) ((List) act.get("address")).get(0); + assertEquals(32, actAddr1.get("number")); + + Map actAddr2 = (Map) ((List) act.get("address")).get(1); + assertEquals(16, actAddr2.get("number")); + } + + @SuppressWarnings("unchecked") + @Test + public void testConvertPropertiesEmptyComplexCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + final JPAStructuredType st = createMetadataForSimpleProperty("Address", "address"); + final JPAStructuredType nb = createMetadataForSimpleProperty("Number", "number"); + final JPAAttribute attributeAddress = mock(JPAAttribute.class); + when(attributeAddress.getStructuredType()).thenReturn(nb); + when(st.getAttribute("address")).thenReturn(attributeAddress); + + Property propertyAddress = mock(Property.class); + when(propertyAddress.getValueType()).thenReturn(ValueType.COLLECTION_COMPLEX); + when(propertyAddress.getName()).thenReturn("Address"); + when(propertyAddress.getValue()).thenReturn(odataComment); + odataProperties.add(propertyAddress); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("address")); + assertEquals(0, ((List>) act.get("address")).size()); + } + + @Test + public void testConvertPropertiesOneSimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + odataComment.add("First Test"); + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertEquals(1, ((List) act.get("comment")).size()); + assertEquals("First Test", ((List) act.get("comment")).get(0)); + } + + @Test + public void testConvertPropertiesTwoSimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + odataComment.add("First Test"); + odataComment.add("Second Test"); + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertEquals(2, ((List) act.get("comment")).size()); + assertEquals("First Test", ((List) act.get("comment")).get(0)); + assertEquals("Second Test", ((List) act.get("comment")).get(1)); + } + + @Test + public void testConvertPropertiesEmptySimpleCollcetionProperty() throws ODataJPAProcessException, + ODataJPAModelException { + final List odataProperties = new ArrayList<>(); + final List odataComment = new ArrayList<>(); + + final JPAStructuredType st = createMetadataForSimpleProperty("Comment", "comment"); + + Property propertyComment = mock(Property.class); + when(propertyComment.getValueType()).thenReturn(ValueType.COLLECTION_PRIMITIVE); + when(propertyComment.getName()).thenReturn("Comment"); + when(propertyComment.getValue()).thenReturn(odataComment); + odataProperties.add(propertyComment); + + Map act = cut.convertProperties(OData.newInstance(), st, odataProperties); + assertNotNull(act.get("comment")); + assertTrue(((List) act.get("comment")).isEmpty()); + } + + private JPAStructuredType createMetadataForSimpleProperty(final String externalName, final String internalName) + throws ODataJPAModelException { + final JPAStructuredType st = mock(JPAStructuredType.class); + final JPAAttribute attribute = mock(JPAAttribute.class); + final JPAPath pathID = mock(JPAPath.class); + final List pathElements = new ArrayList<>(); + pathElements.add(attribute); + when(st.getPath(externalName)).thenReturn(pathID); + when(pathID.getLeaf()).thenReturn(attribute); + when(pathID.getPath()).thenReturn(pathElements); + when(attribute.getInternalName()).thenReturn(internalName); + return st; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java new file mode 100644 index 0000000000..d24b037dc9 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelper.java @@ -0,0 +1,210 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmStructuredType; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.deserializer.DeserializerException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriHelper; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; + +public abstract class TestJPAConversionHelper { + + protected JPAConversionHelper cut; + protected EdmEntitySet edmEntitySet; + protected ODataRequest request; + protected OData odata; + protected JPAEntityType et; + + public TestJPAConversionHelper() { + super(); + } + + @Test + public abstract void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + @Test + public abstract void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + @Test + public abstract void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException; + + protected void prepareConvertCompoundKeyToLocation() throws ODataJPAModelException, + SerializerException, ODataJPAProcessorException { + + final List keyPath = new ArrayList<>(); + + request = mock(ODataRequest.class); + et = mock(JPAEntityType.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + when(et.getKeyPath()).thenReturn(keyPath); + edmEntitySet = mock(EdmEntitySet.class); + + addKeyAttribute(keyPath, "BusinessPartnerID", "businessPartnerID"); + addKeyAttribute(keyPath, "RoleCategory", "roleCategory"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.COMPOUND_KEY); + when(odata.createUriHelper()).thenReturn(uriHelper); + } + + protected void prepareConvertSimpleKeyToLocation() throws ODataJPAModelException { + final List keyPath = new ArrayList<>(); + + request = mock(ODataRequest.class); + et = mock(JPAEntityType.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + edmEntitySet = mock(EdmEntitySet.class); + when(et.getKeyPath()).thenReturn(keyPath); + + addKeyAttribute(keyPath, "ID", "iD"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.SINGLE); + when(odata.createUriHelper()).thenReturn(uriHelper); + } + + void addKeyAttribute(final List keyPath, final String externalName, final String internalName) { + JPAPath key; + JPAAttribute keyAttribute; + key = mock(JPAPath.class); + keyPath.add(key); + keyAttribute = mock(JPAAttribute.class); + when(keyAttribute.getExternalName()).thenReturn(externalName); + when(keyAttribute.getInternalName()).thenReturn(internalName); + when(key.getLeaf()).thenReturn(keyAttribute); + } + + protected void prepareConvertEmbeddedIdToLocation() throws ODataJPAModelException { + List keyPath = new ArrayList<>(); + + request = mock(ODataRequest.class); + when(request.getRawBaseUri()).thenReturn("localhost.test"); + + edmEntitySet = mock(EdmEntitySet.class); + et = mock(JPAEntityType.class); + when(et.getKeyPath()).thenReturn(keyPath); + JPAPath key = mock(JPAPath.class); + keyPath.add(key); + JPAAttribute keyAttribute = mock(JPAAttribute.class); + when(keyAttribute.getExternalName()).thenReturn("Key"); + when(keyAttribute.getInternalName()).thenReturn("key"); + when(keyAttribute.isComplex()).thenReturn(true); + when(keyAttribute.isKey()).thenReturn(true); + when(key.getLeaf()).thenReturn(keyAttribute); + + JPAStructuredType st = mock(JPAStructuredType.class); + when(keyAttribute.getStructuredType()).thenReturn(st); + keyPath = new ArrayList<>(); + when(st.getPathList()).thenReturn(keyPath); + + addKeyAttribute(keyPath, "CodeID", "codeID"); + addKeyAttribute(keyPath, "CodePublisher", "codePublisher"); + addKeyAttribute(keyPath, "DivisionCode", "divisionCode"); + addKeyAttribute(keyPath, "Language", "language"); + + odata = mock(OData.class); + UriHelper uriHelper = new UriHelperSpy(UriHelperSpy.EMBEDDED_ID); + when(odata.createUriHelper()).thenReturn(uriHelper); + + } + + class UriHelperSpy implements UriHelper { + public static final String EMBEDDED_ID = "EmbeddedId"; + public static final String COMPOUND_KEY = "CompoundKey"; + public static final String SINGLE = "SingleID"; + private final String mode; + + public UriHelperSpy(String mode) { + this.mode = mode; + } + + @Override + public String buildCanonicalURL(EdmEntitySet edmEntitySet, Entity entity) throws SerializerException { + if (mode.equals(EMBEDDED_ID)) { + assertEquals(4, entity.getProperties().size()); + int found = 0; + for (final Property property : entity.getProperties()) { + if (property.getName().equals("DivisionCode") && property.getValue().equals("BE1")) + found++; + else if (property.getName().equals("Language") && property.getValue().equals("fr")) + found++; + } + assertEquals(2, found, "Not all key attributes found"); + return "AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')"; + } else if (mode.equals(COMPOUND_KEY)) { + assertEquals(2, entity.getProperties().size()); + int found = 0; + for (final Property property : entity.getProperties()) { + if (property.getName().equals("BusinessPartnerID") && property.getValue().equals("35")) + found++; + else if (property.getName().equals("RoleCategory") && property.getValue().equals("A")) + found++; + } + assertEquals(2, found, "Not all key attributes found"); + return "BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')"; + } else if (mode.equals(SINGLE)) { + assertEquals(1, entity.getProperties().size()); + assertEquals("35", entity.getProperties().get(0).getValue()); + return "Organisation('35')"; + } + fail(); + return null; + + } + + @Override + public String buildContextURLKeyPredicate(List keys) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildContextURLSelectList(EdmStructuredType type, ExpandOption expand, SelectOption select) + throws SerializerException { + fail(); + return null; + } + + @Override + public String buildKeyPredicate(EdmEntityType edmEntityType, Entity entity) throws SerializerException { + fail(); + return null; + } + + @Override + public UriResourceEntitySet parseEntityId(Edm edm, String entityId, String rawServiceRoot) + throws DeserializerException { + fail(); + return null; + } + + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java new file mode 100644 index 0000000000..0929934650 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperEntity.java @@ -0,0 +1,71 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAConversionHelperEntity extends TestJPAConversionHelper { + + @BeforeEach + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Override + @Test + public void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Organization newPOJO = new Organization(); + newPOJO.setID("35"); + + prepareConvertSimpleKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/Organisation('35')", act); + } + + @Override + @Test + public void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + BusinessPartnerRole newPOJO = new BusinessPartnerRole(); + newPOJO.setBusinessPartnerID("35"); + newPOJO.setRoleCategory("A"); + + prepareConvertCompoundKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')", act); + } + + @Override + @Test + public void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + AdministrativeDivisionDescription newPOJO = new AdministrativeDivisionDescription(); + AdministrativeDivisionDescriptionKey primaryKey = new AdministrativeDivisionDescriptionKey(); + primaryKey.setCodeID("NUTS1"); + primaryKey.setCodePublisher("Eurostat"); + primaryKey.setDivisionCode("BE1"); + primaryKey.setLanguage("fr"); + newPOJO.setKey(primaryKey); + + prepareConvertEmbeddedIdToLocation(); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals( + "localhost.test/AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')", + act); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java new file mode 100644 index 0000000000..7f8701a96e --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAConversionHelperMap.java @@ -0,0 +1,76 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAConversionHelperMap extends TestJPAConversionHelper { + @BeforeEach + public void setUp() throws Exception { + cut = new JPAConversionHelper(); + } + + @Override + public void testConvertCompoundKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap<>(); + newPOJO.put("businessPartnerID", "35"); + newPOJO.put("roleCategory", "A"); + + prepareConvertCompoundKeyToLocation(); + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/BusinessPartnerRoles(BusinessPartnerID='35',RoleCategory='A')", act); + } + + @Override + public void testConvertEmbeddedIdToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap<>(); + Map primaryKey = new HashMap<>(); + + primaryKey.put("codeID", "NUTS1"); + primaryKey.put("codePublisher", "Eurostat"); + primaryKey.put("divisionCode", "BE1"); + primaryKey.put("language", "fr"); + newPOJO.put("key", primaryKey); + + prepareConvertEmbeddedIdToLocation(); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals( + "localhost.test/AdministrativeDivisionDescriptions(DivisionCode='BE1',CodeID='NUTS1',CodePublisher='Eurostat',Language='fr')", + act); + } + + @Override + public void testConvertSimpleKeyToLocation() throws ODataJPAProcessorException, SerializerException, + ODataJPAModelException { + + Map newPOJO = new HashMap<>(); + newPOJO.put("iD", "35"); + + prepareConvertSimpleKeyToLocation(); + when(et.getTypeClass()).then(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Organization.class; + } + }); + + String act = cut.convertKeyToLocal(odata, request, edmEntitySet, et, newPOJO); + assertEquals("localhost.test/Organisation('35')", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java new file mode 100644 index 0000000000..5acdfa5625 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPACreateResult.java @@ -0,0 +1,280 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.Tuple; +import javax.persistence.TupleElement; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPACollectionResult; +import com.sap.olingo.jpa.processor.core.converter.JPAExpandResult; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public abstract class TestJPACreateResult extends TestBase { + + protected JPAExpandResult cut; + protected JPAEntityType et; + protected Map> headers; + protected Object jpaEntity; + protected JPATupleChildConverter converter; + + public TestJPACreateResult() { + super(); + } + + @Test + public void testGetChildrenProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + + createCutProvidesEmptyMap(); + + Map act = cut.getChildren(); + + assertNotNull(act); + assertEquals(1, act.size()); + } + + @Test + public void testGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("BusinessPartnerRoles"); + + createCutGetResultSimpleEntity(); + + List act = cut.getResult("root"); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("34", act.get(0).get("BusinessPartnerID")); + } + + @Test + public void testGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisionDescriptions"); + + createCutGetResultWithOneLevelEmbedded(); + + List act = cut.getResult("root"); + + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("A", act.get(0).get("CodeID")); + assertEquals("Hugo", act.get(0).get("Name")); + } + + @Test + public void testGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + + createCutGetResultWithTwoLevelEmbedded(); + + List act = cut.getResult("root"); + assertNotNull(act); + assertEquals(1, act.size()); + assertEquals("01", act.get(0).get("ID")); + assertEquals("99", act.get(0).get("AdministrativeInformation/Created/By")); + } + + @Test + public void testGetResultWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithOneLinked(); + Map act = cut.getChildren(); + assertNotNull(act); + assertEquals(1, act.size()); + for (JPAAssociationPath actPath : act.keySet()) { + assertEquals("Children", actPath.getAlias()); + List subResult = act.get(actPath).getResult("Eurostat/NUTS1/BE2"); + assertEquals(1, subResult.size()); + } + } + + @Test + public void testGetResultWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithTwoLinked(); + Map act = cut.getChildren(); + assertNotNull(act); + assertEquals(1, act.size()); + for (JPAAssociationPath actPath : act.keySet()) { + assertEquals("Children", actPath.getAlias()); + List subResult = act.get(actPath).getResult("Eurostat/NUTS1/BE2"); + assertEquals(2, subResult.size()); + } + } + + @Test + public void testGetResultWithPrimitiveCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithSimpleCollection(); + + final Map act = cut.getChildren(); + assertDoesNotContain(cut.getResult("root"), "Comment"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Comment", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((String) o).isEmpty()); + } + } + } + + @Test + public void testGetResultWithComplexCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithComplexCollection(); + + Map act = cut.getChildren(); + assertDoesNotContain(cut.getResult("root"), "InhouseAddress"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("InhouseAddress", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + + @Test + public void testGetResultWithComplexContainingCollection() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultEntityWithComplexWithCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "Complex/Address"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("Complex/Address")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Complex/Address", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + @Test + public void testGetResultWithContainingNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + createCutGetResultEntityWithNestedComplexCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "Nested"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("Nested")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("Nested", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + @Test + public void testGetResultWithDeepComplexContainingCollection() throws ODataJPAModelException, + ODataApplicationException { + createCutGetResultEntityWithDeepComplexWithCollection(); + + final Map act = cut.getChildren(); + boolean found = false; + assertDoesNotContain(cut.getResult("root"), "FirstLevel/SecondLevel/Address"); + assertNotNull(act); + assertFalse(act.isEmpty()); + for (Entry entity : act.entrySet()) { + if (entity.getKey().getAlias().equals("FirstLevel/SecondLevel/Address")) { + found = true; + assertEquals(1, entity.getValue().getResults().size()); + assertEquals("FirstLevel/SecondLevel/Address", entity.getKey().getAlias()); + final Collection actConverted = ((JPACollectionResult) entity.getValue()).getPropertyCollection( + JPAExpandResult.ROOT_RESULT_KEY); + assertEquals(2, actConverted.size()); + for (Object o : actConverted) { + assertNotNull(o); + assertFalse(((ComplexValue) o).getValue().isEmpty()); + } + } + } + assertTrue(found); + } + + private void assertDoesNotContain(final List result, final String prefix) { + for (Tuple t : result) { + for (TupleElement e : t.getElements()) + assertFalse(e.getAlias().startsWith(prefix), e.getAlias() + " violates prefix check: " + prefix); + } + + } + + protected abstract void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException; + + protected abstract void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException; + + protected abstract void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException; + + protected abstract void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException; +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java new file mode 100644 index 0000000000..9b95152679 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAEntityResult.java @@ -0,0 +1,230 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.CollcetionInnerComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollcetionNestedComplex; +import com.sap.olingo.jpa.processor.core.testmodel.Collection; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionDeep; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionFirstLevelComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionPartOfComplex; +import com.sap.olingo.jpa.processor.core.testmodel.CollectionSecondLevelComplex; +import com.sap.olingo.jpa.processor.core.testmodel.InhouseAddress; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAEntityResult extends TestJPACreateResult { + @BeforeEach + public void setUp() throws Exception { + headers = new HashMap<>(); + jpaEntity = new Organization(); + helper = new TestHelper(emf, PUNIT_NAME); + et = helper.getJPAEntityType("Organizations"); + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + } + + @Override + protected void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + jpaEntity = new BusinessPartnerRole(); + ((BusinessPartnerRole) jpaEntity).setBusinessPartnerID("34"); + ((BusinessPartnerRole) jpaEntity).setRoleCategory("A"); + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + AdministrativeDivisionDescriptionKey key = new AdministrativeDivisionDescriptionKey(); + key.setCodeID("A"); + key.setLanguage("en"); + jpaEntity = new AdministrativeDivisionDescription(); + ((AdministrativeDivisionDescription) jpaEntity).setName("Hugo"); + ((AdministrativeDivisionDescription) jpaEntity).setKey(key); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException { + + jpaEntity = new Organization(); + ((Organization) jpaEntity).onCreate(); + ((Organization) jpaEntity).setID("01"); + ((Organization) jpaEntity).setCustomString1("Dummy"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisions"); + jpaEntity = new AdministrativeDivision(); + AdministrativeDivision child = new AdministrativeDivision(); + List children = new ArrayList<>(); + children.add(child); + ((AdministrativeDivision) jpaEntity).setChildren(children); + + child.setCodeID("NUTS2"); + child.setDivisionCode("BE21"); + child.setCodePublisher("Eurostat"); + + ((AdministrativeDivision) jpaEntity).setCodeID("NUTS1"); + ((AdministrativeDivision) jpaEntity).setDivisionCode("BE2"); + ((AdministrativeDivision) jpaEntity).setCodePublisher("Eurostat"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + createCutGetResultWithWithOneLinked(); + + AdministrativeDivision child = new AdministrativeDivision(); + List children = ((AdministrativeDivision) jpaEntity).getChildren(); + children.add(child); + + child.setCodeID("NUTS2"); + child.setDivisionCode("BE22"); + child.setCodePublisher("Eurostat"); + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } + + @Override + protected void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException { + + final Organization org = new Organization(); + final List comment = org.getComment(); + comment.add("First"); + comment.add("Second"); + org.setID("1"); + jpaEntity = org; + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Persons"); + + final Person person = new Person(); + final List addresses = person.getInhouseAddress(); + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = person; + + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Collections"); + + final Collection collection = new Collection(); + final CollectionPartOfComplex complex = new CollectionPartOfComplex(); + final List addresses = complex.getAddress(); + complex.setNumber(2L); + collection.setComplex(complex); + + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + } + + @Override + protected void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("Collections"); + + final Collection collection = new Collection(); + final List nested = collection.getNested(); + + CollcetionNestedComplex nestedItem = new CollcetionNestedComplex(); + CollcetionInnerComplex inner = new CollcetionInnerComplex(); + inner.setFigure1(1L); + inner.setFigure3(3L); + nestedItem.setInner(inner); + nestedItem.setNumber(100L); + nested.add(nestedItem); + + nestedItem = new CollcetionNestedComplex(); + inner = new CollcetionInnerComplex(); + inner.setFigure1(11L); + inner.setFigure3(13L); + nestedItem.setInner(inner); + nestedItem.setNumber(200L); + nested.add(nestedItem); + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } + + @Override + protected void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("CollectionDeeps"); + + final CollectionDeep collection = new CollectionDeep(); + final CollectionFirstLevelComplex firstLevel = new CollectionFirstLevelComplex(); + final CollectionSecondLevelComplex secondLevel = new CollectionSecondLevelComplex(); + + final List addresses = secondLevel.getAddress(); + collection.setID("27"); + collection.setFirstLevel(firstLevel); + firstLevel.setLevelID(3); + firstLevel.setSecondLevel(secondLevel); + + InhouseAddress addr = new InhouseAddress(); + addr.setBuilding("A"); + addr.setTaskID("DEV"); + addresses.add(addr); + addr = new InhouseAddress(); + addr.setBuilding("C"); + addr.setTaskID("MAIN"); + addresses.add(addr); + + jpaEntity = collection; + cut = new JPAEntityResult(et, jpaEntity, headers, converter); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java new file mode 100644 index 0000000000..21ff14b713 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/modify/TestJPAMapResult.java @@ -0,0 +1,246 @@ +package com.sap.olingo.jpa.processor.core.modify; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAMapResult extends TestJPACreateResult { + List children; + + @BeforeEach + public void setUp() throws Exception { + headers = new HashMap<>(); + jpaEntity = new HashMap(); + helper = new TestHelper(emf, PUNIT_NAME); + et = helper.getJPAEntityType("Organizations"); + children = new ArrayList<>(); + converter = new JPATupleChildConverter(helper.sd, OData.newInstance() + .createUriHelper(), new ServiceMetadataDouble(nameBuilder, "Organizations")); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutProvidesEmptyMap() throws ODataJPAModelException, ODataApplicationException { + // Make Map equal to empty Organization instance + ((Map) jpaEntity).put("type", "2"); + ((Map) jpaEntity).put("comment", new ArrayList(1)); + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultSimpleEntity() throws ODataJPAModelException, ODataApplicationException { + + ((Map) jpaEntity).put("businessPartnerID", "34"); + ((Map) jpaEntity).put("roleCategory", "A"); + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithOneLevelEmbedded() throws ODataJPAModelException, ODataApplicationException { + + Map key = new HashMap<>(); + key.put("codeID", "A"); + key.put("language", "en"); + + ((Map) jpaEntity).put("name", "Hugo"); + ((Map) jpaEntity).put("key", key); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithTwoLevelEmbedded() throws ODataJPAModelException, + ODataApplicationException { + + long time = new Date().getTime(); + Map created = new HashMap<>(); + created.put("by", "99"); + created.put("at", new Timestamp(time)); + + Map admin = new HashMap<>(); + admin.put("created", created); + admin.put("updated", created); + + ((Map) jpaEntity).put("iD", "01"); + ((Map) jpaEntity).put("customString1", "Dummy"); + ((Map) jpaEntity).put("administrativeInformation", admin); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithWithOneLinked() throws ODataJPAModelException, ODataApplicationException { + prepareAdminWithChildren(); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultWithWithTwoLinked() throws ODataJPAModelException, ODataApplicationException { + prepareAdminWithChildren(); + + Map childProperties = new HashMap<>(); + JPARequestEntity child = mock(JPARequestEntity.class); + when(child.getEntityType()).thenReturn(et); + when(child.getData()).thenReturn(childProperties); + childProperties.put("codeID", "NUTS2"); + childProperties.put("divisionCode", "BE22"); + childProperties.put("codePublisher", "Eurostat"); + children.add(child); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + private void prepareAdminWithChildren() throws ODataJPAModelException, ODataApplicationException { + et = helper.getJPAEntityType("AdministrativeDivisions"); + + ((Map) jpaEntity).put("codeID", "NUTS1"); + ((Map) jpaEntity).put("divisionCode", "BE2"); + ((Map) jpaEntity).put("codePublisher", "Eurostat"); + + Map childProperties = new HashMap<>(); + + JPARequestEntity child = mock(JPARequestEntity.class); + when(child.getEntityType()).thenReturn(et); + when(child.getData()).thenReturn(childProperties); + childProperties.put("codeID", "NUTS2"); + childProperties.put("divisionCode", "BE21"); + childProperties.put("codePublisher", "Eurostat"); + children.add(child); + ((Map) jpaEntity).put("children", children); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithSimpleCollection() throws ODataJPAModelException, + ODataApplicationException { + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("comment", Arrays.asList("First", "Second")); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Persons"); + + ((Map) jpaEntity).put("iD", "1"); + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + ((Map) jpaEntity).put("inhouseAddress", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("Collections"); + final Map complex = new HashMap<>(); + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("complex", complex); + complex.put("number", 2L); + + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + complex.put("address", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithNestedComplexCollection() throws ODataJPAModelException, + ODataApplicationException { + et = helper.getJPAEntityType("Collections"); + + ((Map) jpaEntity).put("iD", "1"); + + final Map nested1 = new HashMap<>(); + final Map nested2 = new HashMap<>(); + final Map inner1 = new HashMap<>(); + final Map inner2 = new HashMap<>(); + + nested1.put("inner", inner1); + nested2.put("inner", inner2); + nested1.put("number", 100L); + nested1.put("number", 200L); + + inner1.put("figure1", 1L); + inner1.put("figure3", 3L); + inner2.put("figure1", 11L); + inner2.put("figure3", 13L); + ((Map) jpaEntity).put("nested", Arrays.asList(nested1, nested2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } + + @SuppressWarnings("unchecked") + @Override + protected void createCutGetResultEntityWithDeepComplexWithCollection() throws ODataJPAModelException, + ODataApplicationException { + + et = helper.getJPAEntityType("CollectionDeeps"); + final Map firstLevel = new HashMap<>(); + final Map secondLevel = new HashMap<>(); + + ((Map) jpaEntity).put("iD", "1"); + ((Map) jpaEntity).put("firstLevel", firstLevel); + firstLevel.put("levelID", 2); + firstLevel.put("secondLevel", secondLevel); + secondLevel.put("number", 2L); + final Map addr1 = new HashMap<>(); + final Map addr2 = new HashMap<>(); + + addr1.put("building", "A"); + addr1.put("taskID", "DEV"); + addr2.put("building", "C"); + addr2.put("taskID", "MAIN"); + secondLevel.put("address", Arrays.asList(addr1, addr2)); + + cut = new JPAMapResult(et, (Map) jpaEntity, headers, converter); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java new file mode 100644 index 0000000000..9d8ccdf042 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateDeltaBasedResult.java @@ -0,0 +1,161 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestCreateDeltaBasedResult extends TestJPAModifyProcessor { + private JPACUDRequestProcessor cut; + private List pathElements; + private Person beforeImagePerson; + private Person currentImagePerson; + private JPAAssociationPath path; + + @BeforeEach + public void setup() throws ODataException { + cut = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, new JPAConversionHelper()); + pathElements = new ArrayList<>(3); + path = mock(JPAAssociationPath.class); + + beforeImagePerson = new Person(); + beforeImagePerson.setID("1"); + currentImagePerson = new Person(); + currentImagePerson.setID("1"); + when(em.contains(beforeImagePerson)).thenReturn(Boolean.FALSE); + } + + @Test + public void testShallReturnNullIfBeforeImageNotPresent() throws ODataJPAProcessorException { + + final JPAAssociationPath path = mock(JPAAssociationPath.class); + final JPAElement pathItem = mock(JPAElement.class); + pathElements.add(pathItem); + when(pathItem.getInternalName()).thenReturn("roles"); + final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.empty()); + assertNull(act); + } + + @Test + public void testThrowsExceptionIfBeforeIfManaged() throws ODataJPAProcessorException { + when(em.contains(beforeImagePerson)).thenReturn(Boolean.TRUE); + assertThrows(ODataJPAProcessorException.class, () -> { + cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable(beforeImagePerson)); + }); + } + + @Test + public void testShallReturnNullIfTargetEmpty() throws ODataJPAProcessorException { + + prepareRole(); + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertNull(act); + } + + @Test + public void testShallReturnNullIfNoDeltaFound() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole beforeRole = new BusinessPartnerRole(); + beforeRole.setBusinessPartner(beforeImagePerson); + beforeRole.setRoleCategory("A"); + beforeImagePerson.getRoles().add(beforeRole); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(beforeImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertNull(act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeEmpty() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole exp = new BusinessPartnerRole(); + exp.setBusinessPartner(currentImagePerson); + exp.setRoleCategory("A"); + currentImagePerson.getRoles().add(exp); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeOneNowTwo() throws ODataJPAProcessorException { + + prepareRole(); + final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A"); + currentImagePerson.getRoles().add(exp); + + currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B")); + beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B")); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnsValueIfDeltaFoundBeforeOneNowTwoInversOrder() throws ODataJPAProcessorException { + + prepareRole(); + currentImagePerson.getRoles().add(new BusinessPartnerRole(currentImagePerson, "B")); + beforeImagePerson.getRoles().add(new BusinessPartnerRole(beforeImagePerson, "B")); + final BusinessPartnerRole exp = new BusinessPartnerRole(currentImagePerson, "A"); + currentImagePerson.getRoles().add(exp); + + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + @Test + public void testShallReturnNewValueIfNotACollection() throws ODataJPAProcessorException { + final CommunicationData exp = prepareBeforeImageCommunicationData(); + beforeImagePerson.setCommunicationData(exp); + final Object act = cut.getLinkedInstanceBasedResultByDelta(currentImagePerson, path, Optional.ofNullable( + beforeImagePerson)); + assertEquals(exp, act); + } + + private void prepareRole() { + + final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class); + pathElements.add(pathItem); + when(path.getPath()).thenReturn(pathElements); + when(pathItem.getInternalName()).thenReturn("roles"); + when(path.getLeaf()).thenReturn(pathItem); + when(pathItem.isCollection()).thenReturn(Boolean.TRUE); + } + + private CommunicationData prepareBeforeImageCommunicationData() { + final CommunicationData afterCommData = new CommunicationData(); + currentImagePerson.setCommunicationData(afterCommData); + final JPAAssociationAttribute pathItem = mock(JPAAssociationAttribute.class); + pathElements.add(pathItem); + when(path.getPath()).thenReturn(pathElements); + when(pathItem.getInternalName()).thenReturn("communicationData"); + when(path.getLeaf()).thenReturn(pathItem); + when(pathItem.isCollection()).thenReturn(Boolean.FALSE); + return afterCommData; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java new file mode 100644 index 0000000000..0c74685b65 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestCreateRequestEntity.java @@ -0,0 +1,512 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.data.Link; +import org.apache.olingo.commons.api.data.Property; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.serializer.JPASerializer; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestCreateRequestEntity { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static JPAEdmProvider jpaEdm; + protected static DataSource ds; + + @BeforeAll + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + private OData odata; + private JPACUDRequestProcessor cut; + private Entity oDataEntity; + private ServiceMetadata serviceMetadata; + private JPAODataSessionContextAccess sessionContext; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private UriResourceEntitySet uriEts; + private EntityManager em; + private EntityTransaction transaction; + private JPASerializer serializer; + private EdmEntitySet ets; + private List keyPredicates; + private JPAConversionHelper convHelper; + private List pathParts = new ArrayList<>(); + private Map> headers; + + @BeforeEach + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + serializer = mock(JPASerializer.class); + uriEts = mock(UriResourceEntitySet.class); + pathParts.add(uriEts); + convHelper = new JPAConversionHelper();// mock(JPAConversionHelper.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + headers = new HashMap<>(0); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(uriEts.getKind()).thenReturn(UriResourceKind.entitySet); + when(ets.getName()).thenReturn("AdministrativeDivisions"); + when(em.getTransaction()).thenReturn(transaction); + cut = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + + } + + @Test + public void testCreateDataAndEtCreated() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getData()); + assertNotNull(act.getEntityType()); + } + + @Test + public void testCreateEtName() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertEquals("AdministrativeDivision", act.getEntityType().getExternalName()); + } + + @Test + public void testCreateDataHasProperty() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + String actValue = (String) act.getData().get("codeID"); + assertNotNull(actValue); + assertEquals("DE50", actValue); + } + + @Test + public void testCreateEmptyRelatedEntities() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getRelatedEntities()); + assertTrue(act.getRelatedEntities().isEmpty()); + } + + @Test + public void testCreateEmptyRelationLinks() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act.getRelationLinks()); + assertTrue(act.getRelationLinks().isEmpty()); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLink() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull(actValue, "Is null"); + assertTrue(actValue instanceof List, "Wrong type"); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkSize() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertEquals(1, ((List) actValue).size(), "Wrong size"); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkEntityType() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull(((List) actValue).get(0)); + assertNotNull(((JPARequestEntity) ((List) actValue).get(0)).getEntityType(), "Entity type not found"); + assertEquals("AdministrativeDivision", ((JPARequestEntity) ((List) actValue).get(0)) + .getEntityType().getExternalName(), "Wrong Type"); + } + + @Test + public void testCreateDeepOneChildResultContainsEntityLinkData() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addChildrenNavigationLinkDE501(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertNotNull(((List) actValue).get(0)); + assertNotNull(((JPARequestEntity) ((List) actValue).get(0)).getEntityType(), "Entity type not found"); + Map actData = ((JPARequestEntity) ((List) actValue).get(0)).getData(); + assertNotNull(actData, "Data not found"); + assertNotNull(actData.get("codeID"), "CodeID not found"); + assertEquals("DE501", actData.get("codeID"), "Value not found"); + } + + @Test + public void testCreateDeepTwoChildResultContainsEntityLinkSize() throws ODataJPAModelException, ODataException { + List properties = createProperties(); + createODataEntity(properties); + + List navigationLinks = new ArrayList<>(); + addNavigationLinkDE502(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("children")); + assertEquals(2, ((List) actValue).size(), "Wrong size"); + } + + @Test + public void testCreateWithLinkToOne() throws ODataJPAProcessorException { + List properties = createProperties(); + createODataEntity(properties); + List bindingLinks = new ArrayList<>(); + addParentBindingLink(bindingLinks); + when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findLinkList(act.getRelationLinks(), ("parent")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + } + + @Test + public void testCreateWithLinkToMany() throws ODataJPAProcessorException { + List properties = createProperties(); + createODataEntity(properties); + List bindingLinks = new ArrayList<>(); + addChildrenBindingLink(bindingLinks); + when(oDataEntity.getNavigationBindings()).thenReturn(bindingLinks); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findLinkList(act.getRelationLinks(), ("children")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + assertEquals(2, ((List) actValue).size()); + } + + @Test + public void testCreateDeepToOne() throws ODataJPAProcessorException { + final List properties = createProperties(); + createODataEntity(properties); + + final List navigationLinks = new ArrayList<>(); + final Link navigationLink = addParentNavigationLink(navigationLinks); + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + when(oDataEntity.getNavigationLink("Parent")).thenReturn(navigationLink); + + JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + Object actValue = findEntitryList(act.getRelatedEntities(), ("parent")); + assertNotNull(actValue); + assertTrue(actValue instanceof List); + } + + @Test + public void testCreateOrgWithRoles() throws ODataJPAProcessorException { + + final List properties = new ArrayList<>(); + createPropertyBuPaID(properties, "20"); + createODataEntity(properties); +//----------------------------- + final List navigationLinks = new ArrayList<>(); + + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Roles"); + navigationLinks.add(navigationLink); + final EntityCollection navigationEntitySet = mock(EntityCollection.class); + final List entityCollection = new ArrayList<>(); + + final Entity navigationEntity1 = mock(Entity.class); + final List navigationEntityProperties1 = createPropertiesRoles("20", "A"); + when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);// + entityCollection.add(navigationEntity1); + + final Entity navigationEntity2 = mock(Entity.class); + final List navigationEntityProperties2 = createPropertiesRoles("20", "C"); + when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);// + entityCollection.add(navigationEntity2); + + when(navigationEntitySet.getEntities()).thenReturn(entityCollection); + when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet); + + when(oDataEntity.getNavigationLinks()).thenReturn(navigationLinks); + when(oDataEntity.getNavigationLink("Roles")).thenReturn(navigationLink); +//------------------------------------ + when(ets.getName()).thenReturn("Organizations"); + final JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + + assertNotNull(act); + assertNotNull(act.getData()); + assertNotNull(findEntitryList(act.getRelatedEntities(), ("roles"))); + } + + @Test + public void testCreateDeepOneChildViaComplex() throws ODataJPAModelException, ODataException { + final List properties = new ArrayList<>(); + final List inlineProperties = new ArrayList<>(); + final Entity inlineEntity = mock(Entity.class); + + createODataEntity(properties); + + when(ets.getName()).thenReturn("Persons"); + createPropertyBuPaID(properties, "20"); + when(inlineEntity.getProperties()).thenReturn(inlineProperties); + createPropertyBuPaID(inlineProperties, "200"); + + final List adminProperties = createComplexProperty(properties, "AdministrativeInformation", null, null, + oDataEntity); + final List createdProperties = createComplexProperty(adminProperties, "Created", "User", inlineEntity, + oDataEntity); + createPrimitiveProperty(createdProperties, "99", "By"); + createPrimitiveProperty(createdProperties, Timestamp.valueOf("2016-01-20 09:21:23.0"), "At"); + + final JPARequestEntity act = cut.createRequestEntity(ets, oDataEntity, headers); + final Object actValue = findEntitryList(act.getRelatedEntities(), ("administrativeInformation")); + + assertNotNull(actValue); + assertNotNull(((List) actValue).get(0)); + @SuppressWarnings("unchecked") + JPARequestEntity actDeepEntity = ((List) actValue).get(0); + assertEquals("200", actDeepEntity.getData().get("iD")); + } + + private List createComplexProperty(final List properties, final String name, final String target, + final Entity inlineEntity, final Entity oDataEntity) { + + final Property property = mock(Property.class); + final ComplexValue cv = mock(ComplexValue.class); + final List cProperties = new ArrayList<>(); + final Link navigationLink = mock(Link.class); + + when(property.getName()).thenReturn(name); + when(property.getValue()).thenReturn(cv); + when(property.getValueType()).thenReturn(ValueType.COMPLEX); + when(property.isComplex()).thenReturn(true); + when(property.asComplex()).thenReturn(cv); + + when(cv.getValue()).thenReturn(cProperties); + when(cv.getNavigationLink(target)).thenReturn(navigationLink); + when(navigationLink.getInlineEntity()).thenReturn(inlineEntity); + + when(oDataEntity.getProperty(name)).thenReturn(property); + + properties.add(property); + return cProperties; + } + + private Link addParentNavigationLink(List navigationLinks) { + + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Parent"); + navigationLinks.add(navigationLink); + final Entity navigationEntity = mock(Entity.class); + when(navigationLink.getInlineEntity()).thenReturn(navigationEntity); + final List navigationEntityProperties = createPropertyCodeID("DE5"); + when(navigationEntity.getProperties()).thenReturn(navigationEntityProperties);// + return navigationLink; + } + + private void addParentBindingLink(List bindingLinks) { + Link bindingLink = mock(Link.class); + when(bindingLink.getTitle()).thenReturn("Parent"); + bindingLinks.add(bindingLink); + when(bindingLink.getBindingLink()).thenReturn( + "AdministrativeDivisions(DivisionCode='DE1',CodeID='NUTS1',CodePublisher='Eurostat')"); + } + + private void addChildrenNavigationLinkDE501(List navigationLinks) { + addChildrenNavigationLink(navigationLinks, "DE501", null); + } + + private void addNavigationLinkDE502(List navigationLinks) { + + addChildrenNavigationLink(navigationLinks, "DE501", "DE502"); + } + + private void addChildrenNavigationLink(List navigationLinks, String codeValue1, String codeValue2) { + final Link navigationLink = mock(Link.class); + when(navigationLink.getTitle()).thenReturn("Children"); + navigationLinks.add(navigationLink); + final EntityCollection navigationEntitySet = mock(EntityCollection.class); + final List entityCollection = new ArrayList<>(); + + final Entity navigationEntity1 = mock(Entity.class); + final List navigationEntityProperties1 = createPropertyCodeID(codeValue1); + when(navigationEntity1.getProperties()).thenReturn(navigationEntityProperties1);// + entityCollection.add(navigationEntity1); + if (codeValue2 != null) { + Entity navigationEntity2 = mock(Entity.class); + List navigationEntityProperties2 = createPropertyCodeID(codeValue2); + when(navigationEntity2.getProperties()).thenReturn(navigationEntityProperties2);// + entityCollection.add(navigationEntity2); + } + when(navigationEntitySet.getEntities()).thenReturn(entityCollection); + when(navigationLink.getInlineEntitySet()).thenReturn(navigationEntitySet); + when(oDataEntity.getNavigationLink("Children")).thenReturn(navigationLink); + + } + + private void addChildrenBindingLink(List bindingLinks) { + List links = new ArrayList<>(); + + Link bindingLink = mock(Link.class); + when(bindingLink.getTitle()).thenReturn("Children"); + bindingLinks.add(bindingLink); + when(bindingLink.getBindingLinks()).thenReturn(links); + links.add("AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"); + links.add("AdministrativeDivisions(DivisionCode='DE101',CodeID='NUTS3',CodePublisher='Eurostat')"); + } + + private void createODataEntity(final List properties) { + oDataEntity = mock(Entity.class); + when(oDataEntity.getProperties()).thenReturn(properties); + } + + private List createProperties() { + return createPropertyCodeID("DE50"); + } + + private List createPropertyCodeID(final String codeID) { + List properties = new ArrayList<>(); + createPrimitiveProperty(properties, codeID, "CodeID"); + return properties; + } + + private void createPropertyBuPaID(final List properties, final String value) { + + createPrimitiveProperty(properties, value, "ID"); + } + + private void createPrimitiveProperty(final List properties, final Object value, final String name) { + + final Property property = mock(Property.class); + when(property.getName()).thenReturn(name); + when(property.getValue()).thenReturn(value); + when(property.getValueType()).thenReturn(ValueType.PRIMITIVE); + properties.add(property); + } + + private List createPropertiesRoles(String BuPaId, String RoleCategory) { + List properties = new ArrayList<>(); + createPrimitiveProperty(properties, BuPaId, "BusinessPartnerID"); + createPrimitiveProperty(properties, RoleCategory, "RoleCategory"); + return properties; + } + + private Object findEntitryList(Map> relatedEntities, + String assoziationName) { + for (Entry> entity : relatedEntities.entrySet()) { + if (entity.getKey().getPath().get(0).getInternalName().equals(assoziationName)) + return entity.getValue(); + } + return null; + } + + private Object findLinkList(Map> relationLink, String assoziationName) { + for (Entry> entity : relationLink.entrySet()) { + if (entity.getKey().getPath().get(0).getInternalName().equals(assoziationName)) + return entity.getValue(); + } + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java new file mode 100644 index 0000000000..609bfee386 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAActionProcessor.java @@ -0,0 +1,455 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.data.Parameter; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.edm.EdmAction; +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.edm.provider.CsdlProperty; +import org.apache.olingo.commons.api.edm.provider.CsdlReturnType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.deserializer.DeserializerResult; +import org.apache.olingo.server.api.deserializer.ODataDeserializer; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceAction; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.CommunicationData; +import com.sap.olingo.jpa.processor.core.testobjects.FileAccess; +import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActionNoParameter; +import com.sap.olingo.jpa.processor.core.testobjects.TestJavaActions; + +public class TestJPAActionProcessor { + + private JPAActionRequestProcessor cut; + private ContentType requestFormat; + @Mock + private ODataRequest request; + @Mock + private ODataResponse response; + @Mock + private OData odata; + @Mock + private ODataDeserializer deserializer; + @Mock + private JPAOperationSerializer serializer; + @Mock + private JPAODataSessionContextAccess sessionContext; + @Mock + private JPAODataRequestContextAccess requestContext; + @Mock + private JPAServiceDocument sd; + @Mock + private UriInfo uriInfo; + private List uriResources; + @Mock + private UriResourceAction resource; + @Mock + private EdmAction edmAction; + @Mock + private JPAAction action; + private Map actionParameter; + @Mock + private CsdlReturnType returnType; + @Mock + private UriResourceEntitySet bindingEntity; + + @BeforeEach + public void setup() throws ODataException { + MockitoAnnotations.initMocks(this); + + uriResources = new ArrayList<>(); + uriResources.add(resource); + actionParameter = new HashMap<>(); + + EntityManager em = mock(EntityManager.class); + CriteriaBuilder cb = mock(CriteriaBuilder.class); + JPAEdmProvider edmProvider = mock(JPAEdmProvider.class); + DeserializerResult dResult = mock(DeserializerResult.class); + SerializerResult serializerResult = mock(SerializerResult.class); + + when(requestContext.getEntityManager()).thenReturn(em); + when(em.getCriteriaBuilder()).thenReturn(cb); + when(sessionContext.getEdmProvider()).thenReturn(edmProvider); + when(edmProvider.getServiceDocument()).thenReturn(sd); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + when(serializer.getContentType()).thenReturn(ContentType.APPLICATION_JSON); + + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(resource.getAction()).thenReturn(edmAction); + when(edmAction.isBound()).thenReturn(Boolean.FALSE); + when(sd.getAction(edmAction)).thenReturn(action); + when(odata.createDeserializer((ContentType) any())).thenReturn(deserializer); + + when(deserializer.actionParameters(request.getBody(), resource.getAction())).thenReturn(dResult); + when(dResult.getActionParameters()).thenReturn(actionParameter); + + requestFormat = ContentType.APPLICATION_JSON; + + cut = new JPAActionRequestProcessor(odata, sessionContext, requestContext); + } + + @Test + public void testCallsConstructorWithoutParemeter() throws InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, + SecurityException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + setConstructorAndMethod("unboundReturnPrimitivetNoParameter"); + + cut.performAction(request, response, requestFormat); + + assertEquals(1, TestJavaActionNoParameter.constructorCalls); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsConstructorWithParemeter() throws ODataJPAProcessException, InstantiationException, + IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, + SecurityException, ODataApplicationException { + TestJavaActions.constructorCalls = 0; + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundWithOutParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + cut.performAction(request, response, requestFormat); + + assertEquals(1, TestJavaActions.constructorCalls); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionVoidNoParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundWithOutParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionPrimitiveNoParameterReturnValue() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, SerializerException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("unboundReturnFacetNoParameter"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class); + when(action.getResultParameter()).thenReturn(rParam); + + EdmReturnType rt = mock(EdmReturnType.class); + EdmType type = mock(EdmType.class); + when(edmAction.getReturnType()).thenReturn(rt); + when(rt.getType()).thenReturn(type); + when(type.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(200); + verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type)); + } + + @SuppressWarnings("unchecked") + @Test + public void testCallsActionEntityNoParameterReturnValue() throws NoSuchMethodException, + SecurityException, SerializerException, ODataApplicationException { + + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActions.class.getConstructors()[0]; + Method m = TestJavaActions.class.getMethod("returnEmbeddable"); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + final JPAOperationResultParameter rParam = mock(JPAOperationResultParameter.class); + when(action.getResultParameter()).thenReturn(rParam); + + EdmReturnType rt = mock(EdmReturnType.class); + EdmComplexType type = mock(EdmComplexType.class); + when(edmAction.getReturnType()).thenReturn(rt); + when(rt.getType()).thenReturn(type); + when(type.getKind()).thenReturn(EdmTypeKind.COMPLEX); + + JPAStructuredType st = mock(JPAStructuredType.class); + when(sd.getComplexType((EdmComplexType) any())).thenReturn(st); + when(st.getTypeClass()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return CommunicationData.class; + } + }); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(200); + verify(serializer, times(1)).serialize(any(Annotatable.class), eq(type)); + } + + @Test + public void testCallsActionVoidOneParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataJPAModelException, NumberFormatException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneParameter", Short.class); + + addParameter(m, new Short("10"), "A", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(new Short((short) 10), TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOneEnumerationParameterReturnNoContent() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneEnumerationParameter", FileAccess.class); + + addParameter(m, FileAccess.Create, "AccessRights", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(FileAccess.Create, TestJavaActionNoParameter.enumeration); + } + + @Test + public void testCallsActionVoidTwoParameterReturnNoContent() throws ODataJPAProcessException, NoSuchMethodException, + SecurityException, ODataJPAModelException, NumberFormatException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidTwoParameter", Short.class, Integer.class); + + addParameter(m, new Short("10"), "A", 0); + addParameter(m, new Integer("200000"), "B", 1); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertEquals(new Short((short) 10), TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOneParameterNullableGivenNullReturnNoContent() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("unboundVoidOneParameter", Short.class); + + addParameter(m, null, "A", 0); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNull(TestJavaActionNoParameter.param1); + } + + @Test + public void testCallsActionVoidOnlyBindingParameter() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundOnlyBinding", AdministrativeDivision.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + } + + @Test + public void testCallsActionVoidBindingParameterPlusTwoBothNull() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class, Integer.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[1])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("A"); + + jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[2])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("B"); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + assertNull(TestJavaActionNoParameter.param1); + assertNull(TestJavaActionNoParameter.param2); + } + + @Test + public void testCallsActionVoidBindingParameterPlusTwoFirstNull() throws ODataJPAProcessException, + NoSuchMethodException, SecurityException, ODataJPAModelException, NumberFormatException, + EdmPrimitiveTypeException, ODataApplicationException { + TestJavaActionNoParameter.resetCalls(); + + Method m = setConstructorAndMethod("boundBindingPlus", AdministrativeDivision.class, Short.class, Integer.class); + when(edmAction.isBound()).thenReturn(Boolean.TRUE); + uriResources.add(0, bindingEntity); + + setBindingParameter(m); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[1])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn("A"); + + addParameter(m, 20, "B", 2); + + cut.performAction(request, response, requestFormat); + verify(response, times(1)).setStatusCode(204); + assertNotNull(TestJavaActionNoParameter.bindingParam); + assertEquals("LAU2", TestJavaActionNoParameter.bindingParam.getCodeID()); + assertNull(TestJavaActionNoParameter.param1); + assertEquals(new Integer(20), TestJavaActionNoParameter.param2); + } + + private void setBindingParameter(Method m) throws ODataJPAModelException, EdmPrimitiveTypeException { + final JPAParameter bindingParam = addParameter(m, null, "Root", 0); + when(bindingParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return AdministrativeDivision.class; + } + }); + final List keys = new ArrayList<>(); + final UriParameter key1 = mock(UriParameter.class); + when(bindingEntity.getKeyPredicates()).thenReturn(keys); + when(key1.getName()).thenReturn("CodeID"); + when(key1.getText()).thenReturn("LAU2"); + keys.add(key1); + + final JPAEntityType et = mock(JPAEntityType.class); + final JPAPath codePath = mock(JPAPath.class); + final JPAAttribute code = mock(JPAAttribute.class); + final EdmPrimitiveType edmString = mock(EdmPrimitiveType.class); + final CsdlProperty edmProperty = mock(CsdlProperty.class); + when(sd.getEntity((EdmType) any())).thenReturn(et); + when(et.getPath("CodeID")).thenReturn(codePath); + when(codePath.getLeaf()).thenReturn(code); + when(code.getInternalName()).thenReturn("codeID"); + when(code.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + when(code.getProperty()).thenReturn(edmProperty); + when(odata.createPrimitiveTypeInstance(EdmPrimitiveTypeKind.String)).thenReturn(edmString); + when(edmString.fromUriLiteral("LAU2")).thenReturn("LAU2"); + when(edmString.valueOfString("LAU2", false, 0, 0, 0, true, code.getType())).thenAnswer( + new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + return "LAU2"; + } + }); + } + + private JPAParameter addParameter(final Method m, final Object value, final String name, int index) + throws ODataJPAModelException { + + Parameter param = mock(Parameter.class); + when(param.getValue()).thenReturn(value); + when(param.getName()).thenReturn(name); + when(param.getValueType()).thenReturn(ValueType.PRIMITIVE); + actionParameter.put(name, param); + + JPAParameter jpaParam = mock(JPAParameter.class); + when(action.getParameter(m.getParameters()[index])).thenReturn(jpaParam); + when(jpaParam.getName()).thenReturn(name); + return jpaParam; + } + + @SuppressWarnings("unchecked") + private Method setConstructorAndMethod(String methodName, Class... parameterTypes) throws NoSuchMethodException { + @SuppressWarnings("rawtypes") + Constructor c = TestJavaActionNoParameter.class.getConstructors()[0]; + Method m = TestJavaActionNoParameter.class.getMethod(methodName, parameterTypes); + when(action.getConstructor()).thenReturn(c); + when(action.getMethod()).thenReturn(m); + when(action.getReturnType()).thenReturn(null); + return m; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java new file mode 100644 index 0000000000..97ea3ef7e4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAClearProcessor.java @@ -0,0 +1,512 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.http.HttpMethod; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException.MessageKeys; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult; + +public class TestJPAClearProcessor extends TestJPAModifyProcessor { + private ODataRequest request; + + @BeforeEach + public void setup() throws ODataException { + request = mock(ODataRequest.class); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + } + + @Test + public void testSuccessReturnCode() throws ODataApplicationException { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + prepareDeleteName2(); + processor.clearFields(request, response); + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testHockIsCalled() throws ODataApplicationException { + // .../Organizations('35')/Name2 + + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertTrue(spy.called); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.clearFields(request, new ODataResponse()); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testSimplePropertyEntityTypeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertEquals("Organization", spy.et.getExternalName()); + } + + @Test + public void testSimplePropertyKeyProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + List keys = new ArrayList<>(); + UriParameter uriParam = mock(UriParameter.class); + when(uriParam.getText()).thenReturn("'35'"); + when(uriParam.getName()).thenReturn("ID"); + keys.add(uriParam); + + when(uriEts.getKeyPredicates()).thenReturn(keys); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.keyPredicates.size()); + assertEquals("35", spy.keyPredicates.get("iD")); + } + + @Test + public void testSimplePropertyAttributeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2 + RequestHandleSpy spy = prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("name2", keys[0].toString()); + } + + @Test + public void testComplexPropertyHoleProvided() throws ODataApplicationException { + // .../Organizations('35')/Address + RequestHandleSpy spy = prepareDeleteAddress(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("address", keys[0].toString()); + } + + @Test + public void testSimplePropertyValueAttributeProvided() throws ODataApplicationException { + // .../Organizations('35')/Name2/$value + RequestHandleSpy spy = prepareDeleteName2(); + + UriResourceValue uriProperty; + uriProperty = mock(UriResourceValue.class); + pathParts.add(uriProperty); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + Object[] keys = spy.jpaAttributes.keySet().toArray(); + assertEquals("name2", keys[0].toString()); + } + + @Test + public void testComplexPropertyOnePropertyProvided() throws ODataApplicationException { + // .../Organizations('35')/Address/Country + RequestHandleSpy spy = prepareDeleteAddressCountry(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + @SuppressWarnings("unchecked") + Map address = (Map) spy.jpaAttributes.get("address"); + assertEquals(1, address.size()); + Object[] keys = address.keySet().toArray(); + assertEquals("country", keys[0].toString()); + } + + @SuppressWarnings("unchecked") + @Test + public void testTwoComplexPropertiesOnePropertyProvided() throws ODataApplicationException { + // .../Organizations('4')/AdministrativeInformation/Updated/By + RequestHandleSpy spy = prepareDeleteAdminInfo(); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + Map adminInfo = (Map) spy.jpaAttributes.get("administrativeInformation"); + assertEquals(1, adminInfo.size()); + Map update = (Map) adminInfo.get("updated"); + assertEquals(1, update.size()); + Object[] keys = update.keySet().toArray(); + assertEquals("by", keys[0].toString()); + } + + @SuppressWarnings("unchecked") + @Test + public void testTwoComplexPropertiesOnePropertyValueProvided() throws ODataApplicationException { + // .../Organizations('4')/AdministrativeInformation/Updated/By/$value + RequestHandleSpy spy = prepareDeleteAdminInfo(); + + UriResourceValue uriProperty; + uriProperty = mock(UriResourceValue.class); + pathParts.add(uriProperty); + + processor.clearFields(request, new ODataResponse()); + assertEquals(1, spy.jpaAttributes.size()); + + Map adminInfo = (Map) spy.jpaAttributes.get("administrativeInformation"); + assertEquals(1, adminInfo.size()); + Map update = (Map) adminInfo.get("updated"); + assertEquals(1, update.size()); + Object[] keys = update.keySet().toArray(); + assertEquals("by", keys[0].toString()); + } + + @Test + public void testBeginIsCalledOnNoTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(1)).begin(); + } + + @Test + public void testBeginIsNotCalledOnTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + when(transaction.isActive()).thenReturn(true); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(0)).begin(); + } + + @Test + public void testCommitIsCalledOnNoTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(1)).commit(); + } + + @Test + public void testCommitIsNotCalledOnTransaction() throws ODataApplicationException { + // .../Organizations('35')/Name2 + prepareDeleteName2(); + when(transaction.isActive()).thenReturn(true); + + processor.clearFields(request, new ODataResponse()); + + verify(transaction, times(0)).commit(); + } + + @Test + public void testErrorReturnCodeWithRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(1); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testErrorReturnCodeWithOutRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(1); + when(transaction.isActive()).thenReturn(true); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + verify(transaction, times(0)).rollback(); + return; + } + fail(); + } + + @Test + public void testReraiseWithRollback() { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(2); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testReraiseReturnCodeWithOutRollback() throws ODataJPAProcessException { + // .../Organizations('35')/Name2 + ODataResponse response = new ODataResponse(); + + RequestHandleSpy spy = prepareDeleteName2(); + spy.raiseException(2); + when(transaction.isActive()).thenReturn(true); + try { + processor.clearFields(request, response); + } catch (ODataJPAProcessorException e) { + assertEquals(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), e.getStatusCode()); + verify(transaction, times(0)).rollback(); + return; + } + fail(); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.clearFields(request, response); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.clearFields(request, response); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + when(request.getMethod()).thenReturn(HttpMethod.POST); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class), + any(HttpMethod.class)); + + try { + processor.clearFields(request, response); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.clearFields(request, response); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + private RequestHandleSpy prepareDeleteName2() { + + UriResourcePrimitiveProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Name2"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + private RequestHandleSpy prepareDeleteAddress() { + + UriResourceComplexProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Address"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + private RequestHandleSpy prepareDeleteAddressCountry() { + RequestHandleSpy spy = prepareDeleteAddress(); + + UriResourcePrimitiveProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Country"); + + return spy; + } + + private RequestHandleSpy prepareDeleteAdminInfo() { + + UriResourceComplexProperty uriProperty; + EdmProperty property; + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("AdministrativeInformation"); + + uriProperty = mock(UriResourceComplexProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriProperty); + when(uriProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("Updated"); + + UriResourcePrimitiveProperty uriPrimProperty; + uriPrimProperty = mock(UriResourcePrimitiveProperty.class); + property = mock(EdmProperty.class); + + pathParts.add(uriPrimProperty); + when(uriPrimProperty.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("By"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + return spy; + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public Map keyPredicates; + public Map jpaAttributes; + public JPAEntityType et; + public boolean called; + public Map> headers; + private int raiseEx; + + @Override + public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em, + final HttpMethod verb) throws ODataJPAProcessException { + + this.et = requestEntity.getEntityType(); + this.keyPredicates = requestEntity.getKeys(); + this.jpaAttributes = requestEntity.getData(); + this.headers = requestEntity.getAllHeader(); + called = true; + + if (raiseEx == 1) + throw new NullPointerException(); + if (raiseEx == 2) + throw new ODataJPAProcessorException(MessageKeys.NOT_SUPPORTED_DELETE, HttpStatusCode.NOT_IMPLEMENTED); + return null; + } + + public void raiseException(int type) { + this.raiseEx = type; + + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java new file mode 100644 index 0000000000..06e7f481a0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPACreateProcessor.java @@ -0,0 +1,592 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPACreateProcessor extends TestJPAModifyProcessor { + + @Test + public void testHookIsCalled() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.called); + } + + @Test + public void testEntityTypeProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals("Organization", spy.et.getExternalName()); + } + + @SuppressWarnings("unchecked") + @Test + public void testAttributesProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + Map attributes = new HashMap<>(1); + + attributes.put("ID", "35"); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(convHelper.convertProperties(ArgumentMatchers.any(OData.class), ArgumentMatchers.any(JPAStructuredType.class), + ArgumentMatchers.any( + List.class))).thenReturn(attributes); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.jpaAttributes); + assertEquals(1, spy.jpaAttributes.size()); + assertEquals("35", spy.jpaAttributes.get("ID")); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testThrowExpectedExceptionInCaseOfError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testThrowUnexpectedExceptionInCaseOfError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(NullPointerException.class).when(handler).createEntity(any(JPARequestEntity.class), any( + EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testMinimalResponseLocationHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testMinimalResponseODataEntityIdHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.ODATA_ENTITY_ID)); + } + + @Test + public void testMinimalResponseStatusCode() throws ODataJPAProcessorException, SerializerException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponsePreferApplied() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals("return=minimal", response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testRepresentationResponseStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseStatusCodeMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + byte[] act = new byte[100]; + response.getContent().read(act); + String s = new String(act).trim(); + assertEquals("{\"ID\":\"35\"}", s); + } + + @Test + public void testRepresentationResponseContentMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + byte[] act = new byte[100]; + response.getContent().read(act); + String s = new String(act).trim(); + assertEquals("{\"ID\":\"35\"}", s); + } + + @Test + public void testRepresentationLocationHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testRepresentationLocationHeaderMapResult() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleMapResultSpy()); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(LOCATION_HEADER, response.getHeader(HttpHeader.LOCATION)); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).createEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testResponseCreateChildSameTypeContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + when(ets.getName()).thenReturn("AdministrativeDivisions"); + final AdministrativeDivision div = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS1", + "DE6")); + final AdministrativeDivision child = new AdministrativeDivision(new AdministrativeDivisionKey("Eurostat", "NUTS2", + "DE60")); + div.getChildren().add(child); + final RequestHandleSpy spy = new RequestHandleSpy(div); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareRequestToCreateChild(spy); + + final UriResourceNavigation uriChild = mock(UriResourceNavigation.class); + final List uriKeys = new ArrayList<>(); + final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class); + + createKeyPredicate(uriKeys, "DivisionCode", "DE6"); + createKeyPredicate(uriKeys, "CodeID", "NUTS1"); + createKeyPredicate(uriKeys, "CodePublisher", "Eurostat"); + when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty); + when(uriChild.getProperty()).thenReturn(naviProperty); + when(naviProperty.getName()).thenReturn("Children"); + when(uriEts.getKeyPredicates()).thenReturn(uriKeys); + when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod(); + when(convHelper.buildGetterMap(div)).thenReturn(new JPAConversionHelper().determineGetter(div)); + when(convHelper.buildGetterMap(child)).thenReturn(new JPAConversionHelper().determineGetter(child)); + pathParts.add(uriChild); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.requestEntity.getKeys()); + assertEquals("DE6", spy.requestEntity.getKeys().get("divisionCode")); + assertNotNull(spy.requestEntity.getRelatedEntities()); + for (Entry> c : spy.requestEntity.getRelatedEntities().entrySet()) + assertEquals("Children", c.getKey().getAlias()); + } + + @Test + public void testResponseCreateChildDifferentTypeContent() throws ODataJPAProcessorException, SerializerException, + ODataException, IOException { + + final Organization org = new Organization("Test"); + final BusinessPartnerRole role = new BusinessPartnerRole(); + role.setBusinessPartner(org); + role.setRoleCategory("A"); + org.getRoles().add(role); + + final RequestHandleSpy spy = new RequestHandleSpy(org); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareRequestToCreateChild(spy); + + final UriResourceNavigation uriChild = mock(UriResourceNavigation.class); + final List uriKeys = new ArrayList<>(); + final EdmNavigationProperty naviProperty = mock(EdmNavigationProperty.class); + final EdmNavigationPropertyBinding naviBinding = mock(EdmNavigationPropertyBinding.class); + final EdmEntityContainer container = mock(EdmEntityContainer.class); + final List naviBindings = new ArrayList<>(1); + final EdmEntitySet targetEts = mock(EdmEntitySet.class); + naviBindings.add(naviBinding); + + createKeyPredicate(uriKeys, "ID", "Test"); + when(uriChild.getKind()).thenReturn(UriResourceKind.navigationProperty); + when(uriChild.getProperty()).thenReturn(naviProperty); + when(naviProperty.getName()).thenReturn("Roles"); + when(uriEts.getKeyPredicates()).thenReturn(uriKeys); + when(convHelper.convertUriKeys(any(), any(), any())).thenCallRealMethod(); + when(convHelper.buildGetterMap(org)).thenReturn(new JPAConversionHelper().determineGetter(org)); + when(convHelper.buildGetterMap(role)).thenReturn(new JPAConversionHelper().determineGetter(role)); + when(ets.getNavigationPropertyBindings()).thenReturn(naviBindings); + when(naviBinding.getPath()).thenReturn("Roles"); + when(naviBinding.getTarget()).thenReturn("BusinessPartnerRoles"); + when(ets.getEntityContainer()).thenReturn(container); + when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(targetEts); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.BusinessPartnerRole"); + final List keyNames = Arrays.asList("BusinessPartnerID", "RoleCategory"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + createKeyProperty(fqn, edmET, "BusinessPartnerID", "Test"); + createKeyProperty(fqn, edmET, "RoleCategory", "A"); + // edmType.getFullQualifiedName().getFullQualifiedNameAsString() + + pathParts.add(uriChild); + // return serviceMetadata.getEdm().getEntityType(es.getODataEntityType().getExternalFQN()); + // com.sap.olingo.jpa.BusinessPartnerRole + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + processor.createEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.requestEntity.getKeys()); + assertEquals("Test", spy.requestEntity.getKeys().get("iD")); + assertNotNull(spy.requestEntity.getRelatedEntities()); + for (Entry> c : spy.requestEntity.getRelatedEntities().entrySet()) + assertEquals("Roles", c.getKey().getAlias()); + } + + protected ODataRequest prepareRequestToCreateChild(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + // .../AdministrativeDivisions(DivisionCode='DE6',CodeID='NUTS1',CodePublisher='Eurostat')/Children + final ODataRequest request = prepareSimpleRequest("return=representation"); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision"); + final List keyNames = Arrays.asList("DivisionCode", "CodeID", "CodePublisher"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + + createKeyProperty(fqn, edmET, "DivisionCode", "DE6"); + createKeyProperty(fqn, edmET, "CodeID", "NUTS1"); + createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat"); + + createKeyProperty(fqn, edmET, "DivisionCode", "DE60"); + createKeyProperty(fqn, edmET, "CodeID", "NUTS2"); + createKeyProperty(fqn, edmET, "CodePublisher", "Eurostat"); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes())); + + return request; + } + + private void createKeyPredicate(final List uriKeys, String name, String value) { + UriParameter key = mock(UriParameter.class); + uriKeys.add(key); + when(key.getName()).thenReturn(name); + when(key.getText()).thenReturn("'" + value + "'"); + } + + private void createKeyProperty(final FullQualifiedName fqn, final EdmEntityType edmET, String name, String value) + throws EdmPrimitiveTypeException { + final EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + when(edmET.getKeyPropertyRef(name)).thenReturn(refType); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + final EdmProperty edmProperty = mock(EdmProperty.class); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn(name); + EdmPrimitiveType type = mock(EdmPrimitiveType.class); + when(edmProperty.getType()).thenReturn(type); + when(type.valueToString(ArgumentMatchers.eq(value), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers + .any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(value); + when(type.toUriLiteral(ArgumentMatchers.anyString())).thenReturn(value); + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public Map> headers; + public JPARequestEntity requestEntity; + private final Object result; + + RequestHandleSpy(Object result) { + this.result = result; + } + + RequestHandleSpy() { + this.result = new Organization(); + ((Organization) result).setID("35"); + } + + @Override + public Object createEntity(final JPARequestEntity requestEntity, EntityManager em) + throws ODataJPAProcessException { + + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + this.em = em; + this.headers = requestEntity.getAllHeader(); + this.called = true; + this.requestEntity = requestEntity; + return result; + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + this.noValidateCalls++; + } + + } + + class RequestHandleMapResultSpy extends JPAAbstractCUDRequestHandler { + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public JPARequestEntity requestEntity; + + @Override + public Object createEntity(final JPARequestEntity requestEntity, EntityManager em) + throws ODataJPAProcessException { + Map result = new HashMap<>(); + result.put("iD", "35"); + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + this.em = em; + this.called = true; + this.requestEntity = requestEntity; + return result; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java new file mode 100644 index 0000000000..71fe7bac4b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPADeleteProcessor.java @@ -0,0 +1,347 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPADeleteProcessor { + private JPACUDRequestProcessor processor; + private OData odata; + private ServiceMetadata serviceMetadata; + private JPAODataSessionContextAccess sessionContext; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private UriResourceEntitySet uriEts; + private EdmEntitySet ets; + private List keyPredicates; + private JPAServiceDebugger debugger; + private EntityManager em; + private EntityTransaction transaction; + + private static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static EntityManagerFactory emf; + private static JPAEdmProvider jpaEdm; + private static DataSource ds; + + @BeforeAll + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + @BeforeEach + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + debugger = mock(JPAServiceDebugger.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + final List pathParts = new ArrayList<>(); + uriEts = mock(UriResourceEntitySet.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + pathParts.add(uriEts); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(sessionContext.getDebugger()).thenReturn(debugger); + when(requestContext.getEntityManager()).thenReturn(emf.createEntityManager()); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(ets.getName()).thenReturn("Organizations"); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + } + + @Test + public void testSuccessReturnCode() throws ODataApplicationException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(new RequestHandleSpy()); + + processor.deleteEntity(request, response); + assertEquals(204, response.getStatusCode()); + } + + @Test + public void testThrowUnexpectedExceptionInCaseOfError() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + doThrow(NullPointerException.class).when(handler).deleteEntity(any(JPARequestEntity.class), any( + EntityManager.class)); + + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testThrowExpectedExceptionInCaseOfError() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testConvertEntityType() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param = mock(UriParameter.class); + + keyPredicates.add(param); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(param.getName()).thenReturn("ID"); + when(param.getText()).thenReturn("'1'"); + + processor.deleteEntity(request, response); + + assertEquals("com.sap.olingo.jpa.processor.core.testmodel.Organization", spy.et.getInternalName()); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = mock(ODataRequest.class); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.deleteEntity(request, response); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testConvertKeySingleAttribute() throws ODataJPAProcessException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param = mock(UriParameter.class); + + keyPredicates.add(param); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + when(param.getName()).thenReturn("ID"); + when(param.getText()).thenReturn("'1'"); + processor.deleteEntity(request, response); + + assertEquals(1, spy.keyPredicates.size()); + assertTrue(spy.keyPredicates.get("iD") instanceof String); + assertEquals("1", spy.keyPredicates.get("iD")); + } + + @Test + public void testConvertKeyTwoAttributes() throws ODataJPAProcessException { + // BusinessPartnerRole + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + RequestHandleSpy spy = new RequestHandleSpy(); + UriParameter param1 = mock(UriParameter.class); + UriParameter param2 = mock(UriParameter.class); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(ets.getName()).thenReturn("BusinessPartnerRoles"); + when(param1.getName()).thenReturn("BusinessPartnerID"); + when(param1.getText()).thenReturn("'1'"); + when(param2.getName()).thenReturn("RoleCategory"); + when(param2.getText()).thenReturn("'A'"); + keyPredicates.add(param1); + keyPredicates.add(param2); + processor.deleteEntity(request, response); + + assertEquals(2, spy.keyPredicates.size()); + assertTrue(spy.keyPredicates.get("businessPartnerID") instanceof String); + assertEquals("1", spy.keyPredicates.get("businessPartnerID")); + assertTrue(spy.keyPredicates.get("roleCategory") instanceof String); + assertEquals("A", spy.keyPredicates.get("roleCategory")); + + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.deleteEntity(request, response); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + when(requestContext.getEntityManager()).thenReturn(em); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + + processor.deleteEntity(request, response); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).deleteEntity(any(JPARequestEntity.class), any(EntityManager.class)); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = mock(ODataRequest.class); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.FALSE); + when(requestContext.getEntityManager()).thenReturn(em); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, + new JPAConversionHelper()); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.deleteEntity(request, response); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public Map keyPredicates; + public JPAEntityType et; + public Map> headers; + + @Override + public void deleteEntity(final JPARequestEntity entity, final EntityManager em) { + + this.keyPredicates = entity.getKeys(); + this.et = entity.getEntityType(); + this.headers = entity.getAllHeader(); + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java new file mode 100644 index 0000000000..3038ee936e --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAModifyProcessor.java @@ -0,0 +1,251 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.core.edm.primitivetype.EdmString; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.ArgumentMatchers; + +import com.sap.olingo.jpa.metadata.api.JPAEdmMetadataPostProcessor; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; +import com.sap.olingo.jpa.processor.core.query.EdmEntitySetInfo; +import com.sap.olingo.jpa.processor.core.serializer.JPASerializer; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public abstract class TestJPAModifyProcessor { + protected static final String LOCATION_HEADER = "Organization('35')"; + protected static final String PREFERENCE_APPLIED = "return=minimal"; + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static JPAEdmProvider jpaEdm; + protected static DataSource ds; + + @BeforeAll + public static void setupClass() throws ODataException { + JPAEdmMetadataPostProcessor pP = mock(JPAEdmMetadataPostProcessor.class); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + jpaEdm = new JPAEdmProvider(PUNIT_NAME, emf.getMetamodel(), pP, TestBase.enumPackages); + + } + + protected JPACUDRequestProcessor processor; + protected OData odata; + protected ServiceMetadata serviceMetadata; + protected JPAODataSessionContextAccess sessionContext; + protected JPAODataRequestContextAccess requestContext; + protected UriInfo uriInfo; + protected UriResourceEntitySet uriEts; + protected EntityManager em; + protected EntityTransaction transaction; + protected JPASerializer serializer; + protected EdmEntitySet ets; + protected EdmEntitySetInfo etsInfo; + protected List keyPredicates; + protected JPAConversionHelper convHelper; + protected List pathParts = new ArrayList<>(); + protected SerializerResult serializerResult; + protected List header = new ArrayList<>(); + protected JPAServiceDebugger debugger; + + @BeforeEach + public void setUp() throws Exception { + odata = OData.newInstance(); + sessionContext = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + serviceMetadata = mock(ServiceMetadata.class); + uriInfo = mock(UriInfo.class); + keyPredicates = new ArrayList<>(); + ets = mock(EdmEntitySet.class); + etsInfo = mock(EdmEntitySetInfo.class); + serializer = mock(JPASerializer.class); + uriEts = mock(UriResourceEntitySet.class); + pathParts.add(uriEts); + convHelper = mock(JPAConversionHelper.class); + em = mock(EntityManager.class); + transaction = mock(EntityTransaction.class); + serializerResult = mock(SerializerResult.class); + debugger = mock(JPAServiceDebugger.class); + + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(sessionContext.getDebugger()).thenReturn(debugger); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getSerializer()).thenReturn(serializer); + when(uriInfo.getUriResourceParts()).thenReturn(pathParts); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + when(uriEts.getEntitySet()).thenReturn(ets); + when(uriEts.getKind()).thenReturn(UriResourceKind.entitySet); + when(ets.getName()).thenReturn("Organizations"); + when(em.getTransaction()).thenReturn(transaction); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + processor = new JPACUDRequestProcessor(odata, serviceMetadata, sessionContext, requestContext, convHelper); + + } + + protected ODataRequest prepareRepresentationRequest(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + + ODataRequest request = prepareSimpleRequest("return=representation"); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + Organization org = new Organization(); + when(em.find(Organization.class, "35")).thenReturn(org); + org.setID("35"); + Edm edm = mock(Edm.class); + when(serviceMetadata.getEdm()).thenReturn(edm); + EdmEntityType edmET = mock(EdmEntityType.class); + FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.Organization"); + when(edm.getEntityType(fqn)).thenReturn(edmET); + List keyNames = new ArrayList<>(); + keyNames.add("ID"); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + when(edmET.getKeyPropertyRef("ID")).thenReturn(refType); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + EdmProperty edmProperty = mock(EdmProperty.class); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("ID"); + EdmPrimitiveType type = mock(EdmPrimitiveType.class); + when(edmProperty.getType()).thenReturn(type); + when(type.toUriLiteral(ArgumentMatchers.any())).thenReturn("35"); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ID\":\"35\"}".getBytes())); + + return request; + } + + protected ODataRequest prepareLinkRequest(JPAAbstractCUDRequestHandler spy) + throws ODataJPAProcessorException, SerializerException, ODataException { + + // .../AdministrativeDivisions(DivisionCode='DE60',CodeID='NUTS2',CodePublisher='Eurostat') + final ODataRequest request = prepareSimpleRequest("return=representation"); + final Edm edm = mock(Edm.class); + final EdmEntityType edmET = mock(EdmEntityType.class); + + final FullQualifiedName fqn = new FullQualifiedName("com.sap.olingo.jpa.AdministrativeDivision"); + final List keyNames = new ArrayList<>(); + + final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60"); + final AdministrativeDivision div = new AdministrativeDivision(key); + + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.find(AdministrativeDivision.class, key)).thenReturn(div); + when(serviceMetadata.getEdm()).thenReturn(edm); + when(edm.getEntityType(fqn)).thenReturn(edmET); + when(ets.getName()).thenReturn("AdministrativeDivisions"); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + keyNames.add("DivisionCode"); + keyNames.add("CodeID"); + keyNames.add("CodePublisher"); + when(edmET.getKeyPredicateNames()).thenReturn(keyNames); + when(edmET.getFullQualifiedName()).thenReturn(fqn); + + EdmPrimitiveType type = EdmString.getInstance(); + EdmKeyPropertyRef refType = mock(EdmKeyPropertyRef.class); + EdmProperty edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("DivisionCode")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("DivisionCode"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + refType = mock(EdmKeyPropertyRef.class); + edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("CodeID")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("CodeID"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + refType = mock(EdmKeyPropertyRef.class); + edmProperty = mock(EdmProperty.class); + when(edmET.getKeyPropertyRef("CodePublisher")).thenReturn(refType); + when(refType.getProperty()).thenReturn(edmProperty); + when(refType.getName()).thenReturn("CodePublisher"); + when(edmProperty.getType()).thenReturn(type); + when(edmProperty.getMaxLength()).thenReturn(50); + + when(serializer.serialize(ArgumentMatchers.eq(request), ArgumentMatchers.any(EntityCollection.class))).thenReturn( + serializerResult); + when(serializerResult.getContent()).thenReturn(new ByteArrayInputStream("{\"ParentCodeID\":\"NUTS1\"}".getBytes())); + + return request; + + } + + protected ODataRequest prepareSimpleRequest() throws ODataException, ODataJPAProcessorException, SerializerException { + + return prepareSimpleRequest("return=minimal"); + } + + protected ODataRequest prepareSimpleRequest(String content) throws ODataException, ODataJPAProcessorException, + SerializerException { + + final EntityTransaction transaction = mock(EntityTransaction.class); + when(em.getTransaction()).thenReturn(transaction); + + final ODataRequest request = mock(ODataRequest.class); + when(request.getHeaders(HttpHeader.PREFER)).thenReturn(header); + when(sessionContext.getEdmProvider()).thenReturn(jpaEdm); + when(etsInfo.getEdmEntitySet()).thenReturn(ets); + header.add(content); + + Entity odataEntity = mock(Entity.class); + when(convHelper.convertInputStream(same(odata), same(request), same(ContentType.JSON), any())).thenReturn( + odataEntity); + when(convHelper.convertKeyToLocal(ArgumentMatchers.eq(odata), ArgumentMatchers.eq(request), ArgumentMatchers.eq( + ets), ArgumentMatchers.any(JPAEntityType.class), ArgumentMatchers.any())).thenReturn(LOCATION_HEADER); + return request; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java new file mode 100644 index 0000000000..a700a3b1a4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPARequestLinkImpl.java @@ -0,0 +1,181 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOnConditionItem; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.modify.JPAConversionHelper; + +public class TestJPARequestLinkImpl { + private JPARequestLinkImpl cut; + private JPAAssociationPath path; + private List items; + private JPAConversionHelper helper; + private JPAAssociationAttribute pathLeaf; + + @BeforeEach + public void setUp() throws ODataJPAModelException { + helper = new JPAConversionHelper(); + items = new ArrayList<>(); + path = mock(JPAAssociationPath.class); + pathLeaf = mock(JPAAssociationAttribute.class); + when(path.getJoinColumnsList()).thenReturn(items); + } + + @Disabled + @Test + public void testCreateMultipleStringKeysChildren() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("codeID", "CodeID", "parentCodeID", "ParentCodeID")); + items.add(createConditionItem("divisionCode", "DivisionCode", "parentDivisionCode", "ParentDivisionCode")); + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("DE100", act.get("parentDivisionCode")); + assertEquals("NUTS3", act.get("parentCodeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateMultipleStringKeysParent() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("parentCodeID", "ParentCodeID", "codeID", "CodeID")); + items.add(createConditionItem("parentDivisionCode", "ParentDivisionCode", "divisionCode", "DivisionCode")); + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("DE100", act.get("divisionCode")); + assertEquals("NUTS3", act.get("codeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Disabled + @Test + public void testCreateMultipleStringValuesChildren() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("codeID", "CodeID", "parentCodeID", "ParentCodeID")); + items.add(createConditionItem("divisionCode", "DivisionCode", "parentDivisionCode", "ParentDivisionCode")); + Map act = cut.getValues(); + + assertNotNull(act); + assertEquals("DE100", act.get("divisionCode")); + assertEquals("NUTS3", act.get("codeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateMultipleStringValuesParent() throws ODataJPAModelException, ODataException { + String link = "AdministrativeDivisions(DivisionCode='DE100',CodeID='NUTS3',CodePublisher='Eurostat')"; + cut = new JPARequestLinkImpl(path, link, helper); + + items.add(createConditionItem("codePublisher", "CodePublisher", "codePublisher", "CodePublisher")); + items.add(createConditionItem("parentCodeID", "ParentCodeID", "codeID", "CodeID")); + items.add(createConditionItem("parentDivisionCode", "ParentDivisionCode", "divisionCode", "DivisionCode")); + Map act = cut.getValues(); + + assertNotNull(act); + assertEquals("DE100", act.get("parentDivisionCode")); + assertEquals("NUTS3", act.get("parentCodeID")); + assertEquals("Eurostat", act.get("codePublisher")); + } + + @Test + public void testCreateSingleStringKey() throws ODataJPAModelException, ODataException { + String link = "BusinessPartners('123456')"; + cut = new JPARequestLinkImpl(path, link, helper); + + completeJPAPath(); + + Map act = cut.getRelatedKeys(); + assertNotNull(act); + assertEquals("123456", act.get("ID")); + } + + @Test + public void testCreateSingleStringValue() throws ODataJPAModelException, ODataException { + String link = "BusinessPartners('123456')"; + cut = new JPARequestLinkImpl(path, link, helper); + completeJPAPath(); + + Map act = cut.getValues(); + assertNotNull(act); + assertEquals("123456", act.get("businessPartnerID")); + } + + private void completeJPAPath() throws ODataJPAModelException { + JPAEntityType targetEt = mock(JPAEntityType.class); + JPAEntityType sourceEt = mock(JPAEntityType.class); + JPAAttribute bupaKey = mock(JPAAttribute.class); + JPAAttribute roleKey1 = mock(JPAAttribute.class); + JPAAttribute roleKey2 = mock(JPAAttribute.class); + List bupaKeys = new ArrayList<>(); + List roleKeys = new ArrayList<>(); + bupaKeys.add(bupaKey); + roleKeys.add(roleKey1); + roleKeys.add(roleKey2); + when(bupaKey.getInternalName()).thenReturn("ID"); + when(bupaKey.getExternalName()).thenReturn("ID"); + when(roleKey1.getInternalName()).thenReturn("businessPartnerID"); + when(roleKey1.getExternalName()).thenReturn("BusinessPartnerID"); + when(roleKey2.getInternalName()).thenReturn("roleCategory"); + when(roleKey2.getExternalName()).thenReturn("BusinessPartnerRole"); + + items.add(createConditionItem("businessPartnerID", "BusinessPartnerID", "ID", "ID")); + when(path.getLeaf()).thenReturn(pathLeaf); + when(pathLeaf.getInternalName()).thenReturn("businessPartner"); + when(path.getTargetType()).thenReturn(targetEt); + when(path.getSourceType()).thenReturn(sourceEt); + when(targetEt.getKey()).thenReturn(bupaKeys); + when(sourceEt.getKey()).thenReturn(roleKeys); + } + + private JPAOnConditionItem createConditionItem(String leftInternalName, String leftExternalName, + String rightInternalName, String rightExternalName) throws ODataJPAModelException { + + JPAOnConditionItem item = mock(JPAOnConditionItem.class); + + JPAPath leftPath = mock(JPAPath.class); + JPAPath rightPath = mock(JPAPath.class); + when(item.getLeftPath()).thenReturn(leftPath); + when(item.getRightPath()).thenReturn(rightPath); + + JPAAttribute leftAttribute = mock(JPAAttribute.class); + JPAAttribute rightAttribute = mock(JPAAttribute.class); + when(leftPath.getLeaf()).thenReturn(leftAttribute); + when(rightPath.getLeaf()).thenReturn(rightAttribute); + + when(leftAttribute.getInternalName()).thenReturn(leftInternalName); + when(leftAttribute.getExternalName()).thenReturn(leftExternalName); + when(rightAttribute.getInternalName()).thenReturn(rightInternalName); + when(rightAttribute.getExternalName()).thenReturn(rightExternalName); + when(leftAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String); + when(rightAttribute.getEdmType()).thenReturn(EdmPrimitiveTypeKind.String); + + return item; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java new file mode 100644 index 0000000000..a9ef39e2b6 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestJPAUpdateProcessor.java @@ -0,0 +1,397 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.api.http.HttpHeader; +import org.apache.olingo.commons.api.http.HttpMethod; +import org.apache.olingo.commons.api.http.HttpStatusCode; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; +import com.sap.olingo.jpa.processor.core.api.JPACUDRequestHandler; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; + +public class TestJPAUpdateProcessor extends TestJPAModifyProcessor { + + @Test + public void testHockIsCalled() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.called); + } + + @Test + public void testHttpMethodProvided() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpMethod.PATCH, spy.method); + } + + @Test + public void testEntityTypeProvided() throws ODataJPAModelException, ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertTrue(spy.et instanceof JPAEntityType); + } + + @SuppressWarnings("unchecked") + @Test + public void testJPAAttributes() throws ODataJPAModelException, ODataException, UnsupportedEncodingException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + InputStream is = new ByteArrayInputStream("{\"ID\" : \"35\", \"Country\" : \"USA\"}".getBytes("UTF-8")); + when(request.getBody()).thenReturn(is); + Map jpaAttributes = new HashMap<>(); + jpaAttributes.put("id", "35"); + jpaAttributes.put("country", "USA"); + when(convHelper.convertProperties(any(OData.class), any(JPAStructuredType.class), any(List.class))) + .thenReturn(jpaAttributes); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(2, spy.jpaAttributes.size()); + } + + @Test + public void testHeadersProvided() throws ODataJPAProcessorException, SerializerException, ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + final Map> headers = new HashMap<>(); + + when(request.getAllHeaders()).thenReturn(headers); + headers.put("If-Match", Arrays.asList("2")); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertNotNull(spy.headers); + assertEquals(1, spy.headers.size()); + assertNotNull(spy.headers.get("If-Match")); + assertEquals("2", spy.headers.get("If-Match").get(0)); + } + + @Test + public void testMinimalResponseUpdateStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponseCreatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testMinimalResponseUpdatePreferHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(false, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testMinimalResponseCreatedPreferHeader() throws ODataJPAProcessorException, SerializerException, + ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + RequestHandleSpy spy = new RequestHandleSpy(new JPAUpdateResult(true, new Organization())); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(PREFERENCE_APPLIED, response.getHeader(HttpHeader.PREFERENCE_APPLIED)); + } + + @Test + public void testRepresentationResponseUpdatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false, + new Organization()))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseCreatedStatusCode() throws ODataJPAProcessorException, SerializerException, + ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true, + new Organization()))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + + assertEquals(HttpStatusCode.CREATED.getStatusCode(), response.getStatusCode()); + } + + @Test + public void testRepresentationResponseUpdatedErrorMissingEntity() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(false, null))); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testRepresentationResponseCreatedErrorMissingEntity() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(new JPAUpdateResult(true, null))); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testCallsValidateChangesOnSuccessfullProcessing() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(1, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnForginTransaction() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + RequestHandleSpy spy = new RequestHandleSpy(); + when(sessionContext.getCUDRequestHandler()).thenReturn(spy); + when(em.getTransaction()).thenReturn(transaction); + when(transaction.isActive()).thenReturn(Boolean.TRUE); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertEquals(0, spy.noValidateCalls); + } + + @Test + public void testDoesNotCallsValidateChangesOnError() throws ODataException { + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareSimpleRequest(); + when(request.getMethod()).thenReturn(HttpMethod.PATCH); + final JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).updateEntity(any(JPARequestEntity.class), any(EntityManager.class), + any(HttpMethod.class)); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(handler, never()).validateChanges(em); + return; + } + fail(); + } + + @Test + public void testDoesRollbackIfValidateRaisesError() throws ODataException { + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareSimpleRequest(); + + when(em.getTransaction()).thenReturn(transaction); + + JPACUDRequestHandler handler = mock(JPACUDRequestHandler.class); + when(sessionContext.getCUDRequestHandler()).thenReturn(handler); + + doThrow(new ODataJPAProcessorException(ODataJPAProcessorException.MessageKeys.NOT_SUPPORTED_DELETE, + HttpStatusCode.BAD_REQUEST)).when(handler).validateChanges(em); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataApplicationException e) { + verify(transaction, never()).commit(); + verify(transaction, times(1)).rollback(); + return; + } + fail(); + } + + @Test + public void testResponseErrorIfNull() throws ODataJPAProcessorException, ODataException { + + ODataResponse response = new ODataResponse(); + ODataRequest request = prepareRepresentationRequest(new RequestHandleSpy(null)); + + try { + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + } catch (ODataJPAProcessException e) { + assertEquals(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(), e.getStatusCode()); + return; + } + fail(); + } + + @Test + public void testResponseUpdateLink() throws ODataJPAProcessorException, ODataException { + + final AdministrativeDivisionKey key = new AdministrativeDivisionKey("Eurostat", "NUTS2", "DE60"); + final AdministrativeDivision resultEntity = new AdministrativeDivision(key); + + final AdministrativeDivisionKey childKey = new AdministrativeDivisionKey("Eurostat", "NUTS3", "DE600"); + final AdministrativeDivision childEntity = new AdministrativeDivision(childKey); + + final JPAUpdateResult result = new JPAUpdateResult(false, resultEntity); + final ODataResponse response = new ODataResponse(); + final ODataRequest request = prepareLinkRequest(new RequestHandleSpy(result)); + + resultEntity.setChildren(new ArrayList<>(Arrays.asList(childEntity))); + + processor.updateEntity(request, response, ContentType.JSON, ContentType.JSON); + assertNotNull(response); + + } + + class RequestHandleSpy extends JPAAbstractCUDRequestHandler { + public int noValidateCalls; + public JPAEntityType et; + public Map jpaAttributes; + public EntityManager em; + public boolean called = false; + public HttpMethod method; + public Map> headers; + private final JPAUpdateResult change; + // private Map keys; + + RequestHandleSpy() { + this(new JPAUpdateResult(true, new Organization())); + } + + RequestHandleSpy(final JPAUpdateResult typeOfChange) { + this.change = typeOfChange; + } + + @Override + public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em, + final HttpMethod verb) throws ODataJPAProcessException { + this.et = requestEntity.getEntityType(); + this.jpaAttributes = requestEntity.getData(); + // this.keys = requestEntity.getKeys(); + this.em = em; + this.called = true; + this.method = verb; + this.headers = requestEntity.getAllHeader(); + return change; + } + + @Override + public void validateChanges(final EntityManager em) throws ODataJPAProcessException { + this.noValidateCalls++; + } + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java new file mode 100644 index 0000000000..2a78cee387 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/processor/TestModifyUtil.java @@ -0,0 +1,368 @@ +package com.sap.olingo.jpa.processor.core.processor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; +import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; +import com.sap.olingo.jpa.processor.core.testmodel.PostalAddressData; +import com.sap.olingo.jpa.processor.core.testobjects.BusinessPartnerRoleWithoutSetter; +import com.sap.olingo.jpa.processor.core.testobjects.OrganizationWithoutGetter; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestModifyUtil extends TestBase { + private JPAModifyUtil cut; + private Map jpaAttributes; + private BusinessPartner partner; + private JPAEntityType org; + + @BeforeEach + public void setUp() throws ODataException { + cut = new JPAModifyUtil(); + jpaAttributes = new HashMap<>(); + partner = new Organization(); + helper = new TestHelper(emf, PUNIT_NAME); + org = helper.getJPAEntityType("Organizations"); + } + + @Test + public void testSetAttributeOneAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + } + + @Test + public void testSetAttributeMultipleAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", "2"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributeIfAttributeNull() throws ODataJPAProcessException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", null); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNull(partner.getType()); + } + + @Test + public void testDoNotSetAttributeIfNotInMap() throws ODataJPAProcessException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + cut.setAttributes(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributesDeepOneAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + } + + @Test + public void testSetAttributesDeepMultipleAttribute() throws ODataJPAProcessException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("country", "DEU"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("DEU", partner.getCountry()); + } + + @Test + public void testSetAttributeDeepIfAttributeNull() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("type", null); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNull(partner.getType()); + } + + @Test + public void testDoNotSetAttributeDeepIfNotInMap() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + partner.setType("2"); + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertEquals("2", partner.getType()); + } + + @Test + public void testSetAttributesDeepShallIgnoreRequestEntities() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + JPARequestEntity roles = mock(JPARequestEntity.class); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("roles", roles); + cut.setAttributesDeep(jpaAttributes, partner, org); + } + + @Test + public void testSetAttributesDeepOneLevelViaGetter() throws ODataJPAProcessException, + ODataJPAInvocationTargetException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("address", embeddedAttributes); + embeddedAttributes.put("cityName", "Test Town"); + cut.setAttributesDeep(jpaAttributes, partner, org); + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAddress()); + assertEquals("Test Town", partner.getAddress().getCityName()); + } + + @Test + public void testSetAttributesDeepOneLevelViaGetterWithWrongRequestData() throws Throwable { + Map embeddedAttributes = new HashMap<>(); + Map innerEmbeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("administrativeInformation", embeddedAttributes); + embeddedAttributes.put("updated", innerEmbeddedAttributes); + innerEmbeddedAttributes.put("by", null); + try { + cut.setAttributesDeep(jpaAttributes, partner, org); + } catch (ODataJPAInvocationTargetException e) { + assertEquals("Organization/AdministrativeInformation/Updated/By", e.getPath()); + assertEquals(NullPointerException.class, e.getCause().getClass()); + } + } + + @Test + public void testDoNotSetAttributesDeepOneLevelIfNotProvided() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("address", null); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNull(partner.getAddress()); + } + + @Test + public void testSetAttributesDeepOneLevelIfNull() throws ODataJPAProcessException, + ODataJPAInvocationTargetException { + final PostalAddressData address = new PostalAddressData(); + address.setCityName("Test City"); + + partner.setAddress(address); + jpaAttributes.put("iD", "Willi"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAddress()); + assertEquals("Test City", partner.getAddress().getCityName()); + } + + @Test + public void testSetAttributesDeepOneLevelViaSetter() throws ODataJPAProcessException, + ODataJPAInvocationTargetException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("communicationData", embeddedAttributes); + embeddedAttributes.put("email", "Test@Town"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getCommunicationData()); + assertEquals("Test@Town", partner.getCommunicationData().getEmail()); + } + + @Test + public void testSetAttributesDeepTwoLevel() throws ODataJPAProcessException, ODataJPAModelException { + Map embeddedAttributes = new HashMap<>(); + Map innerEmbeddedAttributes = new HashMap<>(); + jpaAttributes.put("iD", "Willi"); + jpaAttributes.put("administrativeInformation", embeddedAttributes); + embeddedAttributes.put("updated", innerEmbeddedAttributes); + innerEmbeddedAttributes.put("by", "Hugo"); + cut.setAttributesDeep(jpaAttributes, partner, org); + + assertEquals("Willi", partner.getID()); + assertNotNull(partner.getAdministrativeInformation()); + assertNotNull(partner.getAdministrativeInformation().getUpdated()); + assertEquals("Hugo", partner.getAdministrativeInformation().getUpdated().getBy()); + } + + @Test + public void testCreatePrimaryKeyOneStringKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return String.class; + } + }); + + jpaAttributes.put("iD", "Willi"); + String act = (String) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals("Willi", act); + } + + @Test + public void testCreatePrimaryKeyOneIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Integer.class; + } + }); + + jpaAttributes.put("iD", new Integer(10)); + Integer act = (Integer) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals(new Integer(10), act); + } + + @Test + public void testCreatePrimaryKeyOneBigIntegerKeyField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = createSingleKeyEntityType(); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return BigInteger.class; + } + }); + + jpaAttributes.put("iD", new BigInteger("10")); + BigInteger act = (BigInteger) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals(new BigInteger("10"), act); + } + + @Test + public void testCreatePrimaryKeyMultipleField() throws ODataJPAProcessException, ODataJPAModelException { + final JPAEntityType et = mock(JPAEntityType.class); + + when(et.getKeyType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return AdministrativeDivisionKey.class; + } + }); + + jpaAttributes.put("codePublisher", "Test"); + jpaAttributes.put("codeID", "10"); + jpaAttributes.put("divisionCode", "10.1"); + AdministrativeDivisionKey act = (AdministrativeDivisionKey) cut.createPrimaryKey(et, jpaAttributes, org); + assertEquals("Test", act.getCodePublisher()); + assertEquals("10", act.getCodeID()); + assertEquals("10.1", act.getDivisionCode()); + } + + @Test + public void testDeepLinkComplexNotExist() throws ODataJPAProcessorException, ODataJPAModelException { + final Organization source = new Organization("100"); + final Person target = new Person(); + target.setID("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "AdministrativeInformation/Updated/User"); + + cut.linkEntities(source, target, path); + + assertNotNull(source.getAdministrativeInformation()); + assertNotNull(source.getAdministrativeInformation().getUpdated()); + assertEquals(target, source.getAdministrativeInformation().getUpdated().getUser()); + } + + @Test + public void testDirectLink() throws ODataJPAProcessorException, ODataJPAModelException { + final Organization source = new Organization("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setBusinessPartnerID("100"); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.linkEntities(source, target, path); + + assertNotNull(source.getRoles()); + assertNotNull(source.getRoles().toArray()[0]); + assertEquals(target, source.getRoles().toArray()[0]); + } + + @Test + public void testSetForeignKeyOneKey() throws ODataJPAModelException, ODataJPAProcessorException { + final Organization source = new Organization("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + cut.setForeignKey(source, target, path); + assertEquals("100", target.getBusinessPartnerID()); + } + + @Test + public void testSetForeignKeyTrhowsExceptionOnMissingGetter() throws ODataJPAModelException, + ODataJPAProcessorException { + final OrganizationWithoutGetter source = new OrganizationWithoutGetter("100"); + final BusinessPartnerRole target = new BusinessPartnerRole(); + target.setRoleCategory("A"); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + assertThrows(ODataJPAProcessorException.class, () -> { + cut.setForeignKey(source, target, path); + }); + } + + @Test + public void testSetForeignKeyTrhowsExceptionOnMissingSetter() throws ODataJPAModelException, + ODataJPAProcessorException { + final Organization source = new Organization("100"); + final BusinessPartnerRoleWithoutSetter target = new BusinessPartnerRoleWithoutSetter(); + final JPAAssociationPath path = helper.getJPAAssociationPath("Organizations", + "Roles"); + + assertThrows(ODataJPAProcessorException.class, () -> { + cut.setForeignKey(source, target, path); + }); + } + + private JPAEntityType createSingleKeyEntityType() throws ODataJPAModelException { + final List keyAttributes = new ArrayList<>(); + final JPAAttribute keyAttribut = mock(JPAAttribute.class); + final JPAEntityType et = mock(JPAEntityType.class); + + when(keyAttribut.getInternalName()).thenReturn("iD"); + keyAttributes.add(keyAttribut); + when(et.getKey()).thenReturn(keyAttributes); + return et; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java new file mode 100644 index 0000000000..f08b7d4f18 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestEdmEntitySetResult.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.server.api.uri.UriParameter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestEdmEntitySetResult { + private EdmEntitySetResult cut; + private List keys; + private EdmEntitySet es; + private EdmEntitySet est; + + @BeforeEach + public void setup() { + keys = new ArrayList<>(); + es = mock(EdmEntitySet.class); + when(es.getName()).thenReturn("Persons"); + est = mock(EdmEntitySet.class); + when(est.getName()).thenReturn("BusinessPartnerRoles"); + } + + @Test + public void testGetEntitySetName() { + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals("Persons", cut.getName()); + } + + @Test + public void testGetEntitySetGetKeys() { + final UriParameter key = mock(UriParameter.class); + when(key.getName()).thenReturn("ID"); + keys.add(key); + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals(keys, cut.getKeyPredicates()); + } + + @Test + public void testGetEntitySetGet() { + cut = new EdmEntitySetResult(es, keys, "Roles"); + assertEquals("Roles", cut.getNavigationPath()); + } + + @Test + public void testDetermineTargetEntitySetWithNaviNull() { + when(es.getNavigationPropertyBindings()).thenReturn(null); + cut = new EdmEntitySetResult(es, keys, null); + assertEquals(es, cut.getTargetEdmEntitySet()); + } + + @Test + public void testDetermineTargetEntitySetWithNaviEmpty() { + when(es.getNavigationPropertyBindings()).thenReturn(null); + cut = new EdmEntitySetResult(es, keys, ""); + assertEquals(es, cut.getTargetEdmEntitySet()); + } + +// return edmEntitySet.getEntityContainer().getEntitySet(navi.getTarget()); + @Test + public void testDetermineTargetEntitySetWithNavigation() { + final EdmEntityContainer container = mock(EdmEntityContainer.class); + final List bindings = new ArrayList<>(2); + EdmNavigationPropertyBinding binding = mock(EdmNavigationPropertyBinding.class); + bindings.add(binding); + when(binding.getPath()).thenReturn("InhouseAddress"); + + binding = mock(EdmNavigationPropertyBinding.class); + bindings.add(binding); + when(binding.getPath()).thenReturn("Roles"); + when(binding.getTarget()).thenReturn("BusinessPartnerRoles"); + when(es.getEntityContainer()).thenReturn(container); + when(es.getNavigationPropertyBindings()).thenReturn(bindings); + when(container.getEntitySet("BusinessPartnerRoles")).thenReturn(est); + + cut = new EdmEntitySetResult(es, keys, "Roles"); + assertEquals(es, cut.getEdmEntitySet()); + assertEquals(est, cut.getTargetEdmEntitySet()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java new file mode 100644 index 0000000000..bdc544a3a4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandQueryCreateResult.java @@ -0,0 +1,249 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; + +public class TestJPAExpandQueryCreateResult extends TestBase { + private JPAExpandJoinQuery cut; + private JPAODataSessionContextAccess context; + + @BeforeEach + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + createHeaders(); + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "BusinessPartnerRole"); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, + TestBase.enumPackages), ds, null); + cut = new JPAExpandJoinQuery( + null, context, emf.createEntityManager(), new ExpandItemDouble(targetEntity).getResourcePath(), + helper.getJPAAssociationPath("Organizations", "Roles"), helper.sd.getEntity(targetEntity), + new HashMap>()); + // new EdmEntitySetDouble(nameBuilder, "Organisations"), null, new HashMap>()); + } + + @Test + public void checkConvertOneResult() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "1"); + oneResult.put("RoleCategory", "A"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("1")); + assertEquals(1, act.get("1").size()); + assertEquals("1", act.get("1").get(0).get("BusinessPartnerID")); + } + + @Test + public void checkConvertTwoResultOneParent() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(2, act.get("2").size()); + assertEquals("2", act.get("2").get(0).get("BusinessPartnerID")); + } + + @Test + public void checkConvertTwoResultOneParentTop1() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, 1); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("A", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertTwoResultOneParentSkip1() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 1, 1000); + + assertEquals(1, act.size()); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("C", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertTwoResultTwoParent() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "1"); + oneResult.put("RoleCategory", "A"); + t = new TupleDouble(oneResult); + result.add(t); + oneResult = new HashMap<>(); + oneResult.put("BusinessPartnerID", "2"); + oneResult.put("RoleCategory", "C"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(2, act.size()); + assertNotNull(act.get("1")); + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("C", act.get("2").get(0).get("RoleCategory")); + } + + @Test + public void checkConvertOneResultCompundKey() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent"); + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE25"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE2"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("NUTS/2/BE25")); + assertEquals(1, act.get("NUTS/2/BE25").size()); + assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode")); + } + + @Test + public void checkConvertTwoResultsCompundKey() throws ODataJPAModelException, ODataApplicationException { + JPAAssociationPath exp = helper.getJPAAssociationPath("AdministrativeDivisions", "Parent"); + List result = new ArrayList<>(); + HashMap oneResult; + Tuple t; + + oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE25"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE2"); + t = new TupleDouble(oneResult); + result.add(t); + + oneResult = new HashMap<>(); + oneResult.put("CodePublisher", "NUTS"); + oneResult.put("DivisionCode", "BE10"); + oneResult.put("CodeID", "2"); + oneResult.put("ParentCodeID", "1"); + oneResult.put("ParentDivisionCode", "BE1"); + t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertEquals(2, act.size()); + assertNotNull(act.get("NUTS/2/BE25")); + assertEquals(1, act.get("NUTS/2/BE25").size()); + assertEquals("BE2", act.get("NUTS/2/BE25").get(0).get("ParentDivisionCode")); + assertNotNull(act.get("NUTS/2/BE10")); + assertEquals(1, act.get("NUTS/2/BE10").size()); + assertEquals("BE1", act.get("NUTS/2/BE10").get(0).get("ParentDivisionCode")); + } + + @Test + public void checkConvertOneResultJoinTable() throws ODataException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "SupportEngineers"); + + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "Person"); + cut = new JPAExpandJoinQuery( + null, context, emf.createEntityManager(), new ExpandItemDouble(targetEntity).getResourcePath(), + helper.getJPAAssociationPath("Organizations", "SupportEngineers"), helper.sd.getEntity(targetEntity), + new HashMap>()); + + List result = new ArrayList<>(); + HashMap oneResult = new HashMap<>(); + oneResult.put("SupportEngineers" + JPAExpandJoinQuery.ALIAS_SEPERATOR + "ID", "2"); + oneResult.put("ID", "97"); + Tuple t = new TupleDouble(oneResult); + result.add(t); + + Map> act = cut.convertResult(result, exp, 0, Long.MAX_VALUE); + + assertNotNull(act.get("2")); + assertEquals(1, act.get("2").size()); + assertEquals("97", act.get("2").get(0).get("ID")); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java new file mode 100644 index 0000000000..82f0ec9ff6 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAExpandResult.java @@ -0,0 +1,116 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.Expression; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAServiceDebugger; +import com.sap.olingo.jpa.processor.core.database.JPADefaultDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAExpandResult extends TestBase { + private JPAExpandJoinQuery cut; + private EntityManager em; + private JPAODataSessionContextAccess sessionContext; + private TestHelper helper; + + @BeforeEach + public void setup() throws ODataException { + createHeaders(); + helper = new TestHelper(emf, PUNIT_NAME); + em = emf.createEntityManager(); + sessionContext = mock(JPAODataSessionContextAccess.class); + JPAServiceDebugger debugger = mock(JPAServiceDebugger.class); + + when(sessionContext.getEdmProvider()).thenReturn(helper.edmProvider); + when(sessionContext.getOperationConverter()).thenReturn(new JPADefaultDatabaseProcessor()); + when(sessionContext.getDebugger()).thenReturn(debugger); + } + + @Test + public void testSelectAllWithAllExpand() throws ODataException { + // .../Organizations?$expand=Roles&$format=json + JPAInlineItemInfo item = createOrgExpandRoles(null, null); + + cut = new JPAExpandJoinQuery(OData.newInstance(), sessionContext, em, item, headers); + JPAExpandQueryResult act = cut.execute(); + assertEquals(4, act.getNoResults()); + assertEquals(7, act.getNoResultsDeep()); + } + + @Test + public void testSelectOrgByIdWithAllExpand() throws ODataException { + + // .../Organizations('2')?$expand=Roles&$format=json + UriParameter key = mock(UriParameter.class); + when(key.getName()).thenReturn("ID"); + when(key.getText()).thenReturn("'2'"); + List keyPredicates = new ArrayList<>(); + keyPredicates.add(key); + JPAInlineItemInfo item = createOrgExpandRoles(keyPredicates, null); + + cut = new JPAExpandJoinQuery(OData.newInstance(), sessionContext, em, item, headers); + JPAExpandQueryResult act = cut.execute(); + assertEquals(1, act.getNoResults()); + assertEquals(2, act.getNoResultsDeep()); + } + + private JPAInlineItemInfo createOrgExpandRoles(final List keyPredicates, Expression expression) + throws ODataJPAModelException, ODataApplicationException { + JPAEntityType et = helper.getJPAEntityType("BusinessPartnerRoles"); + JPAExpandItemWrapper uriInfo = mock(JPAExpandItemWrapper.class); + UriResourceEntitySet uriEts = mock(UriResourceEntitySet.class); + when(uriEts.getKeyPredicates()).thenReturn(keyPredicates); + EdmEntityType edmType = mock(EdmEntityType.class); + + List hops = new ArrayList<>(); + JPANavigationProptertyInfo hop = new JPANavigationProptertyInfo(helper.sd, uriEts, helper.getJPAEntityType( + "Organizations").getAssociationPath("Roles"), null); + hops.add(hop); + + JPAInlineItemInfo item = mock(JPAInlineItemInfo.class); + UriResourceNavigation target = mock(UriResourceNavigation.class); + EdmNavigationProperty targetProperty = mock(EdmNavigationProperty.class); + when(targetProperty.getName()).thenReturn("Roles"); + when(target.getProperty()).thenReturn(targetProperty); + List resourceParts = new ArrayList<>(); + resourceParts.add(target); + + hop = new JPANavigationProptertyInfo(helper.sd, null, null, et); + hops.add(hop); + + when(item.getEntityType()).thenReturn(et); + when(item.getUriInfo()).thenReturn(uriInfo); + when(item.getHops()).thenReturn(hops); + when(item.getExpandAssociation()).thenReturn(helper.getJPAEntityType("Organizations") + .getAssociationPath("Roles")); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriEts.getType()).thenReturn(edmType); + when(edmType.getNamespace()).thenReturn(PUNIT_NAME); + when(edmType.getName()).thenReturn("Organization"); + return item; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java new file mode 100644 index 0000000000..8105177df8 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunction.java @@ -0,0 +1,88 @@ +package com.sap.olingo.jpa.processor.core.query; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAFunction { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static DataSource ds; + + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + + @BeforeEach + public void setup() { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + emf.getProperties(); + } + + @Disabled // TODO check is path is in general allowed + @Test + public void testNavigationAfterFunctionNotAllowed() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, + "Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Parent"); + helper.assertStatus(501); + } + + @Test + public void testFunctionGenerateQueryString() throws IOException, ODataException, SQLException { + createFunction(); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, + "Siblings(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')"); + helper.assertStatus(200); + } + + private void createFunction() { + final EntityManager em = emf.createEntityManager(); + final EntityTransaction t = em.getTransaction(); + final StringBuilder createSiblingsString = new StringBuilder(); + createSiblingsString.append( + "CREATE FUNCTION \"OLINGO\".\"Siblings\" (\"Publisher\" VARCHAR(10), \"ID\" VARCHAR(10), \"Division\" VARCHAR(10)) "); + createSiblingsString.append( + "RETURNS TABLE(\"CodePublisher\" VARCHAR(10),\"CodeID\" VARCHAR(10),\"DivisionCode\" VARCHAR(10),"); + createSiblingsString.append( + "\"CountryISOCode\" VARCHAR(4), \"ParentCodeID\" VARCHAR(10),\"ParentDivisionCode\" VARCHAR(10),"); + createSiblingsString.append("\"AlternativeCode\" VARCHAR(10),\"Area\" int, \"Population\" BIGINT) "); + createSiblingsString.append("READS SQL DATA "); + createSiblingsString.append("RETURN TABLE( SELECT * FROM \"AdministrativeDivision\" as a WHERE "); + createSiblingsString.append("EXISTS (SELECT \"CodePublisher\" "); + createSiblingsString.append("FROM \"OLINGO\".\"AdministrativeDivision\" as b "); + createSiblingsString.append("WHERE b.\"CodeID\" = \"ID\" "); + createSiblingsString.append("AND b.\"DivisionCode\" = \"Division\" "); + createSiblingsString.append("AND b.\"CodePublisher\" = a.\"CodePublisher\" "); + createSiblingsString.append("AND b.\"ParentCodeID\" = a.\"ParentCodeID\" "); + createSiblingsString.append("AND b.\"ParentDivisionCode\" = a.\"ParentDivisionCode\") "); + createSiblingsString.append("AND NOT( a.\"CodePublisher\" = \"Publisher\" "); + createSiblingsString.append("AND a.\"CodeID\" = \"ID\" "); + createSiblingsString.append("AND a.\"DivisionCode\" = \"Division\" )); "); + t.begin(); + Query qP = em.createNativeQuery(createSiblingsString.toString()); + qP.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java new file mode 100644 index 0000000000..7a8b612dbe --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionDB.java @@ -0,0 +1,148 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.EntityManager; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.core.edm.primitivetype.EdmBoolean; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.annotation.EdmFunctionType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPADataBaseFunction; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAOperationResultParameter; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataDatabaseProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; + +public class TestJPAFunctionDB { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + private JPAODataDatabaseProcessor dbProcessor; + + private OData odata; + private JPAODataSessionContextAccess context; + private JPAODataRequestContextAccess requestContext; + private ODataRequest request; + private ODataResponse response; + private JPAFunctionRequestProcessor cut; + private EdmFunction edmFunction; + private UriInfo uriInfo; + private List uriResources; + private UriResourceFunction uriResource; + private JPAServiceDocument sd; + private JPADataBaseFunction function; + private JPAOperationSerializer serializer; + private SerializerResult serializerResult; + private EntityManager em; + + @BeforeEach + public void setup() throws ODataException { + final JPAEdmProvider provider = mock(JPAEdmProvider.class); + + em = mock(EntityManager.class); + request = mock(ODataRequest.class); + response = mock(ODataResponse.class); + uriInfo = mock(UriInfo.class); + odata = mock(OData.class); + serializer = mock(JPAOperationSerializer.class); + serializerResult = mock(SerializerResult.class); + context = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + dbProcessor = mock(JPAODataDatabaseProcessor.class); + sd = mock(JPAServiceDocument.class); + uriResource = mock(UriResourceFunction.class); + function = mock(JPADataBaseFunction.class); + uriResources = new ArrayList<>(); + edmFunction = mock(EdmFunction.class); + + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getEntityManager()).thenReturn(em); + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(context.getDatabaseProcessor()).thenReturn(dbProcessor); + when(context.getEdmProvider()).thenReturn(provider); + when(provider.getServiceDocument()).thenReturn(sd); + uriResources.add(uriResource); + when(uriResource.getFunction()).thenReturn(edmFunction); + when(sd.getFunction(edmFunction)).thenReturn(function); + when(function.getFunctionType()).thenReturn(EdmFunctionType.UserDefinedFunction); + cut = new JPAFunctionRequestProcessor(odata, context, requestContext); + } + + @Test + public void testCallsFunctionWithBooleanReturnType() throws ODataApplicationException, ODataLibraryException, + ODataJPAModelException { + + EdmReturnType edmReturnType = mock(EdmReturnType.class); + JPAOperationResultParameter resultParam = mock(JPAOperationResultParameter.class); + when(function.getResultParameter()).thenReturn(resultParam); + when(resultParam.getTypeFQN()).thenReturn(new FullQualifiedName(PUNIT_NAME, "CheckRights")); + when(resultParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Boolean.class; + } + }); + + when(edmFunction.getReturnType()).thenReturn(edmReturnType); + when(edmReturnType.getType()).thenReturn(new EdmBoolean()); + + cut.retrieveData(request, response, ContentType.JSON); + verify(dbProcessor, times(1)).executeFunctionQuery(eq(uriResources), eq(function), eq(em)); + } + + @Test + public void testCallsFunctionCount() throws ODataApplicationException, ODataLibraryException, + ODataJPAModelException { + + EdmReturnType edmReturnType = mock(EdmReturnType.class); + JPAOperationResultParameter resultParam = mock(JPAOperationResultParameter.class); + when(function.getResultParameter()).thenReturn(resultParam); + when(resultParam.getTypeFQN()).thenReturn(new FullQualifiedName(PUNIT_NAME, "CheckRights")); + when(resultParam.getType()).thenAnswer(new Answer>() { + @Override + public Class answer(InvocationOnMock invocation) throws Throwable { + return Boolean.class; + } + }); + + when(edmFunction.getReturnType()).thenReturn(edmReturnType); + when(edmReturnType.getType()).thenReturn(new EdmBoolean()); + + cut.retrieveData(request, response, ContentType.JSON); + verify(dbProcessor, times(1)).executeFunctionQuery(eq(uriResources), eq(function), eq(em)); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java new file mode 100644 index 0000000000..50aaa77bff --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionJava.java @@ -0,0 +1,162 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.data.Annotatable; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmParameter; +import org.apache.olingo.commons.api.edm.EdmReturnType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.commons.api.format.ContentType; +import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.ODataLibraryException; +import org.apache.olingo.server.api.ODataRequest; +import org.apache.olingo.server.api.ODataResponse; +import org.apache.olingo.server.api.serializer.SerializerResult; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceFunction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestContextAccess; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.processor.JPAFunctionRequestProcessor; +import com.sap.olingo.jpa.processor.core.serializer.JPAOperationSerializer; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testobjects.TestFunctionParameter; + +public class TestJPAFunctionJava { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + private JPAFunctionRequestProcessor cut; + private OData odata; + private JPAODataSessionContextAccess context; + private JPAODataRequestContextAccess requestContext; + private UriInfo uriInfo; + private List uriResources; + private ODataRequest request; + private ODataResponse response; + private UriResourceFunction uriResource; + private EdmFunction edmFunction; + private JPAOperationSerializer serializer; + private SerializerResult serializerResult; + + @BeforeEach + public void setup() throws ODataException { + odata = mock(OData.class); + context = mock(JPAODataSessionContextAccess.class); + requestContext = mock(JPAODataRequestContextAccess.class); + EntityManager em = mock(EntityManager.class); + uriInfo = mock(UriInfo.class); + serializer = mock(JPAOperationSerializer.class); + serializerResult = mock(SerializerResult.class); + + DataSource ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + final EntityManagerFactory emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + uriResources = new ArrayList<>(); + when(uriInfo.getUriResourceParts()).thenReturn(uriResources); + when(context.getEdmProvider()).thenReturn(new JPAEdmProvider(PUNIT_NAME, emf, null, new String[] { + "com.sap.olingo.jpa.processor.core", "com.sap.olingo.jpa.processor.core.testmodel" })); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(requestContext.getEntityManager()).thenReturn(em); + when(requestContext.getSerializer()).thenReturn(serializer); + when(serializer.serialize(any(Annotatable.class), any(EdmType.class))).thenReturn(serializerResult); + + request = mock(ODataRequest.class); + response = mock(ODataResponse.class); + uriResource = mock(UriResourceFunction.class); + edmFunction = mock(EdmFunction.class); + uriResources.add(uriResource); + when(uriResource.getFunction()).thenReturn(edmFunction); + + cut = new JPAFunctionRequestProcessor(odata, context, requestContext); + } + + @AfterEach + public void teardown() { + TestFunctionParameter.calls = 0; + TestFunctionParameter.param1 = 0; + TestFunctionParameter.param2 = 0; + } + + @Test + public void testCallsFunction() throws ODataApplicationException, ODataLibraryException { + EdmParameter edmParamA = mock(EdmParameter.class); + EdmParameter edmParamB = mock(EdmParameter.class); + EdmReturnType edmReturn = mock(EdmReturnType.class); + EdmType edmType = mock(EdmType.class); + + when(edmFunction.getReturnType()).thenReturn(edmReturn); + when(edmFunction.getName()).thenReturn("Sum"); + when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME); + when(edmFunction.getParameter("A")).thenReturn(edmParamA); + when(edmParamA.getType()).thenReturn(new EdmInt32()); + when(edmFunction.getParameter("B")).thenReturn(edmParamB); + when(edmParamB.getType()).thenReturn(new EdmInt32()); + List parameterList = buildParameters(); + when(uriResource.getParameters()).thenReturn(parameterList); + when(edmReturn.getType()).thenReturn(edmType); + when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.retrieveData(request, response, ContentType.JSON); + assertEquals(1, TestFunctionParameter.calls); + } + + @Test + public void testProvidesParameter() throws ODataApplicationException, ODataLibraryException { + EdmParameter edmParamA = mock(EdmParameter.class); + EdmParameter edmParamB = mock(EdmParameter.class); + EdmReturnType edmReturn = mock(EdmReturnType.class); + EdmType edmType = mock(EdmType.class); + + when(edmFunction.getReturnType()).thenReturn(edmReturn); + when(edmFunction.getName()).thenReturn("Sum"); + when(edmFunction.getNamespace()).thenReturn(PUNIT_NAME); + when(edmFunction.getParameter("A")).thenReturn(edmParamA); + when(edmParamA.getType()).thenReturn(new EdmInt32()); + when(edmFunction.getParameter("B")).thenReturn(edmParamB); + when(edmParamB.getType()).thenReturn(new EdmInt32()); + List parameterList = buildParameters(); + when(uriResource.getParameters()).thenReturn(parameterList); + when(edmReturn.getType()).thenReturn(edmType); + when(edmType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + + cut.retrieveData(request, response, ContentType.JSON); + assertEquals(5, TestFunctionParameter.param1); + assertEquals(7, TestFunctionParameter.param2); + } + + private List buildParameters() { + UriParameter param1 = mock(UriParameter.class); + UriParameter param2 = mock(UriParameter.class); + when(param1.getName()).thenReturn("A"); + when(param1.getText()).thenReturn("5"); + when(param2.getName()).thenReturn("B"); + when(param2.getText()).thenReturn("7"); + return Arrays.asList(new UriParameter[] { param1, param2 }); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java new file mode 100644 index 0000000000..6ea5b775cc --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAFunctionSerializer.java @@ -0,0 +1,187 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.sql.DataSource; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAFunctionSerializer { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + protected static EntityManagerFactory emf; + protected static DataSource ds; + + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + + @BeforeEach + public void setup() { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + Map properties = new HashMap<>(); + properties.put("javax.persistence.nonJtaDataSource", ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + emf.getProperties(); + } + + @Test + public void testFunctionReturnsEntityType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("Area").asInt()); + assertEquals(1250, r.get("Area").asInt()); + } + + @Test + public void testFunctionReturnsEntityTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityType(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsEntityTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityType(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + ArrayNode values = (ArrayNode) r.get("value"); + assertNotNull(values.get(0)); + assertNotNull(values.get(0).get("Area").asInt()); + assertEquals(1250, values.get(0).get("Area").asInt()); + assertNotNull(values.get(1)); + assertNotNull(values.get(1).get("Area").asInt()); + assertEquals(625, values.get(1).get("Area").asInt()); + } + + @Test + public void testFunctionReturnsPrimitiveType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r); + assertNotNull(r.get("value")); + assertEquals(124, r.get("value").asInt()); + } + + @Test + public void testFunctionReturnsPrimitiveTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "PrimitiveValue(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsPrimitiveTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfPrimitiveValues(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ArrayNode r = helper.getValues(); + assertNotNull(r); + assertNotNull(r.get(0)); + assertEquals(124, r.get(0).asInt()); + assertNotNull(r.get(1)); + assertEquals(62, r.get(1).asInt()); + } + + @Test + public void testFunctionReturnsComplexType() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=124)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r); + assertNotNull(r.get("LandlinePhoneNumber")); + assertEquals(124, r.get("LandlinePhoneNumber").asInt()); + } + + @Test + public void testFunctionReturnsComplexTypeNull() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ComplexType(A=0)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(204); + } + + @Test + public void testFunctionReturnsComplexTypeCollection() throws IOException, ODataException, SQLException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfComplexType(A='Willi')", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ArrayNode r = helper.getValues(); + assertNotNull(r); + assertNotNull(r.get(0)); + assertNotNull(r.get(0).get("Created")); + } + + @Test + public void testUsesConverter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ConvertBirthday()", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + } + + @Test + public void testFunctionReturnsEntityTypeWithCollection() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "ListOfEntityTypeWithCollction(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("value")); + ObjectNode person = (ObjectNode) r.get("value").get(0); + ArrayNode addr = (ArrayNode) person.get("InhouseAddress"); + assertEquals(2, addr.size()); + } + + @Test + public void testFunctionReturnsEntityTypeWithDeepCollection() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, ds, "EntityTypeWithDeepCollction(A=1250)", + "com.sap.olingo.jpa.processor.core.query"); + helper.assertStatus(200); + ObjectNode r = helper.getValue(); + assertNotNull(r.get("FirstLevel")); + ObjectNode first = (ObjectNode) r.get("FirstLevel"); + assertEquals(10, first.get("LevelID").asInt()); + + assertNotNull(first.get("SecondLevel")); + ObjectNode second = (ObjectNode) first.get("SecondLevel"); + assertEquals(5L, second.get("Number").asLong()); + ArrayNode addr = (ArrayNode) second.get("Address"); + assertEquals(2, addr.size()); + assertEquals("ADMIN", addr.get(1).get("TaskID").asText()); + + ArrayNode comment = (ArrayNode) second.get("Comment"); + assertEquals(3, comment.size()); + assertEquals("Three", comment.get(2).asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java new file mode 100644 index 0000000000..09668fd8f4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAInstanceResultConverter.java @@ -0,0 +1,126 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.converter.JPAEntityResultConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPAInstanceResultConverter extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPAEntityResultConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + + @BeforeEach + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList<>(); + HashMap keyStrings = new HashMap<>(); + keyStrings.put("BE21", "DivisionCode='BE21',CodeID='NUTS2',CodePublisher='Eurostat'"); + keyStrings.put("BE22", "DivisionCode='BE22',CodeID='NUTS2',CodePublisher='Eurostat'"); + + uriHelper = new UriHelperDouble(); + uriHelper.setKeyPredicates(keyStrings, "DivisionCode"); + cut = new JPAEntityResultConverter(uriHelper, helper.sd, + jpaQueryResult, new EdmEntityTypeDouble(nameBuilder, "AdministrativeDivision")); + } + + @Test + public void checkConvertsEmptyResult() throws ODataApplicationException, SerializerException, URISyntaxException { + assertNotNull(cut.getResult()); + } + + @Test + public void checkConvertsOneResult() throws ODataApplicationException, SerializerException, URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + } + + @Test + public void checkConvertsTwoResult() throws ODataApplicationException, SerializerException, URISyntaxException { + + jpaQueryResult.add(firstResult()); + jpaQueryResult.add(secondResult()); + EntityCollection act = cut.getResult(); + assertEquals(2, act.getEntities().size()); + } + + @Test + public void checkConvertsOneResultOneElement() throws ODataApplicationException, SerializerException, + URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + assertEquals("BE21", act.getEntities().get(0).getProperty("DivisionCode").getValue().toString()); + + } + + @Test + public void checkConvertsOneResultMultiElement() throws ODataApplicationException, SerializerException, + URISyntaxException { + AdministrativeDivision division = firstResult(); + + jpaQueryResult.add(division); + + EntityCollection act = cut.getResult(); + assertEquals(1, act.getEntities().size()); + assertEquals("BE21", act.getEntities().get(0).getProperty("DivisionCode").getValue().toString()); + assertEquals("BE2", act.getEntities().get(0).getProperty("ParentDivisionCode").getValue().toString()); + assertEquals("0", act.getEntities().get(0).getProperty("Population").getValue().toString()); + } + + AdministrativeDivision firstResult() { + AdministrativeDivision division = new AdministrativeDivision(); + + division.setCodePublisher("Eurostat"); + division.setCodeID("NUTS2"); + division.setDivisionCode("BE21"); + division.setCountryCode("BEL"); + division.setParentCodeID("NUTS1"); + division.setParentDivisionCode("BE2"); + division.setAlternativeCode(""); + division.setArea(0); + division.setPopulation(0); + return division; + } + + private Object secondResult() { + AdministrativeDivision division = new AdministrativeDivision(); + + division.setCodePublisher("Eurostat"); + division.setCodeID("NUTS2"); + division.setDivisionCode("BE22"); + division.setCountryCode("BEL"); + division.setParentCodeID("NUTS1"); + division.setParentDivisionCode("BE2"); + division.setAlternativeCode(""); + division.setArea(0); + division.setPopulation(0); + return division; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java new file mode 100644 index 0000000000..ee7b6d02a2 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAProcessorExpand.java @@ -0,0 +1,633 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAProcessorExpand extends TestBase { + + @Test + public void testExpandEntitySet() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID&$expand=Roles"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + ObjectNode org = (ObjectNode) orgs.get(0); + ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(1, roles.size()); + + org = (ObjectNode) orgs.get(3); + roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + } + + @Test + public void testExpandOneEntity() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('2')?$expand=Roles"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(2, roles.size()); + int found = 0; + for (final JsonNode role : roles) { + final String id = role.get("BusinessPartnerID").asText(); + final String code = role.get("RoleCategory").asText(); + if (id.equals("2") && (code.equals("A") || code.equals("C"))) + found++; + } + assertEquals(2, found, "Not all expected results found"); + } + + @Test + public void testExpandOneEntityCompoundKey() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent"); + helper.assertStatus(200); + + final ObjectNode divsion = helper.getValue(); + final ObjectNode parent = (ObjectNode) divsion.get("Parent"); + assertEquals("BE2", parent.get("DivisionCode").asText()); + + } + + @Test + public void testExpandOneEntityCompoundKeyCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)"); + helper.assertStatus(200); + + final ObjectNode divsion = helper.getValue(); + final ArrayNode parent = (ArrayNode) divsion.get("Children"); + assertEquals(8, parent.size()); + assertEquals("BE251", parent.get(0).get("DivisionCode").asText()); + + } + + @Test + public void testExpandEntitySetWithOutParentKeySelection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Name1&$select=Name1&$expand=Roles"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(9); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + + } + + @Test + public void testExpandEntitySetViaNonKeyField_FieldNotSelected() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created?$select=At&$expand=User"); + helper.assertStatus(200); + + final ObjectNode created = helper.getValue(); + assertNotNull(created.get("User")); + } + + @Test + public void testExpandEntitySetViaNonKeyFieldNavi2Hops() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created?$expand=User"); + helper.assertStatus(200); + + final ObjectNode created = helper.getValue(); + @SuppressWarnings("unused") + final ObjectNode user = (ObjectNode) created.get("User"); + } + + @Test + public void testExpandEntityViaComplexProperty() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address?$expand=AdministrativeDivision"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ObjectNode created = (ObjectNode) org.get("AdministrativeDivision"); + assertEquals("USA", created.get("ParentDivisionCode").asText()); + } + + @Disabled // Version 4.4.0 of olingo does not path the expand correctly + // org.apache.olingo.server.core.uri.parser.ExpandParser -> parseExpandPath + // see https://issues.apache.org/jira/browse/OLINGO-1143 + @Test + public void testExpandEntitySetViaNonKeyFieldNavi0Hops() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$expand=AdministrativeInformation/Created/User"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + final ObjectNode admin = (ObjectNode) org.get("AdministrativeInformation"); + final ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User")); + + } + + @Disabled // Version 4.4.0 of olingo does not path the expand correctly + // org.apache.olingo.server.core.uri.parser.ExpandParser -> parseExpandPath + // see https://issues.apache.org/jira/browse/OLINGO-1143 + @Test + public void testExpandEntitySetViaNonKeyFieldNavi1Hop() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation?$expand=Created/User"); + helper.assertStatus(200); + + final ObjectNode admin = helper.getValue(); + final ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User")); + } + + @Test + public void testNestedExpandNestedExpand2LevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($expand=Children)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Children")); + final ArrayNode children = (ArrayNode) parent.get("Children"); + assertEquals(8, children.size()); + assertEquals("NUTS3", children.get(0).get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand3LevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='33016',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Parent")); + assertNotNull(parent.get("Parent").get("CodeID")); + assertEquals("NUTS3", parent.get("CodeID").asText()); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent); + assertNotNull(grandParent.get("CodeID")); + assertEquals("NUTS2", grandParent.get("CodeID").asText()); + final ObjectNode greateGrandParent = (ObjectNode) grandParent.get("Parent"); + assertNotNull(greateGrandParent); + assertNotNull(greateGrandParent.get("CodeID")); + assertEquals("NUTS1", greateGrandParent.get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand3Only1PossibleLevelsSelf() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent($expand=Parent($expand=Parent))"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("CodeID")); + assertEquals("NUTS1", parent.get("CodeID").asText()); + } + + @Test + public void testNestedExpandNestedExpand2LevelsMixed() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address?$select=Country&$expand=AdministrativeDivision($expand=Parent)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode admin = (ObjectNode) div.get("AdministrativeDivision"); + assertNotNull(admin); + final ObjectNode parent = (ObjectNode) admin.get("Parent"); + assertEquals("3166-1", parent.get("CodeID").asText()); + } + + @Disabled // TODO check how the result should look like + @Test + public void testExpandWithNavigationToEntity() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='3',CodePublisher='NUTS')?$expand=Parent/Parent"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("Parent").get("CodeID")); + assertEquals("1", parent.get("Parent").get("CodeID").asText()); + } + + @Disabled // TODO check with Olingo looks like OData does not support this + @Test + public void testExpandWithNavigationToProperty() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE253',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent/CodeID"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ObjectNode parent = (ObjectNode) div.get("Parent"); + assertNotNull(parent.get("CodeID")); + assertEquals("NUTS2", parent.get("CodeID").asText()); + // TODO: Check how to create the response correctly + // assertEquals(1, parent.size()); + } + + @Test + public void testExpandAfterNavigationToEntity() throws IOException, ODataException { + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$filter=DivisionCode eq 'BE21'&$expand=Children($orderby=DivisionCode)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("value").get(0).get("Children"); + assertNotNull(children); + assertEquals(3, children.size()); + assertEquals("BE211", children.get(0).get("DivisionCode").asText()); + assertEquals("BE212", children.get(1).get("DivisionCode").asText()); + assertEquals("BE213", children.get(2).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDesc() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(5, children.size()); + assertEquals("BE25", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByAsc() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($orderby=DivisionCode asc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(5, children.size()); + assertEquals("BE21", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDescTop() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($top=2;$orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(2, children.size()); + assertEquals("BE25", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithOrderByDescTopSkip() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')?$expand=Children($top=2;$skip=2;$orderby=DivisionCode desc)"); + helper.assertStatus(200); + + final ObjectNode div = helper.getValue(); + final ArrayNode children = (ArrayNode) div.get("Children"); + assertEquals(2, children.size()); + assertEquals("BE23", children.get(0).get("DivisionCode").asText()); + } + + @Test + public void testExpandWithCount() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($count=true)&$orderby=Roles/$count desc"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("Roles")); + ArrayNode roles = (ArrayNode) org.get("Roles"); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(roles.size(), org.get("Roles@odata.count").asInt()); + } + + @Test + public void testExpandWithCountPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('2')?$expand=Roles/$count"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(2, org.get("Roles@odata.count").asInt()); + } + + @Disabled // ODataJsonSerializer.writeExpandedNavigationProperty does not write a "@odata.count" for to 1 relations + @Test + public void testExpandOppositeDirectionWithCount() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')?$expand=Organization/$count"); + helper.assertStatus(200); + + final ObjectNode role = helper.getValue(); + assertNotNull(role.get("Organization")); + assertNotNull(role.get("Organization@odata.count")); + assertEquals(1, role.get("Organization@odata.count").asText()); + } + + @Test + public void testExpandWithCountAndTop() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($count=true;$top=1)&$orderby=Roles/$count desc"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("Roles")); + assertNotNull(org.get("Roles@odata.count")); + assertEquals(3, org.get("Roles@odata.count").asInt()); + } + + @Test + public void testExpandWithOrderByDescTopSkipAndExternalOrderBy() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$count=true&$expand=Roles($orderby=RoleCategory desc)&$orderby=Roles/$count desc"); + + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertEquals("3", org.get("ID").asText()); + assertNotNull(org.get("Roles")); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(3, roles.size()); + final ObjectNode firstRole = (ObjectNode) roles.get(0); + assertEquals("C", firstRole.get("RoleCategory").asText()); + } + + @Test + public void testExpandWithFilter() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Children($filter=DivisionCode eq 'BE252')"); + + helper.assertStatus(200); + + final ObjectNode division = helper.getValue(); + assertEquals("BE25", division.get("DivisionCode").asText()); + assertNotNull(division.get("Children")); + final ArrayNode children = (ArrayNode) division.get("Children"); + assertEquals(1, children.size()); + final ObjectNode firstChild = (ObjectNode) children.get(0); + assertEquals("BE252", firstChild.get("DivisionCode").asText()); + } + + @Test + public void testFilterExpandWithFilter() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=DivisionCode eq 'BE25' and CodeID eq 'NUTS2'&$expand=Children($filter=DivisionCode eq 'BE252')"); + + helper.assertStatus(200); + + final JsonNode value = helper.getValue().get("value"); + assertNotNull(value.get(0)); + final ObjectNode division = (ObjectNode) value.get(0); + + assertEquals("BE25", division.get("DivisionCode").asText()); + ArrayNode children = (ArrayNode) division.get("Children"); + assertEquals(1, children.size()); + final ObjectNode firstChild = (ObjectNode) children.get(0); + assertEquals("BE252", firstChild.get("DivisionCode").asText()); + } + + @Test + public void testFilterExpandWithFilterOnParentDescription() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=ID&$filter=LocationName eq 'Deutschland'&$expand=Roles&$orderby=ID asc"); + + helper.assertStatus(200); + + final JsonNode value = helper.getValue().get("value"); + assertNotNull(value.get(0)); + final ArrayNode roles = (ArrayNode) value.get(0).get("Roles"); + + assertEquals(1, roles.size()); + } + + @Test + public void testExpandCompleteEntitySet() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$expand=Roles&orderby=ID"); + + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + final ObjectNode org = (ObjectNode) orgs.get(0); + assertEquals("1", org.get("ID").asText()); + assertNotNull(org.get("Roles")); + final ArrayNode roles = (ArrayNode) org.get("Roles"); + assertEquals(1, roles.size()); + final ObjectNode firstRole = (ObjectNode) roles.get(0); + assertEquals("A", firstRole.get("RoleCategory").asText()); + } + + @Test + public void testExpandTwoNavigationPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=Parent,Children"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandAllNavigationPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandAllNavigationPathOfPath() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE32',CodeID='NUTS2',CodePublisher='Eurostat')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final ArrayNode children = (ArrayNode) org.get("Children"); + assertEquals(7, children.size()); + } + + @Test + public void testExpandLevel1() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=1)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Parent")); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + assertNotNull(parent.get("DivisionCode")); + final TextNode divCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE258", divCode.asText()); + } + + @Test + public void testExpandLevel2() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='38025',CodeID='LAU2',CodePublisher='Eurostat')?$expand=Parent($levels=2)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertFalse(org.get("Parent") instanceof NullNode); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + final TextNode parentDivCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE258", parentDivCode.asText()); + + assertFalse(parent.get("Parent") instanceof NullNode); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent.get("DivisionCode")); + final TextNode grandparentDivCode = (TextNode) grandParent.get("DivisionCode"); + assertEquals("BE25", grandparentDivCode.asText()); + } + + @Test + public void testExpandLevelMax() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE241',CodeID='NUTS3',CodePublisher='Eurostat')?$expand=Parent($levels=max)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertFalse(org.get("Parent") instanceof NullNode); + final ObjectNode parent = (ObjectNode) org.get("Parent"); + final TextNode parentDivCode = (TextNode) parent.get("DivisionCode"); + assertEquals("BE24", parentDivCode.asText()); + + assertFalse(parent.get("Parent") instanceof NullNode); + final ObjectNode grandParent = (ObjectNode) parent.get("Parent"); + assertNotNull(grandParent.get("DivisionCode")); + final TextNode grandparentDivCode = (TextNode) grandParent.get("DivisionCode"); + assertEquals("BE2", grandparentDivCode.asText()); + } + + @Test + public void testExpandAllNavigationPathWithComplex() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')?$expand=*"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles")); + + } + + @Test + public void testExpandCompleteEntitySet2() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "AdministrativeDivisions?$expand=Parent"); + + helper.assertStatus(200); + } + + @Test + public void testExpandViaJoinTable() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('2')?$select=Name1&$expand=SupportEngineers($select=FirstName,LastName)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("SupportEngineers")); + + } + + @Test + public void testExpandViaJoinTable2Levels() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('1')?$select=Name1&$expand=SupportEngineers($select=FirstName,LastName;$expand=SupportedOrganizations)"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("SupportEngineers")); + ArrayNode supportOrgs = (ArrayNode) org.get("SupportEngineers").get(0).get("SupportedOrganizations"); + assertNotNull(supportOrgs); + assertEquals(1, supportOrgs.size()); + + supportOrgs = (ArrayNode) org.get("SupportEngineers").get(1).get("SupportedOrganizations"); + assertNotNull(supportOrgs); + assertEquals(2, supportOrgs.size()); + } + + @Test + public void testExpandViaJoinTable1LevelNoSubType() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons?$select=LastName&$expand=Teams"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org); + } + + @Test + public void testExpandViaJoinTable1LevelNoMapped() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(1)?$expand=OneToMany"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToMany")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToMany"); + assertEquals(2, oneToMany.size()); + } + + @Test + public void testExpandViaJoinTable1LevelNoMappedHidden() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(2)?$expand=OneToManyHidden"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToManyHidden")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToManyHidden"); + assertEquals(2, oneToMany.size()); + } + + @Test + public void testExpandViaJoinTableComplex() throws IOException, ODataException { + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "JoinSources(1)/Complex?$expand=OneToManyComplex"); + helper.assertStatus(200); + + final ObjectNode org = helper.getValue(); + assertNotNull(org.get("OneToManyComplex")); + ArrayNode oneToMany = (ArrayNode) org.get("OneToManyComplex"); + assertEquals(2, oneToMany.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java new file mode 100644 index 0000000000..c8fc50d198 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryBuildSelectionPathList.java @@ -0,0 +1,233 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.UriInfoDouble; + +public class TestJPAQueryBuildSelectionPathList extends TestBase { + + private JPAAbstractJoinQuery cut; + private JPAODataSessionContextAccess context; + private UriInfo uriInfo; + + @BeforeEach + public void setup() throws ODataException { + buildUriInfo("BusinessPartners", "BusinessPartner"); + + helper = new TestHelper(emf, PUNIT_NAME); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + createHeaders(); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages), ds, + null); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + } + + private List buildUriInfo(final String esName, final String etName) { + uriInfo = mock(UriInfo.class); + final EdmEntitySet odataEs = mock(EdmEntitySet.class); + final EdmType odataType = mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = mock(UriResourceEntitySet.class); + when(uriInfo.getUriResourceParts()).thenReturn(resources); + when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + when(esResource.getEntitySet()).thenReturn(odataEs); + when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + when(esResource.getType()).thenReturn(odataType); + when(odataEs.getName()).thenReturn(esName); + when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + when(odataType.getName()).thenReturn(etName); + resources.add(esResource); + return resources; + } + + @Test + public void checkSelectAllAsNoSelectionGiven() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(23, act.size()); + } + + @Test + public void checkSelectAllAsStarGiven() throws ODataApplicationException { + + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("*"))); + assertEquals(23, act.size()); + } + + @Test + public void checkSelectPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Country"))); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectAllFromComplexWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address"))); + assertEquals(10, act.size()); + } + + @Test + public void checkSelectKeyNoDuplicates() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("ID"))); + assertEquals(1, act.size()); + } + + @Test + public void checkSelectAllFromNavigationComplexPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble( + "Address/CountryName"))); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectTwoPrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Country,ETag"))); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectAllFromComplexAndOnePrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble("Address,ETag"))); + assertEquals(11, act.size()); + } + + @Test + public void checkSelectAllFromNavgateComplexPrimitiveAndOnePrimitiveWithKey() throws ODataApplicationException { + final List act = cut.buildSelectionPathList(new UriInfoDouble(new SelectOptionDouble( + "Address/CountryName,Country"))); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectNavigationCompex() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty complexResource = mock(UriResourceComplexProperty.class); + final EdmProperty property = mock(EdmProperty.class); + when(complexResource.getProperty()).thenReturn(property); + when(property.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(complexResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(5, act.size()); + } + + @Test + public void checkSelectNavigationCompexComplex() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class); + final EdmProperty adminInfoProperty = mock(EdmProperty.class); + when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty); + when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(adminInfoResource); + + final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class); + final EdmProperty createdProperty = mock(EdmProperty.class); + when(createdResource.getProperty()).thenReturn(createdProperty); + when(createdProperty.getName()).thenReturn("Created"); + resourcePath.add(createdResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(3, act.size()); + } + + @Test + public void checkSelectNavigationCompexComplexProperty() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty adminInfoResource = mock(UriResourceComplexProperty.class); + final EdmProperty adminInfoProperty = mock(EdmProperty.class); + when(adminInfoResource.getProperty()).thenReturn(adminInfoProperty); + when(adminInfoProperty.getName()).thenReturn("AdministrativeInformation"); + resourcePath.add(adminInfoResource); + + final UriResourceComplexProperty createdResource = mock(UriResourceComplexProperty.class); + final EdmProperty createdProperty = mock(EdmProperty.class); + when(createdResource.getProperty()).thenReturn(createdProperty); + when(createdProperty.getName()).thenReturn("Created"); + resourcePath.add(createdResource); + + final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty byProperty = mock(EdmProperty.class); + when(byResource.getProperty()).thenReturn(byProperty); + when(byProperty.getName()).thenReturn("By"); + resourcePath.add(byResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectNavigationPropertyValue() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + + final UriResourcePrimitiveProperty byResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty byProperty = mock(EdmProperty.class); + when(byResource.getProperty()).thenReturn(byProperty); + when(byProperty.getName()).thenReturn("Country"); + resourcePath.add(byResource); + + final UriResourceValue valueResource = mock(UriResourceValue.class); + when(valueResource.getSegmentValue()).thenReturn(Util.VALUE_RESOURCE.toLowerCase()); + resourcePath.add(valueResource); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } + + @Test + public void checkSelectNavigationCompexWithSelectPrimitive() throws ODataException { + List resourcePath = buildUriInfo("BusinessPartners", "BusinessPartner"); + final UriResourceComplexProperty addressResource = mock(UriResourceComplexProperty.class); + final EdmProperty addressProperty = mock(EdmProperty.class); + when(addressResource.getProperty()).thenReturn(addressProperty); + when(addressProperty.getName()).thenReturn("Address"); + resourcePath.add(addressResource); + + SelectOption selOptions = new SelectOptionDouble("CountryName"); + + when(uriInfo.getSelectOption()).thenReturn(selOptions); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + final List act = cut.buildSelectionPathList(uriInfo); + assertEquals(2, act.size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java new file mode 100644 index 0000000000..9362704ff0 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryCollection.java @@ -0,0 +1,151 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.NullNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryCollection extends TestBase { + + @Test + public void testSelectPropertyAndCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$select=ID,Comment&orderby=ID"); + helper.assertStatus(200); + + final ArrayNode orgs = helper.getValues(); + ObjectNode org = (ObjectNode) orgs.get(0); + assertNotNull(org.get("ID")); + ArrayNode comment = (ArrayNode) org.get("Comment"); + assertEquals(2, comment.size()); + } + + // @Ignore // See https://issues.apache.org/jira/browse/OLINGO-1231 + @Test + public void testSelectPropertyOfCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')/InhouseAddress?$select=Building"); + helper.assertStatus(200); + + final ArrayNode buildings = helper.getValues(); + assertEquals(2, buildings.size()); + ObjectNode building = (ObjectNode) buildings.get(0); + TextNode number = (TextNode) building.get("Building"); + assertNotNull(number); + } + + @Test + public void testSelectAllWithComplexCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons('99')?$select=*"); + helper.assertStatus(200); + + final ObjectNode person = helper.getValue(); + ArrayNode comment = (ArrayNode) person.get("InhouseAddress"); + assertEquals(2, comment.size()); + } + + @Test + public void testSelectAllWithPrimitiveCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('1')?$select=*"); + helper.assertStatus(200); + + final ObjectNode person = helper.getValue(); + ArrayNode comment = (ArrayNode) person.get("Comment"); + assertEquals(2, comment.size()); + } + + @Test + public void testSelectWithNestedComplexCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('504')?$select=Nested"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ArrayNode nested = (ArrayNode) collection.get("Nested"); + assertEquals(1, nested.size()); + ObjectNode n = (ObjectNode) nested.get(0); + assertEquals(1L, n.get("Number").asLong()); + assertFalse(n.get("Inner") instanceof NullNode); + assertEquals(6L, n.get("Inner").get("Figure3").asLong()); + } + + @Test + public void testSelectComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('502')?$select=Complex"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(32L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(2, complex.get("Address").size()); + assertEquals("DEV", complex.get("Address").get(0).get("TaskID").asText()); + } + + @Test + public void testSelectComplexContainingTwoCollections() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Collections('501')?$select=Complex"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(-1L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(1, complex.get("Address").size()); + assertEquals("MAIN", complex.get("Address").get(0).get("TaskID").asText()); + assertFalse(complex.get("Comment") instanceof NullNode); + assertEquals(1, complex.get("Comment").size()); + assertEquals("This is another test", complex.get("Comment").get(0).asText()); + } + + @Test + public void testSelectAllWithComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Collections('502')"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("Complex"); + assertEquals(32L, complex.get("Number").asLong()); + assertFalse(complex.get("Address") instanceof NullNode); + assertEquals(2, complex.get("Address").size()); + assertEquals("DEV", complex.get("Address").get(0).get("TaskID").asText()); + } + + @Test + public void testSelectAllDeepComplexContainingCollection() throws IOException, ODataException { + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, "CollectionDeeps('501')"); + helper.assertStatus(200); + + final ObjectNode collection = helper.getValue(); + ObjectNode complex = (ObjectNode) collection.get("FirstLevel"); + assertEquals(1, complex.get("LevelID").asInt()); + assertFalse(complex.get("SecondLevel") instanceof NullNode); + ObjectNode second = (ObjectNode) complex.get("SecondLevel"); + ArrayNode address = (ArrayNode) second.get("Address"); + assertEquals(32, address.get(0).get("RoomNumber").asInt()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java new file mode 100644 index 0000000000..3e614854e7 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryFromClause.java @@ -0,0 +1,162 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.criteria.From; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Root; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; + +public class TestJPAQueryFromClause extends TestBase { + private JPAAbstractJoinQuery cut; + private JPAEntityType jpaEntityType; + + @BeforeEach + public void setup() throws ODataException { + final UriInfo uriInfo = Mockito.mock(UriInfo.class); + final EdmEntitySet odataEs = Mockito.mock(EdmEntitySet.class); + final EdmType odataType = Mockito.mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = Mockito.mock(UriResourceEntitySet.class); + Mockito.when(uriInfo.getUriResourceParts()).thenReturn(resources); + Mockito.when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + Mockito.when(esResource.getEntitySet()).thenReturn(odataEs); + Mockito.when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + Mockito.when(esResource.getType()).thenReturn(odataType); + Mockito.when(odataEs.getName()).thenReturn("Organizations"); + Mockito.when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + Mockito.when(odataType.getName()).thenReturn("Organization"); + resources.add(esResource); + + helper = new TestHelper(emf, PUNIT_NAME); + jpaEntityType = helper.getJPAEntityType("Organizations"); + JPAODataSessionContextAccess context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, + TestBase.enumPackages), ds, null); + createHeaders(); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + } + + @Test + public void checkFromListContainsRoot() throws ODataApplicationException { + + Map> act = cut.createFromClause(new ArrayList(1), + new ArrayList(), cut.cq); + assertNotNull(act.get(jpaEntityType.getExternalFQN().getFullQualifiedNameAsString())); + } + + @Test + public void checkFromListOrderByContainsOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + final JPAAssociationPath exp = buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + assertNotNull(act.get(exp.getAlias())); + } + + @Test + public void checkFromListOrderByOuterJoinOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + + @SuppressWarnings("unchecked") + Root root = (Root) act.get(jpaEntityType.getExternalFQN() + .getFullQualifiedNameAsString()); + Set> joins = root.getJoins(); + assertEquals(1, joins.size()); + + for (Join join : joins) { + assertEquals(JoinType.LEFT, join.getJoinType()); + } + } + + @Test + public void checkFromListOrderByOuterJoinOnConditionOne() throws ODataJPAModelException, ODataApplicationException { + final List orderBy = new ArrayList<>(); + buildRoleAssociationPath(orderBy); + + Map> act = cut.createFromClause(orderBy, new ArrayList(), cut.cq); + + @SuppressWarnings("unchecked") + Root root = (Root) act.get(jpaEntityType.getExternalFQN() + .getFullQualifiedNameAsString()); + Set> joins = root.getJoins(); + assertEquals(1, joins.size()); + + for (Join join : joins) { + assertNull(join.getOn()); + } + } + + @Test + public void checkFromListDescriptionAssozationAllFields() throws ODataApplicationException, ODataJPAModelException { + List orderBy = new ArrayList<>(); + List descriptionPathList = new ArrayList<>(); + JPAEntityType entity = helper.getJPAEntityType("Organizations"); + descriptionPathList.add(entity.getPath("Address/CountryName")); + + JPAAttribute attri = helper.getJPAAttribute("Organizations", "address"); + JPAAttribute exp = attri.getStructuredType().getAttribute("countryName"); + + Map> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq); + assertEquals(2, act.size()); + assertNotNull(act.get(exp.getInternalName())); + } + + @Test + public void checkFromListDescriptionAssozationAllFields2() throws ODataApplicationException, ODataJPAModelException { + List orderBy = new ArrayList<>(); + List descriptionPathList = new ArrayList<>(); + JPAEntityType entity = helper.getJPAEntityType("Organizations"); + descriptionPathList.add(entity.getPath("Address/RegionName")); + + JPAAttribute attri = helper.getJPAAttribute("Organizations", "address"); + JPAAttribute exp = attri.getStructuredType().getAttribute("regionName"); + + Map> act = cut.createFromClause(orderBy, descriptionPathList, cut.cq); + assertEquals(2, act.size()); + assertNotNull(act.get(exp.getInternalName())); + } + + private JPAAssociationPath buildRoleAssociationPath(final List orderBy) + throws ODataJPAModelException { + JPAAssociationPath exp = helper.getJPAAssociationPath("Organizations", "Roles"); + orderBy.add(exp); + return exp; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java new file mode 100644 index 0000000000..52677576ae --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryJSONAnnotations.java @@ -0,0 +1,81 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryJSONAnnotations extends TestBase { + + @Test + public void testEntityWithMetadataFullContainNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.navigationLink")); + assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText()); + } + + @Test + public void testEntityWithMetadataMinimalWithoutNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=minimal"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNull(org.get("Roles@odata.navigationLink")); + } + + @Test + public void testEntityWithMetadataNoneWithoutNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=none"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNull(org.get("Roles@odata.navigationLink")); + } + + @Test + public void testEntityExpandWithMetadataFullContainNavigationLink() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$expand=Roles&$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("Roles@odata.navigationLink")); + assertEquals("Organizations('3')/Roles", org.get("Roles@odata.navigationLink").asText()); + } + + @Disabled // See https://issues.apache.org/jira/browse/OLINGO-1248 + @Test + public void testEntityWithMetadataFullContainNavigationLinkOfComplex() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')?$format=application/json;odata.metadata=full"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + ObjectNode admin = (ObjectNode) org.get("AdministrativeInformation"); + ObjectNode created = (ObjectNode) admin.get("Created"); + assertNotNull(created.get("User@odata.navigationLink")); + assertEquals("Organizations('3')/AdministrativeInformation/Created/User", created.get("User@odata.navigationLink") + .asText()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java new file mode 100644 index 0000000000..c361e9eb0b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigation.java @@ -0,0 +1,290 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryNavigation extends TestBase { + + @Test + public void testNavigationOneHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Roles"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + } + + @Test + public void testNoNavigationOneEntity() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Third Org.", org.get("Name1").asText()); + } + + @Test + public void testNoNavigationOneEntityCollection() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + ArrayNode comment = (ArrayNode) org.get("Comment"); + assertEquals(2, comment.size()); + } + + @Test + public void testNoNavigationOneEntityNoContent() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1000')"); + helper.assertStatus(404); + } + + @Test + public void testNavigationToComplexValue() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created"); + helper.assertStatus(200); + + ObjectNode created = helper.getValue(); + assertEquals("99", created.get("By").asText()); + } + + @Test + public void testNavigationOneHopAndOrderBy() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Roles?$orderby=RoleCategory desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("C", orgs.get(0).get("RoleCategory").asText()); + assertEquals("A", orgs.get(2).get("RoleCategory").asText()); + } + + @Test + public void testNavigationOneHopReverse() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='2',RoleCategory='A')/BusinessPartner"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("2", org.get("ID").asText()); + } + + @Test + public void testNavigationViaComplexTypeToComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/AdministrativeInformation"); + helper.assertStatus(200); + + ObjectNode admin = helper.getValue(); + ObjectNode created = (ObjectNode) admin.get("Created"); + assertEquals("99", created.get("By").asText()); + } + + @Test + public void testNavigationViaComplexType() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("99", org.get("ID").asText()); + } + + @Test + public void testNavigationViaComplexTypeTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/Address/AdministrativeDivision"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("3166-1", org.get("ParentCodeID").asText()); + } + + @Test + public void testNavigationSelfToOneOneHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("NUTS2", org.get("CodeID").asText()); + assertEquals("BE35", org.get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToOneTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE352',CodeID='NUTS3',CodePublisher='Eurostat')/Parent/Parent"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("NUTS1", org.get("CodeID").asText()); + assertEquals("BE3", org.get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToManyOneHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(5, orgs.size()); + assertEquals("NUTS2", orgs.get(0).get("CodeID").asText()); + assertEquals("BE25", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToManyTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions(DivisionCode='BE2',CodeID='NUTS1',CodePublisher='Eurostat')/Children(DivisionCode='BE25',CodeID='NUTS2',CodePublisher='Eurostat')/Children?$orderby=DivisionCode desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(8, orgs.size()); + assertEquals("NUTS3", orgs.get(0).get("CodeID").asText()); + assertEquals("BE258", orgs.get(0).get("DivisionCode").asText()); + } + + @Test + public void testNavigationSelfToOneThreeHopsNoResult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address/AdministrativeDivision/Parent/Parent"); + helper.assertStatus(204); + } + + @Test + public void testNavigationSelfToManyOneHopsNoResult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Address/AdministrativeDivision/Children"); + helper.assertStatus(200); + } + + @Test + public void testNavigationJoinTableDefined() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('97')/SupportedOrganizations"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testNavigationJoinTableDefinedSecondHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='98',RoleCategory='X')/BusinessPartner/com.sap.olingo.jpa.Person/SupportedOrganizations"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(1, orgs.size()); + } + + @Test + public void testNavigationJoinTableMappedBy() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/SupportEngineers"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(2, orgs.size()); + } + + @Test + public void testNavigationComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/AdministrativeInformation"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + + assertNotNull(org.get("Created")); + assertNotNull(org.get("Updated")); + } + + @Test + public void testNavigationPrimitiveCollectionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('1')/Comment"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals( + "This is another test")); + assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals( + "This is another test")); + } + + @Test + public void testNavigationComplexCollectionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/InhouseAddress"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + } + + @Test + public void testNavigationComplexCollectionPropertyEmptyReult() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('98')/InhouseAddress"); + helper.assertStatus(200); + } + + @Test + public void testNavigationPrimitiveCollectionPropertyTwoHops() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerRoles(BusinessPartnerID='1',RoleCategory='A')/Organization/Comment"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertNotNull(org.get("value")); + assertFalse(org.get("value").isNull()); + ArrayNode values = (ArrayNode) org.get("value"); + assertEquals(2, values.size()); + assertTrue(values.get(0).asText().equals("This is just a test") || values.get(0).asText().equals( + "This is another test")); + assertTrue(values.get(1).asText().equals("This is just a test") || values.get(1).asText().equals( + "This is another test")); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java new file mode 100644 index 0000000000..c24459d382 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryNavigationCount.java @@ -0,0 +1,52 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryNavigationCount extends TestBase { + + @Test + public void testEntitySetCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations/$count"); + assertEquals(200, helper.getStatus()); + + assertEquals("10", helper.getRawResult()); + } + + @Test + public void testEntityNavigateCount() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Roles/$count"); + assertEquals(200, helper.getStatus()); + + assertEquals("3", helper.getRawResult()); + } + + @Test + public void testEntitySetCountWithFilterOn() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations/$count?$filter=Address/HouseNumber gt '30'"); + + assertEquals(200, helper.getStatus()); + assertEquals("7", helper.getRawResult()); + } + + @Test + public void testEntitySetCountWithFilterOnDescription() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Persons/$count?$filter=LocationName eq 'Deutschland'"); + + assertEquals(200, helper.getStatus()); + assertEquals("2", helper.getRawResult()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java new file mode 100644 index 0000000000..8b1fdf2c8f --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryOrderByClause.java @@ -0,0 +1,174 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQueryOrderByClause extends TestBase { + + @Test + public void testOrderByOneProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Name1"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("Eighth Org.", orgs.get(0).get("Name1").asText()); + assertEquals("Third Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderByOneComplexPropertyAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Address/Region"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-CA", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-UT", orgs.get(9).get("Address").get("Region").asText()); + } + + @Test + public void testOrderByOneComplexPropertyDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Address/Region desc"); + if (helper.getStatus() != 200) + System.out.println(helper.getRawResult()); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + } + + @Test + public void testOrderByTwoPropertiesDescAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Address/Region desc,Name1 asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("Third Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderByTwoPropertiesDescDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Address/Region desc,Name1 desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("US-UT", orgs.get(0).get("Address").get("Region").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("First Org.", orgs.get(9).get("Name1").asText()); + } + + @Test + public void testOrderBy$CountDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=Roles/$count desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(0).get("ID").asText()); + assertEquals("2", orgs.get(1).get("ID").asText()); + } + + @Test + public void testOrderBy$CountAndSelectAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$select=ID,Name1,Name2,Address/CountryName&$orderby=Roles/$count asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(9).get("ID").asText()); + assertEquals("2", orgs.get(8).get("ID").asText()); + } + + @Test + public void testCollcetionOrderBy$CountAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count asc"); + + helper.assertStatus(200); + ArrayNode deeps = helper.getValues(); + assertEquals("501", deeps.get(0).get("ID").asText()); + assertEquals("502", deeps.get(1).get("ID").asText()); + } + + @Test + public void testCollcetionOrderBy$CountDesc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "CollectionDeeps?$orderby=FirstLevel/SecondLevel/Comment/$count desc"); + + helper.assertStatus(200); + ArrayNode deeps = helper.getValues(); + assertEquals("502", deeps.get(0).get("ID").asText()); + assertEquals("501", deeps.get(1).get("ID").asText()); + } + + @Test + public void testOrderBy$CountAsc() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Roles/$count asc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(9).get("ID").asText()); + assertEquals("2", orgs.get(8).get("ID").asText()); + } + + @Test + public void testOrderBy$CountDescComplexPropertyAcs() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations?$orderby=Roles/$count desc,Address/Region desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals("3", orgs.get(0).get("ID").asText()); + assertEquals("2", orgs.get(1).get("ID").asText()); + assertEquals("US-CA", orgs.get(9).get("Address").get("Region").asText()); + assertEquals("6", orgs.get(9).get("ID").asText()); + } + + @Test + public void testOrderByAndFilter() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "AdministrativeDivisions?$filter=CodeID eq 'NUTS' or CodeID eq '3166-1'&$orderby=CountryCode desc"); + + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(4, orgs.size()); + assertEquals("USA", orgs.get(0).get("CountryCode").asText()); + } + + @Test + public void testOrderByNavigationOneHop() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/Roles?$orderby=RoleCategory desc"); + helper.assertStatus(200); + + ArrayNode orgs = helper.getValues(); + assertEquals(3, orgs.size()); + assertEquals("C", orgs.get(0).get("RoleCategory").asText()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java new file mode 100644 index 0000000000..7970eb12ca --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectByPath.java @@ -0,0 +1,176 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; + +import org.apache.olingo.commons.api.ex.ODataException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.testmodel.ImageLoader; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAQuerySelectByPath extends TestBase { + + @Test + public void testNavigationToOwnPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/Name1"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Third Org.", org.get("value").asText()); + } + + @Test + public void testNavigationToOwnEmptyPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/BirthDay"); + helper.assertStatus(204); + } + + @Test + public void testNavigationToOwnPrimitivePropertyEntityDoesNotExistEntity() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('9999')/BirthDay"); + helper.assertStatus(404); + } + + @Test + public void testNavigationToOwnPrimitiveDescriptionProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('3')/LocationName"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Vereinigte Staaten von Amerika", org.get("value").asText()); + } + + @Test + public void testNavigationToComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("USA", org.get("Country").asText()); + } + + @Test + public void testNavigationToNotExistingComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('97')/CommunicationData"); + helper.assertStatus(204); + } + + @Test + public void testNavigationToNestedComplexProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/AdministrativeInformation/Created"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("98", org.get("By").asText()); + } + + @Test + public void testNavigationViaComplexAndNaviPropertyToPrimitive() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('3')/AdministrativeInformation/Created/User/FirstName"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("Max", org.get("value").asText()); + } + + @Test + public void testNavigationToComplexPropertySelect() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/Address?$select=Country,Region"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals(3, org.size()); // Node "@odata.context" is also counted + assertEquals("USA", org.get("Country").asText()); + assertEquals("US-UT", org.get("Region").asText()); + } + + @Test + public void testNavigationToComplexPropertyExpand() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + assertEquals("USA", org.get("Country").asText()); + } + + @Test + public void testNavigationToComplexPrimitiveProperty() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations('4')/Address/Region"); + helper.assertStatus(200); + + ObjectNode org = helper.getValue(); + System.out.println(org); + assertEquals("US-UT", org.get("value").asText()); + assertTrue(org.get("@odata.context").asText().endsWith("$metadata#Organizations/Address/Region")); + } + + @Disabled // TODO check image load + @Test + public void testNavigationToStreamValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "PersonImages('99')/$value"); + helper.assertStatus(200); + + byte[] act = helper.getBinaryResult(); + assertEquals(93316, act.length, 0); + } + + @Disabled // TODO check image load + @Test + public void testNavigationToStreamValueVia() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Persons('99')/Image/$value"); + helper.assertStatus(200); + + byte[] act = helper.getBinaryResult(); + assertEquals(93316, act.length, 0); + } + + @Disabled // TODO check image load + @Test + public void testNavigationToComplexAttributeValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/AdministrativeInformation/Created/By/$value"); + helper.assertStatus(200); + + String act = helper.getRawResult(); + assertEquals("98", act); + } + + @Disabled // TODO check image load + @Test + public void testNavigationToPrimitiveAttributeValue() throws IOException, ODataException { + new ImageLoader().loadPerson(emf.createEntityManager(), "OlingoOrangeTM.png", "99"); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "Organizations('4')/ID/$value"); + helper.assertStatus(200); + + String act = helper.getRawResult(); + assertEquals("4", act); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java new file mode 100644 index 0000000000..d1664f76cb --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQuerySelectClause.java @@ -0,0 +1,465 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.criteria.Selection; + +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceValue; +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.testmodel.TestDataConstants; +import com.sap.olingo.jpa.processor.core.util.EdmEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.EdmPropertyDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandItemDouble; +import com.sap.olingo.jpa.processor.core.util.ExpandOptionDouble; +import com.sap.olingo.jpa.processor.core.util.SelectOptionDouble; +import com.sap.olingo.jpa.processor.core.util.TestQueryBase; +import com.sap.olingo.jpa.processor.core.util.UriInfoDouble; +import com.sap.olingo.jpa.processor.core.util.UriResourceNavigationDouble; +import com.sap.olingo.jpa.processor.core.util.UriResourcePropertyDouble; + +public class TestJPAQuerySelectClause extends TestQueryBase { + + @Test + public void checkSelectAll() throws ODataApplicationException, ODataJPAModelException { + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("*"))), root); + assertEquals(jpaEntityType.getPathList().size(), selectClause.size()); + + } + + @Test + public void checkSelectAllWithSelectionNull() throws ODataApplicationException, ODataJPAModelException { + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(new UriInfoDouble( + null)), root); + + assertEquals(jpaEntityType.getPathList().size(), selectClause.size()); + } + + @Test + public void checkSelectExpandViaIgnoredProperties() throws ODataApplicationException, ODataJPAModelException { + // Organizations('3')/Address?$expand=AdministrativeDivision + fillJoinTable(root); + List expItems = new ArrayList<>(); + EdmEntityType startEntity = new EdmEntityTypeDouble(nameBuilder, "Organization"); + EdmEntityType targetEntity = new EdmEntityTypeDouble(nameBuilder, "AdministrativeDivision"); + + ExpandOption expOps = new ExpandOptionDouble("AdministrativeDivision", expItems); + expItems.add(new ExpandItemDouble(targetEntity)); + List startResources = new ArrayList<>(); + UriInfoDouble uriInfo = new UriInfoDouble(null); + uriInfo.setExpandOpts(expOps); + uriInfo.setUriResources(startResources); + + startResources.add(new UriResourceNavigationDouble(startEntity)); + startResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("Address"))); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + + assertContains(selectClause, "Address/RegionCodeID"); + } + + @Test + public void checkSelectOnePropertyCreatedAt() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("CreationDateTime"))), root); + assertEquals(2, selectClause.size()); + assertContains(selectClause, "CreationDateTime"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectOnePropertyID() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("ID"))), root); + assertEquals(1, selectClause.size()); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectOnePropertyPartKey() throws ODataException { + jpaEntityType = helper.getJPAEntityType("AdministrativeDivisionDescriptions"); + buildUriInfo("AdministrativeDivisionDescriptions", "AdministrativeDivisionDescription"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble((new SelectOptionDouble("CodePublisher")))), root); + assertEquals(4, selectClause.size()); + assertContains(selectClause, "CodePublisher"); + assertContains(selectClause, "CodeID"); + assertContains(selectClause, "DivisionCode"); + assertContains(selectClause, "Language"); + } + + @Test + public void checkSelectPropertyTypeCreatedAt() throws ODataApplicationException, ODataJPAModelException { + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Type,CreationDateTime"))), root); + + assertEquals(3, selectClause.size()); + assertContains(selectClause, "CreationDateTime"); + assertContains(selectClause, "Type"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectSupertypePropertyTypeName2() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + buildUriInfo("Organizations", "Organization"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Type,Name2"))), root); + assertContains(selectClause, "Name2"); + assertContains(selectClause, "Type"); + assertContains(selectClause, "ID"); + assertEquals(3, selectClause.size()); + } + + @Test + public void checkSelectCompleteComplexType() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address"))), root); + assertEquals(TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + 1, selectClause.size()); + } + + @Test + public void checkSelectCompleteNestedComplexTypeLowLevel() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation/Created"))), root); + assertEquals(3, selectClause.size()); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "AdministrativeInformation/Created/At"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectCompleteNestedComplexTypeHighLevel() throws ODataException { + // Organizations$select=Address + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("AdministrativeInformation"))), root); + assertEquals(5, selectClause.size()); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "AdministrativeInformation/Created/At"); + assertContains(selectClause, "AdministrativeInformation/Updated/By"); + assertContains(selectClause, "AdministrativeInformation/Updated/At"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectElementOfComplexType() throws ODataException { + // Organizations$select=Address/Country + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables.put(jpaEntityType.getInternalName(), root); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + // SELECT c.address.geocode FROM Company c WHERE c.name = 'Random House' + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address/Country"))), root); + assertContains(selectClause, "Address/Country"); + assertContains(selectClause, "ID"); + assertEquals(2, selectClause.size()); + } + + @Test + public void checkSelectTextJoinSingleAttribute() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address/CountryName"))), root); + assertContains(selectClause, "Address/CountryName"); + assertContains(selectClause, "ID"); + assertEquals(2, selectClause.size()); + } + + @Test + public void checkSelectTextJoinCompextType() throws ODataException { + jpaEntityType = helper.getJPAEntityType("Organizations"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + joinTables.put(jpaEntityType.getInternalName(), root); + fillJoinTable(root); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList( + new UriInfoDouble(new SelectOptionDouble("Address"))), root); + assertEquals(TestDataConstants.NO_ATTRIBUTES_POSTAL_ADDRESS + 1, selectClause.size()); + assertContains(selectClause, "Address/CountryName"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectStreamValueStatic() throws ODataException { + jpaEntityType = helper.getJPAEntityType("PersonImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("PersonImages", "PersonImage"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address")); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "Image"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectStreamValueDynamic() throws ODataException { + jpaEntityType = helper.getJPAEntityType("OrganizationImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("OrganizationImages", "OrganizationImage"); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(new SelectOptionDouble("Address")); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "Image"); + assertContains(selectClause, "MimeType"); + assertContains(selectClause, "ID"); + } + + @Test + public void checkSelectPropertyValue() throws ODataException { + jpaEntityType = helper.getJPAEntityType("PersonImages"); + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + buildUriInfo("PersonImages", "PersonImage"); + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + UriInfoDouble uriInfo = new UriInfoDouble(null); + List uriResources = new ArrayList<>(); + uriInfo.setUriResources(uriResources); + // PersonImages('99')/AdministrativeInformation/Created/By/$value + uriResources.add(new UriResourceEntitySetDouble()); + uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("AdministrativeInformation"))); + uriResources.add(new UriResourceComplexPropertyDouble(new EdmPropertyDouble("Created"))); + uriResources.add(new UriResourcePropertyDouble(new EdmPropertyDouble("By"))); + uriResources.add(new UriResourceValueDouble()); + + List> selectClause = cut.createSelectClause(joinTables, cut.buildSelectionPathList(uriInfo), root); + assertNotNull(selectClause); + assertContains(selectClause, "AdministrativeInformation/Created/By"); + assertContains(selectClause, "ID"); + } + + private void assertContains(List> selectClause, String alias) { + for (Selection selection : selectClause) { + if (selection.getAlias().equals(alias)) + return; + } + fail(alias + " not found"); + } + + private class UriResourceValueDouble implements UriResourceValue { + + @Override + public UriResourceKind getKind() { + return UriResourceKind.value; + } + + @Override + public String getSegmentValue() { + return null; + } + } + + private class UriResourceComplexPropertyDouble implements UriResourceComplexProperty { + private final EdmProperty property; + + public UriResourceComplexPropertyDouble(EdmProperty property) { + super(); + this.property = property; + } + + @Override + public EdmProperty getProperty() { + return property; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexType() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexTypeFilter() { + fail(); + return null; + } + + } + + private class UriResourceEntitySetDouble implements UriResourceEntitySet { + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmEntitySet getEntitySet() { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityType() { + fail(); + return null; + } + + @Override + public List getKeyPredicates() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnCollection() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnEntry() { + fail(); + return null; + } + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java new file mode 100644 index 0000000000..3e05b0b791 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAQueryWithProtection.java @@ -0,0 +1,374 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.sql.Date; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Predicate.BooleanOperator; + +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.eclipse.persistence.internal.jpa.querydef.CompoundExpressionImpl; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAElement; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAServiceDocument; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.api.JPAClaimsPair; +import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.JPAEntityTypeDouble; +import com.sap.olingo.jpa.processor.core.util.TestQueryBase; + +public class TestJPAQueryWithProtection extends TestQueryBase { + private JPAODataSessionContextAccess contextSpy; + private JPAServiceDocument sdSpy; + private EdmType odataType; + private List attributes; + private Set claimNames; + private List pathList; + private JPAEntityType etSpy; + private List protections; + + @Override + @BeforeEach + public void setup() throws ODataException { + super.setup(); + contextSpy = Mockito.spy(context); + JPAEdmProvider providerSpy = Mockito.spy(context.getEdmProvider()); + sdSpy = Mockito.spy(context.getEdmProvider().getServiceDocument()); + when(contextSpy.getEdmProvider()).thenReturn(providerSpy); + when(providerSpy.getServiceDocument()).thenReturn(sdSpy); + + } + + @Test + public void testRestrictOnePropertyOneValue() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(3, bupa.size()); + } + + @Test + public void testRestrictOnePropertyTwoValues() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(16, bupa.size()); + } + + @Test + public void testRestrictOnePropertyNoProvider() throws IOException, ODataException { + JPAODataClaimsProvider claims = null; + + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(403); + } + + @Test + public void testRestrictOnePropertyNoValue() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(403); + } + + @Test + public void testRestrictOnePropertyBetweenValues() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin", "Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds?$select=ID,Name1,Country", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(16, bupa.size()); + } + + @Test + public void testRestrictOnePropertyOneValueWithNavigationToRoles() throws IOException, ODataException { + JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Willi")); + final IntegrationTestHelper helper = new IntegrationTestHelper(emf, + "BusinessPartnerProtecteds('99')/Roles", claims); + helper.assertStatus(200); + + final ArrayNode bupa = helper.getValues(); + assertEquals(2, bupa.size()); + } + + @Test + public void testRestrictComplexOnePropertyOnValue() throws ODataException { + prepareTest(); + prepareComplexAttributeCreateUser("UserId"); + + claimNames.add("UserId"); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath("UserId"); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEqual(act); + } + + @Test + public void testRestrictComplexOnePropertyUpperLowerValues() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin", "Willi")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath("UserId"); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertBetween(act); + } + + @Test + public void testRestrictComplexOnePropertyTwoValues() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin")); + claims.add(claimName, new JPAClaimsPair<>("Willi")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.OR, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + @Test + public void testRestrictComplexOnePropertyOneValuesDate() throws ODataException { + final String claimName = "CreationDate"; + prepareTest(); + prepareComplexAttributeDate(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01"))); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEqual(act); + } + + @Test + public void testRestrictComplexOnePropertyUpperLowerValuesDate() throws ODataException { + final String claimName = "CreationDate"; + prepareTest(); + prepareComplexAttributeDate(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>(Date.valueOf("2010-01-01"), Date.valueOf("9999-12-30"))); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertBetween(act); + } + + @Test + public void testRestrictComplexTwoPropertyOneValuesOperatorAND() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + prepareComplexAttributeUpdateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add(claimName, new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.AND, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + @Test + public void testRestrictTwoPropertiesOneValuesOperatorAND() throws ODataException { + final String claimName = "UserId"; + prepareTest(); + prepareComplexAttributeCreateUser(claimName); + prepareComplexAttributeUpdateUser(claimName); + + claimNames.add(claimName); + final JPAODataClaimsProvider claims = new JPAODataClaimsProvider(); + claims.add("UserId", new JPAClaimsPair<>("Marvin")); + + JPAAttribute aSpy = Mockito.spy(etSpy.getAttribute("administrativeInformation")); + doReturn(true).when(aSpy).hasProtection(); + doReturn(claimNames).when(aSpy).getProtectionClaimNames(); + doReturn(pathList).when(aSpy).getProtectionPath(claimName); + attributes.add(aSpy); + + final Expression act = ((JPAJoinQuery) cut).createProtectionWhere(Optional.of(claims)); + assertEquals(BooleanOperator.AND, ((CompoundExpressionImpl) act).getOperator()); + for (Expression part : ((CompoundExpressionImpl) act).getChildExpressions()) + assertEqual(part); + } + + private void assertBetween(Expression act) { + assertExpression(act, "between", 3); + } + + private void assertEqual(Expression act) { + assertExpression(act, "equal", 2); + } + + private void assertExpression(Expression act, String operator, int size) { + assertNotNull(act); + final List> actChildren = ((CompoundExpressionImpl) act).getChildExpressions(); + assertEquals(size, actChildren.size()); + assertEquals(operator, ((CompoundExpressionImpl) act).getOperation()); + assertEquals("Path", actChildren.get(0).getClass().getInterfaces()[0].getSimpleName()); + } + + private void prepareComplexAttributeUser(final String claimName, final String pathName, + final String intermediateElement) throws ODataJPAModelException { + + final JPAProtectionInfo protection = Mockito.mock(JPAProtectionInfo.class); + protections.add(protection); + + final String path = pathName; + pathList.add(path); + final JPAPath jpaPath = Mockito.mock(JPAPath.class); + final JPAElement adminAttri = Mockito.mock(JPAElement.class); + final JPAElement complexAttri = Mockito.mock(JPAElement.class); + final JPAAttribute simpleAttri = Mockito.mock(JPAAttribute.class); + final List pathElements = Arrays.asList(new JPAElement[] { adminAttri, complexAttri, simpleAttri }); + doReturn(pathElements).when(jpaPath).getPath(); + doReturn("administrativeInformation").when(adminAttri).getInternalName(); + doReturn(intermediateElement).when(complexAttri).getInternalName(); + doReturn("by").when(simpleAttri).getInternalName(); + doReturn(String.class).when(simpleAttri).getType(); + doReturn(simpleAttri).when(jpaPath).getLeaf(); + doReturn(jpaPath).when(etSpy).getPath(path); + + doReturn(simpleAttri).when(protection).getAttribute(); + doReturn(jpaPath).when(protection).getPath(); + doReturn(claimName).when(protection).getClaimName(); + } + + private void prepareComplexAttributeCreateUser(final String claimName) throws ODataJPAModelException { + prepareComplexAttributeUser(claimName, "AdministrativeInformation/Created/By", "created"); + } + + private void prepareComplexAttributeUpdateUser(final String claimName) throws ODataJPAModelException { + prepareComplexAttributeUser(claimName, "AdministrativeInformation/Updated/By", "updated"); + } + + private void prepareComplexAttributeDate(final String claimName) throws ODataJPAModelException { + + final JPAProtectionInfo protection = Mockito.mock(JPAProtectionInfo.class); + protections.add(protection); + + final String path = "AdministrativeInformation/Created/At"; + pathList.add(path); + final JPAPath jpaPath = Mockito.mock(JPAPath.class); + final JPAElement adminAttri = Mockito.mock(JPAElement.class); + final JPAElement complexAttri = Mockito.mock(JPAElement.class); + final JPAAttribute simpleAttri = Mockito.mock(JPAAttribute.class); + final List pathElements = Arrays.asList(new JPAElement[] { adminAttri, complexAttri, simpleAttri }); + doReturn(pathElements).when(jpaPath).getPath(); + doReturn("administrativeInformation").when(adminAttri).getInternalName(); + doReturn("created").when(complexAttri).getInternalName(); + doReturn("at").when(simpleAttri).getInternalName(); + doReturn(Date.class).when(simpleAttri).getType(); + doReturn(simpleAttri).when(jpaPath).getLeaf(); + doReturn(jpaPath).when(etSpy).getPath(path); + + doReturn(simpleAttri).when(protection).getAttribute(); + doReturn(jpaPath).when(protection).getPath(); + doReturn(claimName).when(protection).getClaimName(); + + } + + private void prepareTest() throws ODataException { + buildUriInfo("BusinessPartnerProtecteds", "BusinessPartnerProtected"); + odataType = ((UriResourceEntitySet) uriInfo.getUriResourceParts().get(0)).getType(); + attributes = new ArrayList<>(); + claimNames = new HashSet<>(); + pathList = new ArrayList<>(); + protections = new ArrayList<>(); + + etSpy = Mockito.spy(new JPAEntityTypeDouble(sdSpy.getEntity("BusinessPartnerProtecteds"))); + doReturn(attributes).when(etSpy).getAttributes(); + doReturn(protections).when(etSpy).getProtections(); + doReturn(etSpy).when(sdSpy).getEntity("BusinessPartnerProtecteds"); + doReturn(etSpy).when(sdSpy).getEntity(odataType); + cut = new JPAJoinQuery(null, contextSpy, emf.createEntityManager(), headers, uriInfo); + cut.createFromClause(new ArrayList(1), new ArrayList(), cut.cq); + + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java new file mode 100644 index 0000000000..d885bf0bdc --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPAServerDrivenPaging.java @@ -0,0 +1,311 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.isNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveType; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.queryoption.OrderByItem; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SelectItem; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; +import org.apache.olingo.server.api.uri.queryoption.expression.Member; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.processor.core.api.JPAODataPage; +import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider; +import com.sap.olingo.jpa.processor.core.util.IntegrationTestHelper; +import com.sap.olingo.jpa.processor.core.util.TestBase; + +public class TestJPAServerDrivenPaging extends TestBase { + @Test + public void testReturnsNotImplementedIfPagingProviderNotAvailable() throws IOException, ODataException { + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz"); + helper.assertStatus(501); + } + + @Test + public void testReturnsGoneIfPagingProviderRetunrsNullForSkiptoken() throws IOException, ODataException { + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getNextPage("xyz")).thenReturn(null); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider); + helper.assertStatus(410); + + } + + @Test + public void testReturnsFullResultIfProviderDoesNotReturnPage() throws IOException, ODataException { + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenReturn(null); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations", provider); + helper.assertStatus(200); + assertEquals(10, helper.getValues().size()); + } + + @Test + public void testReturnsPartResultIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + } + + @Test + public void testReturnsNextLinkIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + assertEquals("Organizations?$skiptoken='Hugo'", helper.getValue().get("@odata.nextLink").asText()); + } + + @Test + public void testReturnsNextLinkNotAStringIfProviderPages() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, new Integer(123456789))); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + assertEquals("Organizations?$skiptoken=123456789", helper.getValue().get("@odata.nextLink").asText()); + } + + @Test + public void testReturnsNextPagesRespectingFilter() throws IOException, ODataException { + final UriInfo uriInfo = buildUriInfo(); + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getNextPage("xyz")).thenReturn(new JPAODataPage(uriInfo, 5, 5, null)); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$skiptoken=xyz", provider); + helper.assertStatus(200); + assertEquals(5, helper.getValues().size()); + ObjectNode org = (ObjectNode) helper.getValues().get(4); + assertEquals("1", org.get("ID").asText()); + } + + @Test + public void testEntityManagerProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), any(), any(), isNotNull()); + } + + @Test + public void testCountQueryProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), any(), isNotNull(), any()); + } + + @Test + public void testMaxPageSizeHeaderProvided() throws IOException, ODataException { + + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=50"); + headers.put("Prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), isNotNull(), any(), any()); + } + + @Test + public void testMaxPageSizeHeaderProvidedInLowerCase() throws IOException, ODataException { + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=50"); + headers.put("prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(200); + + verify(provider).getFirstPage(any(), isNotNull(), any(), any()); + } + + @Test + public void testUriInfoProvided() throws IOException, ODataException { + + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider); + helper.assertStatus(200); + + verify(provider).getFirstPage(isNotNull(), any(), any(), any()); + } + + @Test + public void testMaxPageSiteHeaderNotANumber() throws IOException, ODataException { + + headers = new HashMap<>(); + final List headerValues = new ArrayList<>(1); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + headerValues.add("odata.maxpagesize=Hugo"); + headers.put("Prefer", headerValues); + + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc", provider, headers); + helper.assertStatus(400); + + } + + @Test + public void testSelectSubsetOfFields() throws IOException, ODataException { + final UriInfo uriInfo = buildUriInfo(); + final JPAODataPagingProvider provider = mock(JPAODataPagingProvider.class); + final SelectOption selOpt = mock(SelectOption.class); + final List selItems = new ArrayList<>(); + final SelectItem selItem = mock(SelectItem.class); + + when(uriInfo.getSelectOption()).thenReturn(selOpt); + when(selOpt.getKind()).thenReturn(SystemQueryOptionKind.SELECT); + when(selOpt.getSelectItems()).thenReturn(selItems); + selItems.add(selItem); + + final UriInfoResource selectPath = mock(UriInfoResource.class); + final List selectPathItems = new ArrayList<>(1); + final UriResourcePrimitiveProperty selectResource = mock(UriResourcePrimitiveProperty.class); + final EdmProperty selectProperty = mock(EdmProperty.class); + selectPathItems.add(selectResource); + when(selItem.getResourcePath()).thenReturn(selectPath); + when(selectPath.getUriResourceParts()).thenReturn(selectPathItems); + when(selectResource.getSegmentValue()).thenReturn("ID"); + when(selectResource.getProperty()).thenReturn(selectProperty); + when(selectProperty.getName()).thenReturn("ID"); + + when(provider.getFirstPage(any(), any(), any(), any())).thenAnswer(i -> new JPAODataPage((UriInfo) i + .getArguments()[0], 0, 5, "Hugo")); + + when(provider.getNextPage("'Hugo'")).thenReturn(new JPAODataPage(uriInfo, 5, 5, "Willi")); + IntegrationTestHelper helper = new IntegrationTestHelper(emf, "Organizations?$orderby=ID desc&$select=ID", + provider); + helper.assertStatus(200); + assertNull(helper.getValues().get(0).get("Country")); + IntegrationTestHelper act = new IntegrationTestHelper(emf, "Organizations?$skiptoken='Hugo'", + provider); + act.assertStatus(200); + assertEquals(5, act.getValues().size()); + assertNull(act.getValues().get(0).get("Country")); + + } + + private UriInfo buildUriInfo() throws EdmPrimitiveTypeException { + final UriInfo uriInfo = mock(UriInfo.class); + final UriResourceEntitySet uriEs = mock(UriResourceEntitySet.class); + final EdmEntitySet es = mock(EdmEntitySet.class); + final EdmEntityType et = mock(EdmEntityType.class); + final EdmType type = mock(EdmType.class); + final OrderByOption order = mock(OrderByOption.class); + final OrderByItem orderItem = mock(OrderByItem.class); + final Member orderExpression = mock(Member.class); + final UriInfoResource orderResourcePath = mock(UriInfoResource.class); + final UriResourcePrimitiveProperty orderResourcePathItem = mock(UriResourcePrimitiveProperty.class); + final EdmProperty orderProperty = mock(EdmProperty.class); + final List orderItems = new ArrayList<>(); + final List orderResourcePathItems = new ArrayList<>(); + + final EdmProperty propertyID = mock(EdmProperty.class); // type.getStructuralProperty(propertyName); + final EdmProperty propertyCountry = mock(EdmProperty.class); + final EdmPrimitiveType propertyType = mock(EdmPrimitiveType.class); + + orderItems.add(orderItem); + orderResourcePathItems.add(orderResourcePathItem); + when(uriEs.getKind()).thenReturn(UriResourceKind.entitySet); + when(uriEs.getEntitySet()).thenReturn(es); + when(uriEs.getType()).thenReturn(type); + when(uriEs.isCollection()).thenReturn(true); + when(es.getName()).thenReturn("Organizations"); + when(es.getEntityType()).thenReturn(et); + when(type.getNamespace()).thenReturn("com.sap.olingo.jpa"); + when(type.getName()).thenReturn("Organization"); + when(et.getFullQualifiedName()).thenReturn(new FullQualifiedName("com.sap.olingo.jpa", "Organization")); + when(et.getPropertyNames()).thenReturn(Arrays.asList("ID", "Country")); + when(et.getStructuralProperty("ID")).thenReturn(propertyID); + when(et.getStructuralProperty("Country")).thenReturn(propertyCountry); + + when(propertyID.getName()).thenReturn("ID"); + when(propertyID.isPrimitive()).thenReturn(true); + when(propertyID.getType()).thenReturn(propertyType); + when(propertyCountry.getName()).thenReturn("Country"); + when(propertyCountry.isPrimitive()).thenReturn(true); + when(propertyCountry.getType()).thenReturn(propertyType); + when(propertyType.getKind()).thenReturn(EdmTypeKind.PRIMITIVE); + when(propertyType.valueToString(any(), any(), any(), any(), any(), any())).thenAnswer(i -> i.getArguments()[0] + .toString()); + + when(order.getKind()).thenReturn(SystemQueryOptionKind.ORDERBY); + when(orderItem.isDescending()).thenReturn(true); + when(orderItem.getExpression()).thenReturn(orderExpression); + when(orderExpression.getResourcePath()).thenReturn(orderResourcePath); + when(orderResourcePath.getUriResourceParts()).thenReturn(orderResourcePathItems); + when(orderResourcePathItem.getProperty()).thenReturn(orderProperty); + when(orderProperty.getName()).thenReturn("ID"); + when(order.getOrders()).thenReturn(orderItems); + final List resourceParts = new ArrayList<>(); + resourceParts.add(uriEs); + when(uriInfo.getUriResourceParts()).thenReturn(resourceParts); + when(uriInfo.getOrderByOption()).thenReturn(order); + return uriInfo; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java new file mode 100644 index 0000000000..78816e3aa6 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverter.java @@ -0,0 +1,248 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.data.ComplexValue; +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.data.ValueType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPATupleChildConverter extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPATupleChildConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + private Map keyPredicates; + private HashMap> queryResult = new HashMap<>(1); + + @BeforeEach + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList<>(); + + queryResult.put(ROOT_RESULT_KEY, jpaQueryResult); + uriHelper = new UriHelperDouble(); + keyPredicates = new HashMap<>(); + uriHelper.setKeyPredicates(keyPredicates, "ID"); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "Organization")); + + } + + @Test + public void checkConvertsEmptyResult() throws ODataApplicationException, ODataJPAModelException { + + assertNotNull(cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType("Organizations")))); + } + + @Test + public void checkConvertsOneResultOneElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result = new HashMap<>(); + + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + } + + @Test + public void checkConvertsOneResultOneKey() throws ODataApplicationException, ODataJPAModelException { + HashMap result = new HashMap<>(); + keyPredicates.put("1", "'1'"); + + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("Organizations" + "('1')", act.getEntities().get(0).getId().getPath()); + } + + @Test + public void checkConvertsTwoResultsOneElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", new String("1")); + jpaQueryResult.add(new TupleDouble(result)); + + result = new HashMap<>(); + result.put("ID", new String("5")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + keyPredicates.put("5", "Organizations('5')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(2, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + assertEquals("5", act.getEntities().get(1).getProperty("ID").getValue().toString()); + } + + @Test + public void checkConvertsOneResultsTwoElements() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", new String("1")); + result.put("Name1", new String("Willi")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("1", act.getEntities().get(0).getProperty("ID").getValue().toString()); + assertEquals("Willi", act.getEntities().get(0).getProperty("Name1").getValue().toString()); + } + + @Test + public void checkConvertsOneResultsOneComplexElement() throws ODataApplicationException, ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", "1"); + result.put("Address/CityName", "Test City"); + result.put("Address/Country", "GB"); + result.put("Address/PostalCode", "ZE1 3AA"); + result.put("Address/StreetName", "Test Road"); + result.put("Address/HouseNumber", "123"); + result.put("Address/POBox", "155"); + result.put("Address/Region", "GB-12"); + result.put("Address/CountryName", "Willi"); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + + assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("Address").getValueType()); + ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("Address").getValue(); + assertEquals(NO_POSTAL_ADDRESS_FIELDS, value.getValue().size()); + } + + @Test + public void checkConvertsOneResultsOneNestedComplexElement() throws ODataApplicationException, + ODataJPAModelException { + HashMap result; + +// AdministrativeInformation adminInfo = new AdministrativeInformation(); +// adminInfo.setCreated(new ChangeInformation("Joe Doe", Timestamp.valueOf("2016-01-22 12:25:23"))); +// adminInfo.setUpdated(new ChangeInformation("Joe Doe", Timestamp.valueOf("2016-01-24 14:29:45"))); + result = new HashMap<>(); + result.put("ID", "1"); + result.put("AdministrativeInformation/Created/By", "Joe Doe"); + result.put("AdministrativeInformation/Created/At", "2016-01-22 12:25:23"); + result.put("AdministrativeInformation/Updated/By", "Joe Doe"); + result.put("AdministrativeInformation/Updated/At", "2016-01-24 14:29:45"); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + // Check first level + assertEquals(ValueType.COMPLEX, act.getEntities().get(0).getProperty("AdministrativeInformation").getValueType()); + ComplexValue value = (ComplexValue) act.getEntities().get(0).getProperty("AdministrativeInformation").getValue(); + assertEquals(NO_ADMIN_INFO_FIELDS, value.getValue().size()); + // Check second level + assertEquals(ValueType.COMPLEX, value.getValue().get(0).getValueType()); + } + + @Test + public void checkConvertsOneResultsOneElementOfComplexElement() throws ODataApplicationException, + ODataJPAModelException { + HashMap result; + + result = new HashMap<>(); + result.put("ID", "1"); + result.put("Address/Region", new String("CA")); + jpaQueryResult.add(new TupleDouble(result)); + + keyPredicates.put("1", "Organizations('1')"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(queryResult, null, helper.getJPAEntityType( + "Organizations"))).get(ROOT_RESULT_KEY); + assertEquals(1, act.getEntities().size()); + assertEquals("CA", ((ComplexValue) act.getEntities().get(0).getProperty("Address").getValue()).getValue().get(0) + .getValue().toString()); + } + + @Test + public void checkConvertMediaStreamStaticMime() throws ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + HashMap> result = new HashMap<>(1); + result.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, "PersonImage")); + + HashMap entityResult; + byte[] image = { -119, 10 }; + entityResult = new HashMap<>(); + entityResult.put("ID", "1"); + entityResult.put("Image", image); + jpaQueryResult.add(new TupleDouble(entityResult)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType( + "PersonImages"))).get(ROOT_RESULT_KEY); + + assertEquals("image/png", act.getEntities().get(0).getMediaContentType()); + } + + @Test + public void checkConvertMediaStreamDynamicMime() throws ODataJPAModelException, NumberFormatException, + ODataApplicationException { + + HashMap> result = new HashMap<>(1); + result.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "OrganizationImage")); + + HashMap entityResult; + byte[] image = { -119, 10 }; + entityResult = new HashMap<>(); + entityResult.put("ID", "9"); + entityResult.put("Image", image); + entityResult.put("MimeType", "image/svg+xml"); + jpaQueryResult.add(new TupleDouble(entityResult)); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(result, null, helper.getJPAEntityType( + "OrganizationImages"))).get(ROOT_RESULT_KEY); + assertEquals("image/svg+xml", act.getEntities().get(0).getMediaContentType()); + assertEquals(2, act.getEntities().get(0).getProperties().size()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java new file mode 100644 index 0000000000..560548dcb5 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/query/TestJPATupleChildConverterCompoundKey.java @@ -0,0 +1,111 @@ +package com.sap.olingo.jpa.processor.core.query; + +import static com.sap.olingo.jpa.processor.core.converter.JPAExpandResult.ROOT_RESULT_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Tuple; + +import org.apache.olingo.commons.api.data.EntityCollection; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.ODataApplicationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.processor.core.converter.JPATupleChildConverter; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.util.ServiceMetadataDouble; +import com.sap.olingo.jpa.processor.core.util.TestBase; +import com.sap.olingo.jpa.processor.core.util.TestHelper; +import com.sap.olingo.jpa.processor.core.util.TupleDouble; +import com.sap.olingo.jpa.processor.core.util.UriHelperDouble; + +public class TestJPATupleChildConverterCompoundKey extends TestBase { + public static final int NO_POSTAL_ADDRESS_FIELDS = 8; + public static final int NO_ADMIN_INFO_FIELDS = 2; + private JPATupleChildConverter cut; + private List jpaQueryResult; + private UriHelperDouble uriHelper; + private Map keyPredicates; + + @BeforeEach + public void setup() throws ODataException { + helper = new TestHelper(emf, PUNIT_NAME); + jpaQueryResult = new ArrayList<>(); + uriHelper = new UriHelperDouble(); + keyPredicates = new HashMap<>(); + } + + @Test + public void checkConvertsOneResultsTwoKeys() throws ODataApplicationException, ODataJPAModelException { + // .../BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C') + + HashMap> resultContainer = new HashMap<>(1); + resultContainer.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "BusinessPartnerRole")); + + HashMap result; + + result = new HashMap<>(); + result.put("BusinessPartnerID", new String("3")); + result.put("RoleCategory", new String("C")); + jpaQueryResult.add(new TupleDouble(result)); + + uriHelper.setKeyPredicates(keyPredicates, "BusinessPartnerID"); + keyPredicates.put("3", "BusinessPartnerID='3',RoleCategory='C'"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType( + "BusinessPartnerRoles"))).get(ROOT_RESULT_KEY); + + assertEquals(1, act.getEntities().size()); + assertEquals("3", act.getEntities().get(0).getProperty("BusinessPartnerID").getValue().toString()); + assertEquals("C", act.getEntities().get(0).getProperty("RoleCategory").getValue().toString()); + + assertEquals("BusinessPartnerRoles(BusinessPartnerID='3',RoleCategory='C')", + act.getEntities().get(0).getId().getPath()); + } + + @Test // EmbeddedIds are resolved to elementary key properties + public void checkConvertsOneResultsEmbeddedKey() throws ODataApplicationException, ODataJPAModelException { + // .../AdministrativeDivisionDescriptions(CodePublisher='ISO', CodeID='3166-1', DivisionCode='DEU',Language='en') + + HashMap> resultContainer = new HashMap<>(1); + resultContainer.put("root", jpaQueryResult); + + cut = new JPATupleChildConverter(helper.sd, uriHelper, new ServiceMetadataDouble(nameBuilder, + "AdministrativeDivisionDescription")); + + AdministrativeDivisionDescriptionKey country = new AdministrativeDivisionDescriptionKey(); + country.setLanguage("en"); + + HashMap result; + + result = new HashMap<>(); + result.put("CodePublisher", new String("ISO")); + result.put("CodeID", new String("3166-1")); + result.put("DivisionCode", new String("DEU")); + result.put("Language", new String("en")); + jpaQueryResult.add(new TupleDouble(result)); + uriHelper.setKeyPredicates(keyPredicates, "DivisionCode"); + keyPredicates.put("DEU", "CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en'"); + + EntityCollection act = cut.getResult(new JPAExpandQueryResult(resultContainer, null, helper.getJPAEntityType( + "AdministrativeDivisionDescriptions"))).get(ROOT_RESULT_KEY); + + assertEquals(1, act.getEntities().size()); + assertEquals("ISO", act.getEntities().get(0).getProperty("CodePublisher").getValue().toString()); + assertEquals("en", act.getEntities().get(0).getProperty("Language").getValue().toString()); + + assertEquals( + "AdministrativeDivisionDescriptions(CodePublisher='ISO',CodeID='3166-1',DivisionCode='DEU',Language='en')", + act.getEntities().get(0).getId().getPath()); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java new file mode 100644 index 0000000000..717ceb7146 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntitySetDouble.java @@ -0,0 +1,80 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmBindingTarget; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmMapping; +import org.apache.olingo.commons.api.edm.EdmNavigationPropertyBinding; +import org.apache.olingo.commons.api.edm.EdmTerm; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class EdmEntitySetDouble implements EdmEntitySet { + private final String name; + private final EdmEntityType type; + // private final JPAEdmNameBuilder nameBuilder; + + public EdmEntitySetDouble(final JPAEdmNameBuilder nameBuilder, final String name) { + super(); + this.name = name; + this.type = new EdmEntityTypeDouble(nameBuilder, name.substring(0, name.length() - 1)); + // this.nameBuilder = nameBuilder; + } + + @Override + public String getTitle() { + return null; + } + + @Override + public EdmBindingTarget getRelatedBindingTarget(final String path) { + return null; + } + + @Override + public List getNavigationPropertyBindings() { + return null; + } + + @Override + public EdmEntityContainer getEntityContainer() { + return null; + } + + @Override + public EdmEntityType getEntityType() { + return type; + } + + @Override + public String getName() { + return name; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + return null; + } + + @Override + public List getAnnotations() { + return null; + } + + @Override + public boolean isIncludeInServiceDocument() { + return false; + } + + @Override + public EdmMapping getMapping() { + fail(); + return null; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java new file mode 100644 index 0000000000..cb89a2e82b --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmEntityTypeDouble.java @@ -0,0 +1,141 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmElement; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class EdmEntityTypeDouble implements EdmEntityType { + + private final String name; + private final JPAEdmNameBuilder nameBuilder; + + public EdmEntityTypeDouble(final JPAEdmNameBuilder nameBuilder, final String name) { + this.name = name; + this.nameBuilder = nameBuilder; + } + + @Override + public EdmElement getProperty(final String name) { + fail(); + return null; + } + + @Override + public List getPropertyNames() { + fail(); + return null; + } + + @Override + public EdmProperty getStructuralProperty(final String name) { + fail(); + return null; + } + + @Override + public EdmNavigationProperty getNavigationProperty(final String name) { + fail(); + return null; + } + + @Override + public List getNavigationPropertyNames() { + fail(); + return null; + } + + @Override + public boolean compatibleTo(final EdmType targetType) { + fail(); + return false; + } + + @Override + public boolean isOpenType() { + fail(); + return false; + } + + @Override + public boolean isAbstract() { + fail(); + return false; + } + + @Override + public FullQualifiedName getFullQualifiedName() { + return nameBuilder.buildFQN(name); + } + + @Override + public String getNamespace() { + return nameBuilder.buildNamespace(); + } + + @Override + public EdmTypeKind getKind() { + fail(); + return null; + } + + @Override + public String getName() { + return name; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public List getKeyPredicateNames() { + fail(); + return null; + } + + @Override + public List getKeyPropertyRefs() { + fail(); + return null; + } + + @Override + public EdmKeyPropertyRef getKeyPropertyRef(final String keyPredicateName) { + fail(); + return null; + } + + @Override + public boolean hasStream() { + fail(); + return false; + } + + @Override + public EdmEntityType getBaseType() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java new file mode 100644 index 0000000000..8ef7884dce --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmNavigationPropertyDouble.java @@ -0,0 +1,80 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmReferentialConstraint; +import org.apache.olingo.commons.api.edm.EdmTerm; + +public class EdmNavigationPropertyDouble implements EdmNavigationProperty { + private final String name; + + public EdmNavigationPropertyDouble(final String name) { + super(); + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public EdmEntityType getType() { + fail(); + return null; + } + + @Override + public boolean isNullable() { + fail(); + return false; + } + + @Override + public boolean containsTarget() { + fail(); + return false; + } + + @Override + public EdmNavigationProperty getPartner() { + fail(); + return null; + } + + @Override + public String getReferencingPropertyName(final String referencedPropertyName) { + fail(); + return null; + } + + @Override + public List getReferentialConstraints() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java new file mode 100644 index 0000000000..b788a74a36 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/EdmPropertyDouble.java @@ -0,0 +1,112 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmAnnotation; +import org.apache.olingo.commons.api.edm.EdmMapping; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.edm.geo.SRID; + +public class EdmPropertyDouble implements EdmProperty { + private final String name; + + public EdmPropertyDouble(final String name) { + super(); + this.name = name; + } + + @Override + public String getName() { + + return name; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public EdmMapping getMapping() { + fail(); + return null; + } + + @Override + public EdmAnnotation getAnnotation(final EdmTerm term, final String qualifier) { + fail(); + return null; + } + + @Override + public List getAnnotations() { + fail(); + return null; + } + + @Override + public String getMimeType() { + fail(); + return null; + } + + @Override + public boolean isPrimitive() { + fail(); + return false; + } + + @Override + public boolean isNullable() { + fail(); + return false; + } + + @Override + public Integer getMaxLength() { + fail(); + return null; + } + + @Override + public Integer getPrecision() { + fail(); + return null; + } + + @Override + public Integer getScale() { + fail(); + return null; + } + + @Override + public SRID getSrid() { + fail(); + return null; + } + + @Override + public boolean isUnicode() { + fail(); + return false; + } + + @Override + public String getDefaultValue() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java new file mode 100644 index 0000000000..ae8f83895a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandItemDouble.java @@ -0,0 +1,115 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.LevelsExpandOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class ExpandItemDouble implements ExpandItem { + private UriResourceNavigation target; + + public ExpandItemDouble(final EdmEntityType naviTargetEntity) { + target = new UriResourceNavigationDouble(naviTargetEntity, new EdmNavigationPropertyDouble( + naviTargetEntity.getName())); + } + + @Override + public LevelsExpandOption getLevelsOption() { + return null; + } + + @Override + public FilterOption getFilterOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + fail(); + return null; + } + + @Override + public UriInfoResource getResourcePath() { + return new UriInfoResourceDouble(target); + } + + @Override + public boolean isStar() { + return false; + } + + @Override + public boolean isRef() { + fail(); + return false; + } + + @Override + public EdmType getStartTypeFilter() { + fail(); + return null; + } + + @Override + public boolean hasCountPath() { + fail(); + return false; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java new file mode 100644 index 0000000000..f6fc14d428 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ExpandOptionDouble.java @@ -0,0 +1,43 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.server.api.uri.queryoption.ExpandItem; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOptionKind; + +public class ExpandOptionDouble implements ExpandOption { + private final String text; + private final List items; + + public ExpandOptionDouble(final String text, final List items) { + super(); + this.text = text; + this.items = items; + } + + @Override + public SystemQueryOptionKind getKind() { + fail(); + return null; + } + + @Override + public String getName() { + fail(); + return null; + } + + @Override + public String getText() { + return text; + } + + @Override + public List getExpandItems() { + return items; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java new file mode 100644 index 0000000000..96e9e38c95 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletRequestDouble.java @@ -0,0 +1,373 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletInputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.olingo.commons.api.http.HttpMethod; + +public class HttpServletRequestDouble implements HttpServletRequest { + private final HttpRequestHeaderDouble reqHeader; + private final String queryString; + private final StringBuffer url; + private final StringBuffer input; + + public HttpServletRequestDouble(final String uri) throws IOException { + this(uri, null); + } + + public HttpServletRequestDouble(final String uri, final StringBuffer body) throws IOException { + this(uri, body, null); + } + + public HttpServletRequestDouble(final String uri, final StringBuffer body, + final Map> headers) throws IOException { + + super(); + this.reqHeader = new HttpRequestHeaderDouble(); + String[] uriParts = uri.split("\\?"); + this.url = new StringBuffer(uriParts[0]); + queryString = (uriParts.length == 2) ? uriParts[1] : null; + this.input = body; + if (uri.contains("$batch")) { + reqHeader.setBatchRequest(); + } + this.reqHeader.setHeaders(headers); + } + + @Override + public Object getAttribute(final String name) { + if (!"requestMapping".equals(name)) + fail(); + return null; + } + + @Override + public Enumeration getAttributeNames() { + fail(); + return null; + } + + @Override + public String getCharacterEncoding() { + fail(); + return null; + } + + @Override + public void setCharacterEncoding(final String env) throws UnsupportedEncodingException { + fail(); + + } + + @Override + public int getContentLength() { + fail(); + return 0; + } + + @Override + public String getContentType() { + fail(); + return null; + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return new ServletInputStreamDouble(input); + } + + @Override + public String getParameter(final String name) { + fail(); + return null; + } + + @Override + public Enumeration getParameterNames() { + fail(); + return null; + } + + @Override + public String[] getParameterValues(final String name) { + fail(); + return null; + } + + @Override + public Map getParameterMap() { + fail(); + return null; + } + + @Override + public String getProtocol() { + return "HTTP/1.1"; + } + + @Override + public String getScheme() { + fail(); + return null; + } + + @Override + public String getServerName() { + fail(); + return null; + } + + @Override + public int getServerPort() { + fail(); + return 0; + } + + @Override + public BufferedReader getReader() throws IOException { + fail(); + return null; + } + + @Override + public String getRemoteAddr() { + fail(); + return null; + } + + @Override + public String getRemoteHost() { + fail(); + return null; + } + + @Override + public void setAttribute(final String name, final Object o) { + fail(); + + } + + @Override + public void removeAttribute(final String name) { + fail(); + + } + + @Override + public Locale getLocale() { + fail(); + return null; + } + + @Override + public Enumeration getLocales() { + fail(); + return null; + } + + @Override + public boolean isSecure() { + fail(); + return false; + } + + @Override + public RequestDispatcher getRequestDispatcher(final String path) { + fail(); + return null; + } + + @Override + public String getRealPath(final String path) { + fail(); + return null; + } + + @Override + public int getRemotePort() { + fail(); + return 0; + } + + @Override + public String getLocalName() { + fail(); + return null; + } + + @Override + public String getLocalAddr() { + fail(); + return null; + } + + @Override + public int getLocalPort() { + fail(); + return 0; + } + + @Override + public String getAuthType() { + fail(); + return null; + } + + @Override + public Cookie[] getCookies() { + fail(); + return null; + } + + @Override + public long getDateHeader(final String name) { + fail(); + return 0; + } + + @Override + public String getHeader(final String name) { + return null; + } + + @Override + public Enumeration getHeaders(final String name) { + + return reqHeader.get(name); + } + + @Override + public Enumeration getHeaderNames() { + return reqHeader.getEnumerator(); + } + + @Override + public int getIntHeader(final String name) { + fail(); + return 0; + } + + @Override + public String getMethod() { + if (url.toString().contains("$batch")) + return HttpMethod.POST.toString(); + else + return HttpMethod.GET.toString(); + } + + @Override + public String getPathInfo() { + fail(); + return null; + } + + @Override + public String getPathTranslated() { + fail(); + return null; + } + + @Override + public String getContextPath() { + fail(); + return null; + } + + @Override + public String getQueryString() { + // $orderby=Roles/$count%20desc,Address/Region%20asc&$select=ID,Name1 + return queryString; + } + + @Override + public String getRemoteUser() { + fail(); + return null; + } + + @Override + public boolean isUserInRole(final String role) { + fail(); + return false; + } + + @Override + public Principal getUserPrincipal() { + fail(); + return null; + } + + @Override + public String getRequestedSessionId() { + fail(); + return null; + } + + @Override + public String getRequestURI() { + fail(); + return null; + } + + @Override + public StringBuffer getRequestURL() { + // http://localhost:8090/BuPa/BuPa.svc/AdministrativeDivisions(DivisionCode='BE252',CodeID='3',CodePublisher='NUTS')/Parent/Parent + // http://localhost:8090/BuPa/BuPa.svc/Organizations + return url; + } + + @Override + public String getServletPath() { + return "/Olingo.svc"; + } + + @Override + public HttpSession getSession(final boolean create) { + return null; + } + + @Override + public HttpSession getSession() { + fail(); + return null; + } + + @Override + public boolean isRequestedSessionIdValid() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromURL() { + fail(); + return false; + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + fail(); + return false; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java new file mode 100644 index 0000000000..97aa45f4e4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/HttpServletResponseDouble.java @@ -0,0 +1,253 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; + +public class HttpServletResponseDouble implements HttpServletResponse { + + private int setStatus; + private ServletOutputStream outputStream = new OutPutStream(); + + @Override + public String getCharacterEncoding() { + fail(); + return null; + } + + @Override + public String getContentType() { + fail(); + return null; + } + + @Override + public ServletOutputStream getOutputStream() throws IOException { + return this.outputStream; + } + + @Override + public PrintWriter getWriter() throws IOException { + fail(); + return null; + } + + @Override + public void setCharacterEncoding(String charset) { + fail(); + + } + + @Override + public void setContentLength(int len) { + fail(); + + } + + @Override + public void setContentType(String type) { + fail(); + + } + + @Override + public void setBufferSize(int size) { + fail(); + + } + + @Override + public int getBufferSize() { + return ((OutPutStream) this.outputStream).getSize(); + } + + @Override + public void flushBuffer() throws IOException { + fail(); + + } + + @Override + public void resetBuffer() { + fail(); + + } + + @Override + public boolean isCommitted() { + fail(); + return false; + } + + @Override + public void reset() { + fail(); + + } + + @Override + public void setLocale(Locale loc) { + fail(); + + } + + @Override + public Locale getLocale() { + fail(); + return null; + } + + @Override + public void addCookie(Cookie cookie) { + fail(); + + } + + @Override + public boolean containsHeader(String name) { + fail(); + return false; + } + + @Override + public String encodeURL(String url) { + fail(); + return null; + } + + @Override + public String encodeRedirectURL(String url) { + fail(); + return null; + } + + @Override + public String encodeUrl(String url) { + fail(); + return null; + } + + @Override + public String encodeRedirectUrl(String url) { + fail(); + return null; + } + + @Override + public void sendError(int sc, String msg) throws IOException { + fail(); + + } + + @Override + public void sendError(int sc) throws IOException { + fail(); + + } + + @Override + public void sendRedirect(String location) throws IOException { + fail(); + + } + + @Override + public void setDateHeader(String name, long date) { + fail(); + + } + + @Override + public void addDateHeader(String name, long date) { + fail(); + + } + + @Override + public void setHeader(String name, String value) { + fail(); + + } + + @Override + public void addHeader(String name, String value) { + // TODO + } + + @Override + public void setIntHeader(String name, int value) { + fail(); + + } + + @Override + public void addIntHeader(String name, int value) { + fail(); + + } + + @Override + public void setStatus(int sc) { + this.setStatus = sc; + } + + @Override + public void setStatus(int sc, String sm) { + fail(); + + } + + public int getStatus() { + return setStatus; + } + + class OutPutStream extends ServletOutputStream { + List buffer = new ArrayList<>(); + + @Override + public void write(int b) throws IOException { + buffer.add(new Integer(b)); + } + + public Iterator getBuffer() { + return buffer.iterator(); + } + + public int getSize() { + return buffer.size(); + } + } + + // + class ResultStream extends InputStream { + private final Iterator bufferExcess; + + public ResultStream(OutPutStream buffer) { + super(); + this.bufferExcess = buffer.getBuffer(); + } + + @Override + public int read() throws IOException { + if (bufferExcess.hasNext()) + return bufferExcess.next().intValue(); + return -1; + } + + } + + public InputStream getInputStream() { + + return new ResultStream((OutPutStream) this.outputStream); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java new file mode 100644 index 0000000000..a1b4bac8da --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/IntegrationTestHelper.java @@ -0,0 +1,213 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.OData; +import org.apache.olingo.server.api.ODataHttpHandler; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataBatchProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataClaimsProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataPagingProvider; +import com.sap.olingo.jpa.processor.core.api.JPAODataRequestProcessor; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; + +public class IntegrationTestHelper { + public final HttpServletRequestDouble req; + public final HttpServletResponseDouble resp; + private static final String uriPrefix = "http://localhost:8080/Test/Olingo.svc/"; + private static final String PUNIT_NAME = "com.sap.olingo.jpa"; + + public IntegrationTestHelper(EntityManagerFactory localEmf, String urlPath) throws IOException, + ODataException { + this(localEmf, null, urlPath, null, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath) throws IOException, + ODataException { + this(localEmf, ds, urlPath, null, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, String urlPath, StringBuffer requestBody) + throws IOException, ODataException { + this(localEmf, null, urlPath, requestBody, null, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, String functionPackage) + throws IOException, ODataException { + this(localEmf, ds, urlPath, null, functionPackage, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, StringBuffer requestBody) + throws IOException, ODataException { + this(localEmf, ds, urlPath, requestBody, null, null); + } + + public IntegrationTestHelper(final EntityManagerFactory localEmf, final String urlPath, + final JPAODataPagingProvider provider) throws IOException, ODataException { + this(localEmf, null, urlPath, null, null, provider); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, final String urlPath, JPAODataClaimsProvider claims) + throws IOException, ODataException { + this(localEmf, null, urlPath, null, null, null, null, claims); + } + + public IntegrationTestHelper(final EntityManagerFactory emf, final String urlPath, + final JPAODataPagingProvider provider, final Map> headers) throws IOException, + ODataException { + this(emf, null, urlPath, null, null, provider, headers, null); + } + + public IntegrationTestHelper(EntityManagerFactory localEmf, DataSource ds, String urlPath, StringBuffer requestBody, + String functionPackage, JPAODataPagingProvider provider) throws IOException, ODataException { + this(localEmf, ds, urlPath, requestBody, functionPackage, provider, null, null); + } + + public IntegrationTestHelper(final EntityManagerFactory localEmf, final DataSource ds, final String urlPath, + final StringBuffer requestBody, final String functionPackage, final JPAODataPagingProvider provider, + final Map> headers, final JPAODataClaimsProvider claims) + throws IOException, ODataException { + + super(); + EntityManager em = localEmf.createEntityManager(); + this.req = new HttpServletRequestDouble(uriPrefix + urlPath, requestBody, headers); + this.resp = new HttpServletResponseDouble(); + OData odata = OData.newInstance(); + String[] packages = TestBase.enumPackages; + if (functionPackage != null) + packages = ArrayUtils.add(packages, functionPackage); + + JPAODataSessionContextAccess context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, localEmf, + null, packages), ds, provider, functionPackage); + + ODataHttpHandler handler = odata.createHandler(odata.createServiceMetadata(context.getEdmProvider(), + new ArrayList())); + + handler.register(new JPAODataRequestProcessor(context, claims, em)); + handler.register(new JPAODataBatchProcessor(context, em)); + handler.process(req, resp); + + } + + public HttpServletResponseDouble getResponce() { + return resp; + } + + public int getStatus() { + return resp.getStatus(); + } + + public String getRawResult() throws IOException { + InputStream in = resp.getInputStream(); + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String read; + + while ((read = br.readLine()) != null) { + sb.append(read); + } + br.close(); + return sb.toString(); + } + + public List getRawBatchResult() throws IOException { + List result = new ArrayList<>(); + + InputStream in = resp.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String read; + + while ((read = br.readLine()) != null) { + result.add(read); + } + br.close(); + return result; + } + + public ArrayNode getValues() throws JsonProcessingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + JsonNode node = mapper.readTree(getRawResult()); + if (!(node.get("value") instanceof ArrayNode)) + fail("Wrong result type; ArrayNode expected"); + ArrayNode values = (ArrayNode) node.get("value"); + return values; + } + + public ObjectNode getValue() throws JsonProcessingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + JsonNode value = mapper.readTree(getRawResult()); + if (!(value instanceof ObjectNode)) + fail("Wrong result type; ObjectNode expected"); + return (ObjectNode) value; + } + + public void assertStatus(int exp) throws IOException { + assertEquals(exp, getStatus(), getRawResult()); + + } + + public int getBatchResultStatus(int i) throws IOException { + List result = getRawBatchResult(); + int count = 0; + for (String resultLine : result) { + if (resultLine.contains("HTTP/1.1")) { + count += 1; + if (count == i) { + String[] statusElements = resultLine.split(" "); + return Integer.parseInt(statusElements[1]); + } + } + } + return 0; + } + + public JsonNode getBatchResult(int i) throws IOException { + List result = getRawBatchResult(); + int count = 0; + boolean found = false; + + for (String resultLine : result) { + if (resultLine.contains("HTTP/1.1")) { + count += 1; + if (count == i) { + found = true; + } + } + if (found && resultLine.startsWith("{")) { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readTree(resultLine); + } + } + return null; + } + + public byte[] getBinaryResult() throws IOException { + byte[] result = new byte[resp.getBufferSize()]; + InputStream in = resp.getInputStream(); + in.read(result); + return result; + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java new file mode 100644 index 0000000000..67998f420a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/JPAEntityTypeDouble.java @@ -0,0 +1,200 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.server.api.uri.UriResourceProperty; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPACollectionAttribute; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAPath; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAProtectionInfo; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; + +public class JPAEntityTypeDouble implements JPAEntityType { + private final JPAEntityType base; + + public JPAEntityTypeDouble(JPAEntityType base) { + super(); + this.base = base; + } + + @Override + public JPAAssociationAttribute getAssociation(String internalName) throws ODataJPAModelException { + return base.getAssociation(internalName); + } + + @Override + public JPAAssociationPath getAssociationPath(String externalName) throws ODataJPAModelException { + return base.getAssociationPath(externalName); + } + + @Override + public List getAssociationPathList() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAttribute getAttribute(UriResourceProperty uriResourceItem) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAttribute getAttribute(String internalName) throws ODataJPAModelException { + return base.getAttribute(internalName); + } + + @Override + public List getAttributes() throws ODataJPAModelException { + return base.getAttributes(); + } + + @Override + public List getCollectionAttributesPath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAssociationPath getDeclaredAssociation(JPAAssociationPath associationPath) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAAssociationPath getDeclaredAssociation(String externalName) throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredAssociations() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredAttributes() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getDeclaredCollectionAttributes() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAPath getPath(String externalName) throws ODataJPAModelException { + return base.getPath(externalName); + } + + @Override + public List getPathList() throws ODataJPAModelException { + return base.getPathList(); + } + + @Override + public Class getTypeClass() { + return base.getTypeClass(); + } + + @Override + public boolean isAbstract() { + fail(); + return false; + } + + @Override + public FullQualifiedName getExternalFQN() { + return base.getExternalFQN(); + } + + @Override + public String getExternalName() { + return base.getExternalName(); + } + + @Override + public String getInternalName() { + return getInternalName(); + } + + @Override + public String getContentType() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public JPAPath getContentTypeAttributePath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getKey() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public List getKeyPath() throws ODataJPAModelException { + fail(); + return null; + } + + @Override + public Class getKeyType() { + return base.getKeyType(); + } + + @Override + public List getSearchablePath() throws ODataJPAModelException { + return base.getSearchablePath(); + } + + @Override + public JPAPath getStreamAttributePath() throws ODataJPAModelException { + return base.getStreamAttributePath(); + } + + @Override + public String getTableName() { + return base.getTableName(); + } + + @Override + public boolean hasEtag() throws ODataJPAModelException { + return base.hasEtag(); + } + + @Override + public boolean hasStream() throws ODataJPAModelException { + return base.hasStream(); + } + + @Override + public List searchChildPath(JPAPath selectItemPath) { + return base.searchChildPath(selectItemPath); + } + + @Override + public JPACollectionAttribute getCollectionAttribute(String externalName) throws ODataJPAModelException { + return base.getCollectionAttribute(externalName); + } + + @Override + public List getProtections() throws ODataJPAModelException { + return base.getProtections(); + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java new file mode 100644 index 0000000000..281299d757 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/ServiceMetadataDouble.java @@ -0,0 +1,188 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmAction; +import org.apache.olingo.commons.api.edm.EdmAnnotations; +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntityContainer; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmEnumType; +import org.apache.olingo.commons.api.edm.EdmFunction; +import org.apache.olingo.commons.api.edm.EdmSchema; +import org.apache.olingo.commons.api.edm.EdmTerm; +import org.apache.olingo.commons.api.edm.EdmTypeDefinition; +import org.apache.olingo.commons.api.edm.FullQualifiedName; +import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; +import org.apache.olingo.commons.api.edmx.EdmxReference; +import org.apache.olingo.server.api.ServiceMetadata; +import org.apache.olingo.server.api.etag.ServiceMetadataETagSupport; + +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; + +public class ServiceMetadataDouble implements ServiceMetadata { + private final Edm edm; + + public ServiceMetadataDouble() { + super(); + edm = new EdmDouble(); + } + + public ServiceMetadataDouble(JPAEdmNameBuilder nameBuilder, String typeName) { + super(); + this.nameBuilder = nameBuilder; + this.edm = new EdmDouble(typeName); + } + + private JPAEdmNameBuilder nameBuilder; + + @Override + public Edm getEdm() { + return edm; + } + + @Override + public ODataServiceVersion getDataServiceVersion() { + fail(); + return null; + } + + @Override + public List getReferences() { + fail(); + return null; + } + + @Override + public ServiceMetadataETagSupport getServiceMetadataETagSupport() { + fail(); + return null; + } + + class EdmDouble implements Edm { + private Map typeMap; + + public EdmDouble() { + super(); + typeMap = new HashMap<>(); + } + + public EdmDouble(String name) { + super(); + typeMap = new HashMap<>(); + EdmEntityType edmType = new EdmEntityTypeDouble(nameBuilder, name); + typeMap.put(edmType.getFullQualifiedName(), edmType); + } + + @Override + public List getSchemas() { + fail(); + return null; + } + + @Override + public EdmSchema getSchema(String namespace) { + fail(); + return null; + } + + @Override + public EdmEntityContainer getEntityContainer() { + fail(); + return null; + } + + @Override + public EdmEntityContainer getEntityContainer(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmEnumType getEnumType(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmTypeDefinition getTypeDefinition(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityType(FullQualifiedName name) { + return typeMap.get(name); + } + + @Override + public EdmComplexType getComplexType(FullQualifiedName name) { + fail(); + return null; + } + + @Override + public EdmAction getUnboundAction(FullQualifiedName actionName) { + fail(); + return null; + } + + @Override + public EdmAction getBoundAction(FullQualifiedName actionName, FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + fail(); + return null; + } + + @Override + public List getUnboundFunctions(FullQualifiedName functionName) { + fail(); + return null; + } + + @Override + public EdmFunction getUnboundFunction(FullQualifiedName functionName, List parameterNames) { + fail(); + return null; + } + + @Override + public EdmFunction getBoundFunction(FullQualifiedName functionName, FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection, List parameterNames) { + fail(); + return null; + } + + @Override + public EdmTerm getTerm(FullQualifiedName termName) { + fail(); + return null; + } + + @Override + public EdmAnnotations getAnnotationGroup(FullQualifiedName targetName, String qualifier) { + fail(); + return null; + } + + @Override + public EdmAction getBoundActionWithBindingType(FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + return null; + } + + @Override + public List getBoundFunctionsWithBindingType(FullQualifiedName bindingParameterTypeName, + Boolean isBindingParameterCollection) { + // TODO Check what this is used for + return null; + } + + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java new file mode 100644 index 0000000000..3e0472f27e --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestBase.java @@ -0,0 +1,41 @@ +package com.sap.olingo.jpa.processor.core.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.junit.jupiter.api.BeforeAll; + +import com.sap.olingo.jpa.metadata.api.JPAEntityManagerFactory; +import com.sap.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestBase { + + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + public static final String[] enumPackages = { "com.sap.olingo.jpa.processor.core.testmodel" }; + protected static EntityManagerFactory emf; + protected TestHelper helper; + protected Map> headers; + protected static JPAEdmNameBuilder nameBuilder; + protected static DataSource ds; + + @BeforeAll + public static void setupClass() throws ODataJPAModelException { + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_DERBY); + emf = JPAEntityManagerFactory.getEntityManagerFactory(PUNIT_NAME, ds); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + } + + protected void createHeaders() { + headers = new HashMap<>(); + List languageHeaders = new ArrayList<>(); + languageHeaders.add("de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); + headers.put("accept-language", languageHeaders); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java new file mode 100644 index 0000000000..670a59fc08 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/TestQueryBase.java @@ -0,0 +1,91 @@ +package com.sap.olingo.jpa.processor.core.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.persistence.criteria.From; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Root; + +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.commons.api.ex.ODataException; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.Mockito; + +import com.sap.olingo.jpa.metadata.api.JPAEdmProvider; +import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; +import com.sap.olingo.jpa.metadata.core.edm.mapper.impl.JPAEdmNameBuilder; +import com.sap.olingo.jpa.processor.core.api.JPAODataContextAccessDouble; +import com.sap.olingo.jpa.processor.core.api.JPAODataSessionContextAccess; +import com.sap.olingo.jpa.processor.core.query.JPAAbstractJoinQuery; +import com.sap.olingo.jpa.processor.core.query.JPAJoinQuery; + +public class TestQueryBase extends TestBase { + + protected JPAAbstractJoinQuery cut; + protected JPAEntityType jpaEntityType; + protected HashMap> joinTables; + protected Root root; + protected JPAODataSessionContextAccess context; + protected UriInfo uriInfo; + + public TestQueryBase() { + super(); + } + + @BeforeEach + public void setup() throws ODataException { + buildUriInfo("BusinessPartners", "BusinessPartner"); + + helper = new TestHelper(emf, PUNIT_NAME); + nameBuilder = new JPAEdmNameBuilder(PUNIT_NAME); + jpaEntityType = helper.getJPAEntityType("BusinessPartners"); + createHeaders(); + context = new JPAODataContextAccessDouble(new JPAEdmProvider(PUNIT_NAME, emf, null, TestBase.enumPackages), ds, + null); + + cut = new JPAJoinQuery(null, context, emf.createEntityManager(), headers, uriInfo); + + root = emf.getCriteriaBuilder().createTupleQuery().from(jpaEntityType.getTypeClass()); + joinTables = new HashMap<>(); + joinTables.put(jpaEntityType.getExternalName(), root); + } + + protected EdmType buildUriInfo(final String esName, final String etName) { + uriInfo = Mockito.mock(UriInfo.class); + final EdmEntitySet odataEs = Mockito.mock(EdmEntitySet.class); + final EdmType odataType = Mockito.mock(EdmEntityType.class); + final List resources = new ArrayList<>(); + final UriResourceEntitySet esResource = Mockito.mock(UriResourceEntitySet.class); + Mockito.when(uriInfo.getUriResourceParts()).thenReturn(resources); + Mockito.when(esResource.getKeyPredicates()).thenReturn(new ArrayList<>(1)); + Mockito.when(esResource.getEntitySet()).thenReturn(odataEs); + Mockito.when(esResource.getKind()).thenReturn(UriResourceKind.entitySet); + Mockito.when(esResource.getType()).thenReturn(odataType); + Mockito.when(odataEs.getName()).thenReturn(esName); + Mockito.when(odataType.getNamespace()).thenReturn(PUNIT_NAME); + Mockito.when(odataType.getName()).thenReturn(etName); + resources.add(esResource); + return odataType; + } + + protected void fillJoinTable(Root joinRoot) { + Join join = joinRoot.join("locationName", JoinType.LEFT); + joinTables.put("locationName", join); + join = joinRoot.join("address", JoinType.LEFT); + join = join.join("countryName", JoinType.LEFT); + joinTables.put("countryName", join); + join = joinRoot.join("address", JoinType.LEFT); + join = join.join("regionName", JoinType.LEFT); + joinTables.put("regionName", join); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java new file mode 100644 index 0000000000..cbd909dea7 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriHelperDouble.java @@ -0,0 +1,66 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; +import java.util.Map; + +import org.apache.olingo.commons.api.data.Entity; +import org.apache.olingo.commons.api.edm.Edm; +import org.apache.olingo.commons.api.edm.EdmEntitySet; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmStructuredType; +import org.apache.olingo.server.api.deserializer.DeserializerException; +import org.apache.olingo.server.api.serializer.SerializerException; +import org.apache.olingo.server.api.uri.UriHelper; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceEntitySet; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; + +public class UriHelperDouble implements UriHelper { + private Map keyPredicates; + private String idPropertyName; + + @Override + public String buildContextURLSelectList(EdmStructuredType type, ExpandOption expand, SelectOption select) + throws SerializerException { + fail(); + return null; + } + + @Override + public String buildContextURLKeyPredicate(List keys) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildCanonicalURL(EdmEntitySet edmEntitySet, Entity entity) throws SerializerException { + fail(); + return null; + } + + @Override + public String buildKeyPredicate(EdmEntityType edmEntityType, Entity entity) throws SerializerException { + + return keyPredicates.get(entity.getProperty(idPropertyName).getValue()); + } + + @Override + public UriResourceEntitySet parseEntityId(Edm edm, String entityId, String rawServiceRoot) + throws DeserializerException { + fail(); + return null; + } + + public Map getKeyPredicates() { + return keyPredicates; + } + + public void setKeyPredicates(Map keyPredicates, String idPropertyName) { + this.keyPredicates = keyPredicates; + this.idPropertyName = idPropertyName; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java new file mode 100644 index 0000000000..061d211dac --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoDouble.java @@ -0,0 +1,380 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmComplexType; +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriInfo; +import org.apache.olingo.server.api.uri.UriInfoAll; +import org.apache.olingo.server.api.uri.UriInfoBatch; +import org.apache.olingo.server.api.uri.UriInfoCrossjoin; +import org.apache.olingo.server.api.uri.UriInfoEntityId; +import org.apache.olingo.server.api.uri.UriInfoKind; +import org.apache.olingo.server.api.uri.UriInfoMetadata; +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriInfoService; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceComplexProperty; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourcePrimitiveProperty; +import org.apache.olingo.server.api.uri.UriResourceProperty; +import org.apache.olingo.server.api.uri.queryoption.AliasQueryOption; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption; +import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.FormatOption; +import org.apache.olingo.server.api.uri.queryoption.IdOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption; +import org.apache.olingo.server.api.uri.queryoption.SystemQueryOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class UriInfoDouble implements UriInfo { + + private final SelectOption selOpts; + private ExpandOption expandOpts; + private List uriResources; + + public UriInfoDouble(SelectOption selOpts) { + super(); + this.selOpts = selOpts; + this.uriResources = new ArrayList<>(1); + } + + @Override + public FormatOption getFormatOption() { + fail(); + return null; + } + + @Override + public String getFragment() { + fail(); + return null; + } + + @Override + public List getCustomQueryOptions() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + return expandOpts; + } + + @Override + public FilterOption getFilterOption() { + fail(); + return null; + } + + @Override + public IdOption getIdOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + return selOpts; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public SkipTokenOption getSkipTokenOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public List getUriResourceParts() { + return uriResources; + } + + @Override + public String getValueForAlias(String alias) { + fail(); + return null; + } + + @Override + public List getEntitySetNames() { + fail(); + return null; + } + + @Override + public EdmEntityType getEntityTypeCast() { + fail(); + return null; + } + + @Override + public UriInfoKind getKind() { + fail(); + return null; + } + + @Override + public UriInfoService asUriInfoService() { + fail(); + return null; + } + + @Override + public UriInfoAll asUriInfoAll() { + fail(); + return null; + } + + @Override + public UriInfoBatch asUriInfoBatch() { + fail(); + return null; + } + + @Override + public UriInfoCrossjoin asUriInfoCrossjoin() { + fail(); + return null; + } + + @Override + public UriInfoEntityId asUriInfoEntityId() { + fail(); + return null; + } + + @Override + public UriInfoMetadata asUriInfoMetadata() { + fail(); + return null; + } + + @Override + public UriInfoResource asUriInfoResource() { + fail(); + return null; + } + + @Override + public List getSystemQueryOptions() { + fail(); + return null; + } + + @Override + public List getAliases() { + fail(); + return null; + } + + class primitiveDouble implements UriResourcePrimitiveProperty { + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + } + + class complexDouble implements UriResourceComplexProperty { + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexType() { + fail(); + return null; + } + + @Override + public EdmComplexType getComplexTypeFilter() { + fail(); + return null; + } + } + + class propertyDouble implements UriResourceProperty { + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmProperty getProperty() { + fail(); + return null; + } + } + + public void setExpandOpts(ExpandOption expandOpts) { + this.expandOpts = expandOpts; + } + + public void setUriResources(List uriResources) { + this.uriResources = uriResources; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + + @Override + public DeltaTokenOption getDeltaTokenOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java new file mode 100644 index 0000000000..7eb66b16b6 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriInfoResourceDouble.java @@ -0,0 +1,126 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.olingo.server.api.uri.UriInfoResource; +import org.apache.olingo.server.api.uri.UriResource; +import org.apache.olingo.server.api.uri.UriResourceNavigation; +import org.apache.olingo.server.api.uri.queryoption.ApplyOption; +import org.apache.olingo.server.api.uri.queryoption.CountOption; +import org.apache.olingo.server.api.uri.queryoption.CustomQueryOption; +import org.apache.olingo.server.api.uri.queryoption.DeltaTokenOption; +import org.apache.olingo.server.api.uri.queryoption.ExpandOption; +import org.apache.olingo.server.api.uri.queryoption.FilterOption; +import org.apache.olingo.server.api.uri.queryoption.FormatOption; +import org.apache.olingo.server.api.uri.queryoption.IdOption; +import org.apache.olingo.server.api.uri.queryoption.OrderByOption; +import org.apache.olingo.server.api.uri.queryoption.SearchOption; +import org.apache.olingo.server.api.uri.queryoption.SelectOption; +import org.apache.olingo.server.api.uri.queryoption.SkipOption; +import org.apache.olingo.server.api.uri.queryoption.SkipTokenOption; +import org.apache.olingo.server.api.uri.queryoption.TopOption; + +public class UriInfoResourceDouble implements UriInfoResource { + private final List resources; + + public UriInfoResourceDouble(UriResourceNavigation target) { + resources = new ArrayList<>(); + resources.add(target); + } + + @Override + public List getCustomQueryOptions() { + fail(); + return null; + } + + @Override + public ExpandOption getExpandOption() { + fail(); + return null; + } + + @Override + public FilterOption getFilterOption() { + return null; + } + + @Override + public FormatOption getFormatOption() { + fail(); + return null; + } + + @Override + public IdOption getIdOption() { + fail(); + return null; + } + + @Override + public CountOption getCountOption() { + fail(); + return null; + } + + @Override + public OrderByOption getOrderByOption() { + fail(); + return null; + } + + @Override + public SearchOption getSearchOption() { + fail(); + return null; + } + + @Override + public SelectOption getSelectOption() { + fail(); + return null; + } + + @Override + public SkipOption getSkipOption() { + fail(); + return null; + } + + @Override + public SkipTokenOption getSkipTokenOption() { + fail(); + return null; + } + + @Override + public TopOption getTopOption() { + fail(); + return null; + } + + @Override + public List getUriResourceParts() { + return resources; + } + + @Override + public String getValueForAlias(String alias) { + fail(); + return null; + } + + @Override + public ApplyOption getApplyOption() { + return null; + } + + @Override + public DeltaTokenOption getDeltaTokenOption() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java new file mode 100644 index 0000000000..2572ed583a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourceNavigationDouble.java @@ -0,0 +1,85 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import java.util.List; + +import org.apache.olingo.commons.api.edm.EdmEntityType; +import org.apache.olingo.commons.api.edm.EdmNavigationProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriParameter; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceNavigation; + +public class UriResourceNavigationDouble implements UriResourceNavigation { + private final EdmType type; + private final EdmNavigationProperty property; + + public UriResourceNavigationDouble(EdmEntityType naviTargetEntity) { + this(naviTargetEntity, null); + } + + public UriResourceNavigationDouble(EdmType type, EdmNavigationProperty property) { + super(); + this.type = type; + this.property = property; + } + + @Override + public EdmType getType() { + return type; + } + + @Override + public boolean isCollection() { + fail(); + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + return UriResourceKind.navigationProperty; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmNavigationProperty getProperty() { + return property; + } + + @Override + public List getKeyPredicates() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnCollection() { + fail(); + return null; + } + + @Override + public EdmType getTypeFilterOnEntry() { + fail(); + return null; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java new file mode 100644 index 0000000000..7df9f874e4 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-processor/src/test/java/com/sap/olingo/jpa/processor/core/util/UriResourcePropertyDouble.java @@ -0,0 +1,59 @@ +package com.sap.olingo.jpa.processor.core.util; + +import static org.junit.jupiter.api.Assertions.fail; + +import org.apache.olingo.commons.api.edm.EdmProperty; +import org.apache.olingo.commons.api.edm.EdmType; +import org.apache.olingo.server.api.uri.UriResourceKind; +import org.apache.olingo.server.api.uri.UriResourceProperty; + +public class UriResourcePropertyDouble implements UriResourceProperty { + private final EdmProperty property; + + public UriResourcePropertyDouble(EdmProperty property) { + super(); + this.property = property; + } + + @Override + public EdmType getType() { + fail(); + return null; + } + + @Override + public boolean isCollection() { + return false; + } + + @Override + public String getSegmentValue(boolean includeFilters) { + fail(); + return null; + } + + @Override + public String toString(boolean includeFilters) { + fail(); + return null; + } + + @Override + public UriResourceKind getKind() { + fail(); + return null; + } + + @Override + public String getSegmentValue() { + fail(); + return null; + } + + @Override + public EdmProperty getProperty() { + + return property; + } + +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java new file mode 100644 index 0000000000..7152324faa --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/main/java/com/sap/olingo/jpa/processor/core/testmodel/AssertCollection.java @@ -0,0 +1,29 @@ +package com.sap.olingo.jpa.processor.core.testmodel; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.apache.commons.lang3.builder.EqualsBuilder; + +public class AssertCollection { + + public static void assertListEquals(final List exp, final List act, Class reflection) { + assertEquals(exp.size(), act.size()); + boolean found; + for (final T expItem : exp) { + for (T actItem : act) { + found = EqualsBuilder.reflectionEquals(expItem, actItem, true, reflection); + if (found) { + break; + } + assertTrue(found, "Cloud not find" + expItem.toString()); + } + } + } + + private AssertCollection() { + super(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java new file mode 100644 index 0000000000..39bf929ade --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestAssociations.java @@ -0,0 +1,163 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.Country; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestAssociations { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private EntityManager em; + private CriteriaBuilder cb; + + @BeforeAll + public static void setupClass() { + Map properties = new HashMap<>(); + properties.put(ENTITY_MANAGER_DATA_SOURCE, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + @BeforeEach + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + @Test + public void getBuPaRoles() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("roles").alias("roles")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + BusinessPartnerRole role = (BusinessPartnerRole) result.get(0).get("roles"); + assertNotNull(role); + } + + @Test + public void getBuPaLocation() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("locationName").alias("L")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivisionDescription act = (AdministrativeDivisionDescription) result.get(0).get("L"); + assertNotNull(act); + } + + @Test + public void getRoleBuPa() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartnerRole.class); + + cq.multiselect(root.get("businessPartner").alias("BuPa")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + BusinessPartner bp = (BusinessPartner) result.get(0).get("BuPa"); + assertNotNull(bp); + } + + @Test + public void getBuPaCountryName() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("address").get("countryName").alias("CN")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + Country region = (Country) result.get(0).get("CN"); + assertNotNull(region); + } + + @Test + public void getBuPaRegionName() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(BusinessPartner.class); + + cq.multiselect(root.get("address").get("regionName").alias("RN")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivisionDescription region = (AdministrativeDivisionDescription) result.get(0).get("RN"); + assertNotNull(region); + } + + @Test + public void getAdministrativeDivisionParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + + cq.multiselect(root.get("parent").alias("P")); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("P"); + assertNotNull(act); + } + + @Test + public void getAdministrativeDivisionOneParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + root.alias("Source"); + cq.multiselect(root.get("parent").alias("P")); + // cq.select((Selection) root); + cq.where(cb.and( + cb.equal(root.get("codePublisher"), "Eurostat"), + cb.and( + cb.equal(root.get("codeID"), "NUTS3"), + cb.equal(root.get("divisionCode"), "BE251")))); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("P"); + assertNotNull(act); + assertEquals("NUTS2", act.getCodeID()); + assertEquals("BE25", act.getDivisionCode()); + } + + @Test + public void getAdministrativeDivisionChildrenOfOneParent() { + CriteriaQuery cq = cb.createTupleQuery(); + Root root = cq.from(AdministrativeDivision.class); + root.alias("Source"); + cq.multiselect(root.get("children").alias("C")); + cq.where(cb.and( + cb.equal(root.get("codePublisher"), "Eurostat"), + cb.and( + cb.equal(root.get("codeID"), "NUTS2"), + cb.equal(root.get("divisionCode"), "BE25")))); + cq.orderBy(cb.desc(root.get("divisionCode"))); + TypedQuery tq = em.createQuery(cq); + List result = tq.getResultList(); + AdministrativeDivision act = (AdministrativeDivision) result.get(0).get("C"); + assertNotNull(act); + assertEquals(8, result.size()); + assertEquals("NUTS3", act.getCodeID()); + assertEquals("BE251", act.getDivisionCode()); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java new file mode 100644 index 0000000000..18e6f4745a --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestCriteriaBuilder.java @@ -0,0 +1,242 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.criteria.Subquery; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescription; +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivisionDescriptionKey; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartner; +import com.sap.olingo.jpa.processor.core.testmodel.BusinessPartnerRole; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; +import com.sap.olingo.jpa.processor.core.testmodel.Organization; +import com.sap.olingo.jpa.processor.core.testmodel.Person; + +public class TestCriteriaBuilder { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private EntityManager em; + private CriteriaBuilder cb; + + @BeforeAll + public static void setupClass() { + Map properties = new HashMap<>(); + properties.put(ENTITY_MANAGER_DATA_SOURCE, DataSourceHelper.createDataSource( + DataSourceHelper.DB_HSQLDB)); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + @BeforeEach + public void setup() { + em = emf.createEntityManager(); + assertNotNull(em); + cb = em.getCriteriaBuilder(); + assertNotNull(cb); + } + + @SuppressWarnings("unchecked") + @Test + public void testSubstringWithExperession() { + CriteriaQuery adminQ = cb.createTupleQuery(); + Root adminRoot1 = adminQ.from(AdministrativeDivisionDescription.class); +// (Expression) cb.sum(jpaOperator.getLeft(), jpaOperator.getRightAsNumber()); +// cb.substring((Expression) (jpaFunction.getParameter(0).get()), start, length); + Path p = adminRoot1.get("name"); + + Expression sum = cb.sum(cb.literal(1), cb.literal(4)); + + adminQ.where(cb.equal(cb.substring((Expression) (p), cb.literal(1), sum), "North")); + adminQ.multiselect(adminRoot1.get("name")); + TypedQuery tq = em.createQuery(adminQ); + tq.getResultList(); + } + + @Disabled // To time consuming + @Test + public void testSubSelect() { + // https://stackoverflow.com/questions/29719321/combining-conditional-expressions-with-and-and-or-predicates-using-the-jpa-c + CriteriaQuery adminQ1 = cb.createTupleQuery(); + Subquery adminQ2 = adminQ1.subquery(Long.class); + Subquery adminQ3 = adminQ2.subquery(Long.class); + Subquery org = adminQ3.subquery(Long.class); + + Root adminRoot1 = adminQ1.from(AdministrativeDivision.class); + Root adminRoot2 = adminQ2.from(AdministrativeDivision.class); + Root adminRoot3 = adminQ3.from(AdministrativeDivision.class); + Root org1 = org.from(Organization.class); + + org.where(cb.and(cb.equal(org1.get("iD"), "3")), createParentOrg(org1, adminRoot3)); + org.select(cb.literal(1L)); + + adminQ3.where(cb.and(createParentAdmin(adminRoot3, adminRoot2), cb.exists(org))); + adminQ3.select(cb.literal(1L)); + + adminQ2.where(cb.and(createParentAdmin(adminRoot2, adminRoot1), cb.exists(adminQ3))); + adminQ2.select(cb.literal(1L)); + + adminQ1.where(cb.exists(adminQ2)); + adminQ1.multiselect(adminRoot1.get("divisionCode")); + + TypedQuery tq = em.createQuery(adminQ1); + tq.getResultList(); + } + + @SuppressWarnings("unchecked") + @Test + public void testSubSelectTopOrderBy() { + // https://stackoverflow.com/questions/9321916/jpa-criteriabuilder-how-to-use-in-comparison-operator + // https://stackoverflow.com/questions/24109412/in-clause-with-a-composite-primary-key-in-jpa-criteria#24265131 + CriteriaQuery roleQ = cb.createTupleQuery(); + Root roleRoot = roleQ.from(BusinessPartnerRole.class); + + Subquery bupaQ = roleQ.subquery(BusinessPartner.class); + @SuppressWarnings("rawtypes") + Root bupaRoot = roleQ.from(BusinessPartner.class); + + bupaQ.select(bupaRoot.get("iD")); +// Expression exp = scheduleRequest.get("createdBy"); +// Predicate predicate = exp.in(myList); +// criteria.where(predicate); + + List ids = new ArrayList<>(); + ids.add("1"); + ids.add("2"); + bupaQ.where(bupaRoot.get("iD").in(ids)); +// bupaQ.select( +// (Expression) cb.construct( +// BusinessPartner.class, +// bupaRoot.get("ID"))); + + // roleQ.where(cb.in(roleRoot.get("businessPartnerID")).value(bupaQ)); + roleQ.where(cb.in(roleRoot.get("businessPartnerID")).value(bupaQ)); + roleQ.multiselect(roleRoot.get("businessPartnerID")); + TypedQuery tq = em.createQuery(roleQ); + tq.getResultList(); + } + + @Test + public void testFilterOnPrimitiveCollectionAttribute() { + CriteriaQuery orgQ = cb.createTupleQuery(); + Root orgRoot = orgQ.from(Organization.class); + orgQ.select(orgRoot.get("iD")); + orgQ.where(cb.like(orgRoot.get("comment"), "%just%")); + TypedQuery tq = em.createQuery(orgQ); + List act = tq.getResultList(); + assertEquals(1, act.size()); + } + + @Test + public void testFilterOnEmbeddedCollectionAttribute() { + CriteriaQuery pQ = cb.createTupleQuery(); + Root pRoot = pQ.from(Person.class); + pQ.select(pRoot.get("iD")); + pQ.where(cb.equal(pRoot.get("inhouseAddress").get("taskID"), "MAIN")); + TypedQuery tq = em.createQuery(pQ); + List act = tq.getResultList(); + assertEquals(1, act.size()); + } + + @Test + public void TestExpandCount() { + CriteriaQuery count = cb.createTupleQuery(); + Root roles = count.from(BusinessPartnerRole.class); + + count.multiselect(roles.get("businessPartnerID"), cb.count(roles).alias("$count")); + count.groupBy(roles.get("businessPartnerID")); + count.orderBy(cb.desc(cb.count(roles))); + TypedQuery tq = em.createQuery(count); + tq.getResultList(); + tq.getFirstResult(); + } + + @Test + public void TestAnd() { + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + + count.multiselect(adminDiv); + Predicate[] restrictions = new Predicate[3]; + restrictions[0] = cb.equal(adminDiv.get("codeID"), "NUTS2"); + restrictions[1] = cb.equal(adminDiv.get("divisionCode"), "BE34"); + restrictions[2] = cb.equal(adminDiv.get("codePublisher"), "Eurostat"); + count.where(cb.and(restrictions)); + TypedQuery tq = em.createQuery(count); + tq.getResultList(); + tq.getFirstResult(); + } + + @Disabled + @Test + public void TestSearchEmbeddedId() { + CriteriaQuery cq = cb.createTupleQuery(); + Root adminDiv = cq.from(AdministrativeDivisionDescription.class); + cq.multiselect(adminDiv); + + Subquery sq = cq.subquery(AdministrativeDivisionDescriptionKey.class); + Root text = sq.from(AdministrativeDivisionDescription.class); + sq.where(cb.function("CONTAINS", Boolean.class, text.get("name"), cb.literal("luettich"))); + Expression exp = text.get("key"); + sq.select(exp); + + cq.where(cb.and(cb.equal(adminDiv.get("key").get("codeID"), "NUTS2"), + cb.in(sq).value(sq))); + TypedQuery tq = em.createQuery(cq); + List act = tq.getResultList(); + System.out.println(act.size()); + } + + @Disabled + @Test + public void TestSearchNoSubquery() { + CriteriaQuery cq = cb.createTupleQuery(); + Root adminDiv = cq.from(AdministrativeDivisionDescription.class); + cq.multiselect(adminDiv); + + // Predicate[] restrictions = new Predicate[2]; + cq.where( + cb.and(cb.equal(cb.conjunction(), + cb.function("CONTAINS", Boolean.class, adminDiv.get("name"), cb.literal("luettich"))), + cb.equal(adminDiv.get("key").get("codeID"), "NUTS2"))); + + TypedQuery tq = em.createQuery(cq); + List act = tq.getResultList(); + System.out.println(act.size()); + } + + private Expression createParentAdmin(Root subQuery, + Root query) { + return cb.and(cb.equal(query.get("codePublisher"), subQuery.get("codePublisher")), + cb.and(cb.equal(query.get("codeID"), subQuery.get("parentCodeID")), + cb.equal(query.get("divisionCode"), subQuery.get("parentDivisionCode")))); + } + + private Predicate createParentOrg(Root org1, Root adminRoot3) { + return cb.and(cb.equal(adminRoot3.get("codePublisher"), org1.get("address").get("regionCodePublisher")), + cb.and(cb.equal(adminRoot3.get("codeID"), org1.get("address").get("regionCodeID")), + cb.equal(adminRoot3.get("divisionCode"), org1.get("address").get("region")))); + } +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java new file mode 100644 index 0000000000..aca427613c --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctions.java @@ -0,0 +1,177 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.ParameterMode; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.StoredProcedureQuery; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.sql.DataSource; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestFunctions { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private static DataSource ds; + + @BeforeAll + public static void setupClass() { + + Map properties = new HashMap<>(); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + + properties.put(ENTITY_MANAGER_DATA_SOURCE, ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + private EntityManager em; + + private CriteriaBuilder cb; + + @BeforeEach + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + @Disabled + @Test + public void TestProcedure() throws SQLException { + StoredProcedureQuery pc = em.createStoredProcedureQuery("\"OLINGO\".\"org.apache.olingo.jpa::Siblings\""); + + pc.registerStoredProcedureParameter("CodePublisher", String.class, ParameterMode.IN); + pc.setParameter("CodePublisher", "Eurostat"); + pc.registerStoredProcedureParameter("CodeID", String.class, ParameterMode.IN); + pc.setParameter("CodeID", "NUTS2"); + pc.registerStoredProcedureParameter("DivisionCode", String.class, ParameterMode.IN); + pc.setParameter("DivisionCode", "BE25"); +// pc.setParameter("CodePublisher", "Eurostat"); +// pc.setParameter("CodeID", "NUTS2"); +// pc.setParameter("DivisionCode", "BE25"); + + Connection conn = ds.getConnection(); + DatabaseMetaData meta = conn.getMetaData(); + ResultSet metaR = meta.getProcedures(conn.getCatalog(), "OLINGO", "%"); + + while (metaR.next()) { + String procedureCatalog = metaR.getString(1); + String procedureSchema = metaR.getString(2); + String procedureName = metaR.getString(3); +// reserved for future use +// reserved for future use +// reserved for future use + String remarks = metaR.getString(7); + Short procedureTYpe = metaR.getShort(8); +// String specificName = metaR.getString(9); + + System.out.println("procedureCatalog=" + procedureCatalog); + System.out.println("procedureSchema=" + procedureSchema); + System.out.println("procedureName=" + procedureName); + System.out.println("remarks=" + remarks); + System.out.println("procedureType=" + procedureTYpe); +// System.out.println("specificName=" + specificName); + } + ResultSet rs = meta.getProcedureColumns(conn.getCatalog(), + "OLINGO", "%", "%"); + + while (rs.next()) { + // get stored procedure metadata + String procedureCatalog = rs.getString(1); + String procedureSchema = rs.getString(2); + String procedureName = rs.getString(3); + String columnName = rs.getString(4); + short columnReturn = rs.getShort(5); + int columnDataType = rs.getInt(6); + String columnReturnTypeName = rs.getString(7); + int columnPrecision = rs.getInt(8); + int columnByteLength = rs.getInt(9); + short columnScale = rs.getShort(10); + short columnRadix = rs.getShort(11); + short columnNullable = rs.getShort(12); + String columnRemarks = rs.getString(13); + + System.out.println("stored Procedure name=" + procedureName); + System.out.println("procedureCatalog=" + procedureCatalog); + System.out.println("procedureSchema=" + procedureSchema); + System.out.println("procedureName=" + procedureName); + System.out.println("columnName=" + columnName); + System.out.println("columnReturn=" + columnReturn); + System.out.println("columnDataType=" + columnDataType); + System.out.println("columnReturnTypeName=" + columnReturnTypeName); + System.out.println("columnPrecision=" + columnPrecision); + System.out.println("columnByteLength=" + columnByteLength); + System.out.println("columnScale=" + columnScale); + System.out.println("columnRadix=" + columnRadix); + System.out.println("columnNullable=" + columnNullable); + System.out.println("columnRemarks=" + columnRemarks); + } + conn.close(); + pc.execute(); + List r = pc.getResultList(); + + Object[] one = (Object[]) r.get(0); + assertNotNull(one); + } + + @Disabled + @Test + public void TestScalarFunctionsWhere() { + CreateUDFDerby(); + + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + count.multiselect(adminDiv); + count.where(cb.equal( + cb.function("IS_PRIME", boolean.class, cb.literal(5)), + new Boolean(true))); + // cb.literal + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + assertNotNull(act); + tq.getFirstResult(); + } + + private void CreateUDFDerby() { + EntityTransaction t = em.getTransaction(); + + StringBuffer dropString = new StringBuffer("DROP FUNCTION IS_PRIME"); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("CREATE FUNCTION IS_PRIME(number Integer) RETURNS Integer "); + sqlString.append("PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA "); + sqlString.append("EXTERNAL NAME 'com.sap.olingo.jpa.processor.core.test_udf.isPrime'"); + + t.begin(); + Query d = em.createNativeQuery(dropString.toString()); + Query q = em.createNativeQuery(sqlString.toString()); + d.executeUpdate(); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java new file mode 100644 index 0000000000..b9f76d23c8 --- /dev/null +++ b/src/test/resources/oracle/commits/olingo-jpa-processor-v4-5e77141293d32b015a92e48d099195840f2b2e87/jpa/odata-jpa-test/src/test/java/com/sap/olingo/jpa/processor/test/TestFunctionsHSQLDB.java @@ -0,0 +1,95 @@ +package com.sap.olingo.jpa.processor.test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.Tuple; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.sql.DataSource; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sap.olingo.jpa.processor.core.testmodel.AdministrativeDivision; +import com.sap.olingo.jpa.processor.core.testmodel.DataSourceHelper; + +public class TestFunctionsHSQLDB { + protected static final String PUNIT_NAME = "com.sap.olingo.jpa"; + private static final String ENTITY_MANAGER_DATA_SOURCE = "javax.persistence.nonJtaDataSource"; + private static EntityManagerFactory emf; + private static DataSource ds; + + @BeforeAll + public static void setupClass() { + + Map properties = new HashMap<>(); + + ds = DataSourceHelper.createDataSource(DataSourceHelper.DB_HSQLDB); + + properties.put(ENTITY_MANAGER_DATA_SOURCE, ds); + emf = Persistence.createEntityManagerFactory(PUNIT_NAME, properties); + } + + private EntityManager em; + + private CriteriaBuilder cb; + + @BeforeEach + public void setup() { + em = emf.createEntityManager(); + cb = em.getCriteriaBuilder(); + } + + // @Ignore + @Test + public void TestScalarFunctionsWhere() { + CreateUDFHSQLDB(); + + CriteriaQuery count = cb.createTupleQuery(); + Root adminDiv = count.from(AdministrativeDivision.class); + count.multiselect(adminDiv); + + count.where(cb.and(cb.greaterThan( + // + cb.function("PopulationDensity", Integer.class, adminDiv.get("area"), adminDiv.get("population")), + new Integer(60))), cb.equal(adminDiv.get("countryCode"), cb.literal("BEL"))); + // cb.literal + TypedQuery tq = em.createQuery(count); + List act = tq.getResultList(); + assertNotNull(act); + tq.getFirstResult(); + } + + private void CreateUDFHSQLDB() { + EntityTransaction t = em.getTransaction(); + + // StringBuffer dropString = new StringBuffer("DROP FUNCTION PopulationDensity"); + + StringBuffer sqlString = new StringBuffer(); + + sqlString.append("CREATE FUNCTION PopulationDensity (area INT, population BIGINT ) "); + sqlString.append("RETURNS INT "); + sqlString.append("IF area <= 0 THEN RETURN 0;"); + sqlString.append("ELSE RETURN population / area; "); + sqlString.append("END IF"); + + t.begin(); + // Query d = em.createNativeQuery(dropString.toString()); + Query q = em.createNativeQuery(sqlString.toString()); + // d.executeUpdate(); + q.executeUpdate(); + t.commit(); + } +} diff --git a/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.json b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.json new file mode 100644 index 0000000000..1de2f3c50d --- /dev/null +++ b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331.json @@ -0,0 +1 @@ +{"parentCommitId":"79abd64b338caa1f9e03e768da19c08ea0bb7e38","currentCommitId":"4312eb178b6cb000ea8a3c78df70567182341331","filesBefore":["plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java"],"filesCurrent":["plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["plc4j/core/src","plc4j","plc4j/protocols/s7/src/test/java","plc4j/protocols/s7/src/test/java/org/apache/plc4x","plc4j/core/src/test/java/org/apache","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java","plc4j/core/src/test/java/org/apache/plc4x/java","plc4j/protocols/s7/src","plc4j/protocols/s7","plc4j/core/src/test","plc4j/protocols","plc4j/protocols/s7/src/test","plc4j/core","plc4j/protocols/s7/src/test/java/org","plc4j/core/src/test/java","plc4j/core/src/test/java/org","plc4j/protocols/s7/src/test/java/org/apache","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7","plc4j/core/src/test/java/org/apache/plc4x"],"repositoryDirectoriesCurrent":["plc4j/core/src","plc4j","plc4j/protocols/s7/src/test/java","plc4j/protocols/s7/src/test/java/org/apache/plc4x","plc4j/core/src/test/java/org/apache","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java","plc4j/core/src/test/java/org/apache/plc4x/java","plc4j/protocols/s7/src","plc4j/protocols/s7","plc4j/core/src/test","plc4j/protocols","plc4j/protocols/s7/src/test","plc4j/core","plc4j/protocols/s7/src/test/java/org","plc4j/core/src/test/java","plc4j/core/src/test/java/org","plc4j/protocols/s7/src/test/java/org/apache","plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7","plc4j/core/src/test/java/org/apache/plc4x"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java new file mode 100644 index 0000000000..cb9bd55e94 --- /dev/null +++ b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java @@ -0,0 +1,98 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ +package org.apache.plc4x.java; + +import org.apache.plc4x.java.authentication.PlcUsernamePasswordAuthentication; +import org.apache.plc4x.java.exceptions.PlcConnectionException; +import org.apache.plc4x.java.exceptions.PlcException; +import org.apache.plc4x.java.mock.MockConnection; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; + +class PlcDriverManagerTest { + + /** + * Tries to get the mock plc driver which is part of this testsuite. + */ + @Test + @Tag("fast") + void getExistingDriverTest() throws PlcException { + MockConnection mockConnection = (MockConnection) new PlcDriverManager().getConnection("mock://some-cool-url"); + Assertions.assertNull(mockConnection.getAuthentication()); + } + + /** + * Tries to get the mock plc driver with authentication which is part of this testsuite. + */ + @Test + @Tag("fast") + void getExistingDriverWithAuthenticationTest() throws PlcException { + PlcUsernamePasswordAuthentication authentication = + new PlcUsernamePasswordAuthentication("user", "pass"); + MockConnection mockConnection = (MockConnection) new PlcDriverManager().getConnection("mock://some-cool-url", authentication); + Assertions.assertNotNull(mockConnection.getAuthentication()); + Assertions.assertTrue(mockConnection.getAuthentication() instanceof PlcUsernamePasswordAuthentication); + } + + /** + * In this test case a driver is requested which is not registered with the {@link PlcDriverManager}. + */ + @Test + @Tag("fast") + void getNotExistingDriverTest() throws PlcException { + Assertions.assertThrows(PlcConnectionException.class, + () -> new PlcDriverManager().getConnection("non-existing-protocol://some-cool-url")); + } + + /** + * In this test case a driver is requested which is not registered with the {@link PlcDriverManager}. + */ + @Test + @Tag("fast") + void getInvalidUriTest() throws PlcException { + Assertions.assertThrows(PlcConnectionException.class, + () -> new PlcDriverManager().getConnection("The quick brown fox jumps over the lazy dog")); + } + + /** + * In this test the {@link PlcDriverManager} will be configured with a service list that + * contains multiple implementation instances of the same protocol. This should result in + * an error. + */ + @Test + @Tag("fast") + void getDuplicateDriver() throws PlcException, MalformedURLException { + // Save and replace the context classloader as we need to force the ServiceLoader to + // use a different service file. + ClassLoader originalClassloader = Thread.currentThread().getContextClassLoader(); + URL[] urls = new URL[1]; + urls[0] = new File("src/test/resources/test").toURI().toURL(); + ClassLoader fakeClassLoader = new URLClassLoader(urls, originalClassloader); + + Assertions.assertThrows(IllegalStateException.class, + () -> new PlcDriverManager(fakeClassLoader).getConnection("mock://some-cool-url")); + } + +} diff --git a/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java new file mode 100644 index 0000000000..0de0303464 --- /dev/null +++ b/src/test/resources/oracle/commits/plc4x-4312eb178b6cb000ea8a3c78df70567182341331/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java @@ -0,0 +1,142 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ +package org.apache.plc4x.java.s7; + + +import org.apache.plc4x.java.PlcDriverManager; +import org.apache.plc4x.java.authentication.PlcUsernamePasswordAuthentication; +import org.apache.plc4x.java.connection.PlcConnection; +import org.apache.plc4x.java.connection.PlcReader; +import org.apache.plc4x.java.exceptions.PlcConnectionException; +import org.apache.plc4x.java.exceptions.PlcException; +import org.apache.plc4x.java.messages.Address; +import org.apache.plc4x.java.messages.PlcSimpleReadRequest; +import org.apache.plc4x.java.messages.PlcSimpleReadResponse; +import org.apache.plc4x.java.s7.connection.S7PlcConnection; +import org.apache.plc4x.java.types.ByteValue; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.Calendar; +import java.util.concurrent.CompletableFuture; + +class S7PlcDriverTest { + + @Test + @Tag("fast") + void getConnectionTest() throws PlcException { + S7PlcConnection s7Connection = (S7PlcConnection) + new PlcDriverManager().getConnection("s7://localhost/1/2"); + Assertions.assertEquals(s7Connection.getHostName(), "localhost"); + Assertions.assertEquals(s7Connection.getRack(), 1); + Assertions.assertEquals(s7Connection.getSlot(), 2); + } + + /** + * In this test case the 's7' driver should report an invalid url format. + * + * @throws PlcException something went wrong + */ + @Test + @Tag("fast") + void getConnectionInvalidUrlTest() throws PlcException { + Assertions.assertThrows(PlcConnectionException.class, + () -> new PlcDriverManager().getConnection("s7://localhost/hurz/2")); + } + + /** + * In this test case the 's7' driver should report an error as this protocol + * doesn't support authentication. + * + * @throws PlcException something went wrong + */ + @Test + @Tag("fast") + void getConnectionWithAuthenticationTest() throws PlcException { + Assertions.assertThrows(PlcConnectionException.class, + () -> new PlcDriverManager().getConnection("s7://localhost/1/2", + new PlcUsernamePasswordAuthentication("user", "pass"))); + } + + /** + * Example code do demonstrate using the S7 Plc Driver. + * + * @param args ignored. + * @throws Exception something went wrong. + */ + public static void main(String[] args) throws Exception { + try { + // Create a connection to the S7 PLC (s7://{hostname/ip}/{racknumber}/{slotnumber}) + PlcConnection plcConnection = new PlcDriverManager().getConnection("s7://192.168.0.1/0/0"); + plcConnection.connect(); + + // Check if this connection support reading of data. + if (plcConnection instanceof PlcReader) { + PlcReader plcReader = (PlcReader) plcConnection; + + // Prepare some address object for accessing fields in the PLC. + // ({memory-area}/{byte-offset}[/{bit-offset}] + // "bit-offset is only specified if the requested type is "bit" + // NOTICE: This format is probably only valid when using a S7 connection. + Address inputs = plcConnection.parseAddress("INPUTS/0"); + Address outputs = plcConnection.parseAddress("OUTPUTS/0"); + + ////////////////////////////////////////////////////////// + // Read synchronously ... + // NOTICE: the ".get()" immediately lets this thread pause till + // the response is processed and available. + PlcSimpleReadResponse plcReadResponse = plcReader.read( + new PlcSimpleReadRequest<>(ByteValue.class, inputs)).get(); + ByteValue data = plcReadResponse.getValue(); + System.out.println("Inputs: " + data.getValue()); + + ////////////////////////////////////////////////////////// + // Read asynchronously ... + Calendar start = Calendar.getInstance(); + CompletableFuture> asyncResponse = plcReader.read( + new PlcSimpleReadRequest<>(ByteValue.class, outputs)); + + // Simulate doing something else ... + System.out.println("Processing: "); + while (true) { + // I had to make sleep this small or it would have printed only one "." + // On my system the average response time with a siemens s7-1200 was 5ms. + Thread.sleep(1); + System.out.print("."); + if (asyncResponse.isDone()) { + break; + } + } + System.out.println(); + + Calendar end = Calendar.getInstance(); + plcReadResponse = asyncResponse.get(); + data = plcReadResponse.getValue(); + System.out.println("Outputs: " + data.getValue() + " (in " + (end.getTimeInMillis() - start.getTimeInMillis()) + "ms)"); + } + } + // Catch any exception or the application won't be able to finish if something goes wrong. + catch (Exception e) { + e.printStackTrace(); + } + System.exit(0); + } + +} diff --git a/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java b/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java new file mode 100644 index 0000000000..8a62470a20 --- /dev/null +++ b/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/core/src/test/java/org/apache/plc4x/java/PlcDriverManagerTest.java @@ -0,0 +1,88 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ +package org.apache.plc4x.java; + +import org.apache.plc4x.java.authentication.PlcUsernamePasswordAuthentication; +import org.apache.plc4x.java.exceptions.PlcConnectionException; +import org.apache.plc4x.java.exceptions.PlcException; +import org.apache.plc4x.java.mock.MockConnection; +import org.junit.Assert; +import org.testng.annotations.Test; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; + +public class PlcDriverManagerTest { + + /** + * Tries to get the mock plc driver which is part of this testsuite. + */ + @Test(groups = { "fast" }) + public void getExistingDriverTest() throws PlcException { + MockConnection mockConnection = (MockConnection) new PlcDriverManager().getConnection("mock://some-cool-url"); + Assert.assertNull(mockConnection.getAuthentication()); + } + + /** + * Tries to get the mock plc driver with authentication which is part of this testsuite. + */ + @Test(groups = { "fast" }) + public void getExistingDriverWithAuthenticationTest() throws PlcException { + PlcUsernamePasswordAuthentication authentication = + new PlcUsernamePasswordAuthentication("user", "pass"); + MockConnection mockConnection = (MockConnection) new PlcDriverManager().getConnection("mock://some-cool-url", authentication); + Assert.assertNotNull(mockConnection.getAuthentication()); + Assert.assertTrue(mockConnection.getAuthentication() instanceof PlcUsernamePasswordAuthentication); + } + + /** + * In this test case a driver is requested which is not registered with the {@link PlcDriverManager}. + */ + @Test(groups = { "fast" }, expectedExceptions = {PlcConnectionException.class}) + public void getNotExistingDriverTest() throws PlcException { + new PlcDriverManager().getConnection("non-existing-protocol://some-cool-url"); + } + + /** + * In this test case a driver is requested which is not registered with the {@link PlcDriverManager}. + */ + @Test(groups = { "fast" }, expectedExceptions = {PlcConnectionException.class}) + public void getInvalidUriTest() throws PlcException { + new PlcDriverManager().getConnection("The quick brown fox jumps over the lazy dog"); + } + + /** + * In this test the {@link PlcDriverManager} will be configured with a service list that + * contains multiple implementation instances of the same protocol. This should result in + * an error. + */ + @Test(groups = { "fast" }, expectedExceptions = {IllegalStateException.class}) + public void getDuplicateDriver() throws PlcException, MalformedURLException { + // Save and replace the context classloader as we need to force the ServiceLoader to + // use a different service file. + ClassLoader originalClassloader = Thread.currentThread().getContextClassLoader(); + URL[] urls = new URL[1]; + urls[0] = new File("src/test/resources/test").toURI().toURL(); + ClassLoader fakeClassLoader = new URLClassLoader(urls, originalClassloader); + new PlcDriverManager(fakeClassLoader).getConnection("mock://some-cool-url"); + } + +} diff --git a/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java b/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java new file mode 100644 index 0000000000..b316b47606 --- /dev/null +++ b/src/test/resources/oracle/commits/plc4x-79abd64b338caa1f9e03e768da19c08ea0bb7e38/plc4j/protocols/s7/src/test/java/org/apache/plc4x/java/s7/S7PlcDriverTest.java @@ -0,0 +1,136 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ +package org.apache.plc4x.java.s7; + + +import org.apache.plc4x.java.PlcDriverManager; +import org.apache.plc4x.java.authentication.PlcUsernamePasswordAuthentication; +import org.apache.plc4x.java.connection.PlcConnection; +import org.apache.plc4x.java.connection.PlcReader; +import org.apache.plc4x.java.exceptions.PlcConnectionException; +import org.apache.plc4x.java.exceptions.PlcException; +import org.apache.plc4x.java.messages.Address; +import org.apache.plc4x.java.messages.PlcSimpleReadRequest; +import org.apache.plc4x.java.messages.PlcSimpleReadResponse; +import org.apache.plc4x.java.s7.connection.S7PlcConnection; +import org.apache.plc4x.java.types.ByteValue; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Calendar; +import java.util.concurrent.CompletableFuture; + +public class S7PlcDriverTest { + + @Test(groups = {"fast"}) + public void getConnectionTest() throws PlcException { + S7PlcConnection s7Connection = (S7PlcConnection) + new PlcDriverManager().getConnection("s7://localhost/1/2"); + Assert.assertEquals(s7Connection.getHostName(), "localhost"); + Assert.assertEquals(s7Connection.getRack(), 1); + Assert.assertEquals(s7Connection.getSlot(), 2); + } + + /** + * In this test case the 's7' driver should report an invalid url format. + * + * @throws PlcException something went wrong + */ + @Test(groups = {"fast"}, expectedExceptions = {PlcConnectionException.class}) + public void getConnectionInvalidUrlTest() throws PlcException { + new PlcDriverManager().getConnection("s7://localhost/hurz/2"); + } + + /** + * In this test case the 's7' driver should report an error as this protocol + * doesn't support authentication. + * + * @throws PlcException something went wrong + */ + @Test(groups = {"fast"}, expectedExceptions = {PlcConnectionException.class}) + public void getConnectionWithAuthenticationTest() throws PlcException { + new PlcDriverManager().getConnection("s7://localhost/1/2", + new PlcUsernamePasswordAuthentication("user", "pass")); + } + + /** + * Example code do demonstrate using the S7 Plc Driver. + * + * @param args ignored. + * @throws Exception something went wrong. + */ + public static void main(String[] args) throws Exception { + try { + // Create a connection to the S7 PLC (s7://{hostname/ip}/{racknumber}/{slotnumber}) + PlcConnection plcConnection = new PlcDriverManager().getConnection("s7://192.168.0.1/0/0"); + plcConnection.connect(); + + // Check if this connection support reading of data. + if (plcConnection instanceof PlcReader) { + PlcReader plcReader = (PlcReader) plcConnection; + + // Prepare some address object for accessing fields in the PLC. + // ({memory-area}/{byte-offset}[/{bit-offset}] + // "bit-offset is only specified if the requested type is "bit" + // NOTICE: This format is probably only valid when using a S7 connection. + Address inputs = plcConnection.parseAddress("INPUTS/0"); + Address outputs = plcConnection.parseAddress("OUTPUTS/0"); + + ////////////////////////////////////////////////////////// + // Read synchronously ... + // NOTICE: the ".get()" immediately lets this thread pause till + // the response is processed and available. + PlcSimpleReadResponse plcReadResponse = plcReader.read( + new PlcSimpleReadRequest<>(ByteValue.class, inputs)).get(); + ByteValue data = plcReadResponse.getValue(); + System.out.println("Inputs: " + data.getValue()); + + ////////////////////////////////////////////////////////// + // Read asynchronously ... + Calendar start = Calendar.getInstance(); + CompletableFuture> asyncResponse = plcReader.read( + new PlcSimpleReadRequest<>(ByteValue.class, outputs)); + + // Simulate doing something else ... + System.out.println("Processing: "); + while (true) { + // I had to make sleep this small or it would have printed only one "." + // On my system the average response time with a siemens s7-1200 was 5ms. + Thread.sleep(1); + System.out.print("."); + if (asyncResponse.isDone()) { + break; + } + } + System.out.println(); + + Calendar end = Calendar.getInstance(); + plcReadResponse = asyncResponse.get(); + data = plcReadResponse.getValue(); + System.out.println("Outputs: " + data.getValue() + " (in " + (end.getTimeInMillis() - start.getTimeInMillis()) + "ms)"); + } + } + // Catch any exception or the application won't be able to finish if something goes wrong. + catch (Exception e) { + e.printStackTrace(); + } + System.exit(0); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.json b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.json new file mode 100644 index 0000000000..6b0196ce22 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998.json @@ -0,0 +1 @@ +{"parentCommitId":"2de9405d52b0626569e411b59ff8deb4e73bb3b6","currentCommitId":"1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998","filesBefore":["jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java","jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java","jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java","jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java","jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java","jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java","problem/src/test/java/org/zalando/problem/DefaultProblemTest.java","problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java","problem/src/test/java/org/zalando/problem/ExceptionalTest.java","problem/src/test/java/org/zalando/problem/GenericProblemsTest.java","problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java","problem/src/test/java/org/zalando/problem/MoreStatusTest.java","problem/src/test/java/org/zalando/problem/OutOfStockProblem.java","problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java","problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java","problem/src/test/java/org/zalando/problem/ProblemTest.java","problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java"],"filesCurrent":["jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java","jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java","jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java","jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java","jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java","jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java","problem/src/test/java/org/zalando/problem/DefaultProblemTest.java","problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java","problem/src/test/java/org/zalando/problem/ExceptionalTest.java","problem/src/test/java/org/zalando/problem/GenericProblemsTest.java","problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java","problem/src/test/java/org/zalando/problem/MoreStatusTest.java","problem/src/test/java/org/zalando/problem/OutOfStockProblem.java","problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java","problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java","problem/src/test/java/org/zalando/problem/ProblemTest.java","problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["jackson-datatype-problem","jackson-datatype-problem/src/test","jackson-datatype-problem/src","problem/src/test/java/org","problem/src","problem/src/test","jackson-datatype-problem/src/test/java/org/zalando","jackson-datatype-problem/src/test/java","problem/src/test/java","problem","jackson-datatype-problem/src/test/java/org","problem/src/test/java/org/zalando","jackson-datatype-problem/src/test/java/org/zalando/problem","problem/src/test/java/org/zalando/problem"],"repositoryDirectoriesCurrent":["jackson-datatype-problem","jackson-datatype-problem/src/test","jackson-datatype-problem/src","problem/src/test/java/org","problem/src","problem/src/test","jackson-datatype-problem/src/test/java/org/zalando","jackson-datatype-problem/src/test/java","problem/src/test/java","problem","jackson-datatype-problem/src/test/java/org","problem/src/test/java/org/zalando","jackson-datatype-problem/src/test/java/org/zalando/problem","problem/src/test/java/org/zalando/problem"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java new file mode 100644 index 0000000000..ddbcb1455f --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java @@ -0,0 +1,9 @@ +package org.zalando.problem; + +abstract class BusinessException extends Exception { + + BusinessException(final String message) { + super(message); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java new file mode 100644 index 0000000000..59f223decf --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java @@ -0,0 +1,31 @@ +package org.zalando.problem; + +import com.google.gag.annotation.remark.Hack; +import com.google.gag.annotation.remark.OhNoYouDidnt; +import org.junit.jupiter.api.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Hack +@OhNoYouDidnt +final class EnforceCoverageTest { + + @Test + void shouldUseMixinConstructor() { + assertThrows(AbstractThrowableProblem.class, () -> { + new AbstractThrowableProblemMixIn(URI.create("https://example.org"), "Bad Request", BAD_REQUEST, null, null, + null) { + + @Override + void set(final String key, final Object value) { + + } + + }; + }); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java new file mode 100644 index 0000000000..184cc12635 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java @@ -0,0 +1,37 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@JsonTypeName(InsufficientFundsProblem.TYPE_VALUE) +public final class InsufficientFundsProblem extends AbstractThrowableProblem { + + static final String TYPE_VALUE = "https://example.org/insufficient-funds"; + private static final URI TYPE = URI.create(TYPE_VALUE); + + private final int balance; + private final int debit; + + @JsonCreator + public InsufficientFundsProblem( + @JsonProperty("balance") final int balance, + @JsonProperty("debit") final int debit) { + super(TYPE, "Insufficient Funds", BAD_REQUEST); + this.balance = balance; + this.debit = debit; + } + + int getBalance() { + return balance; + } + + int getDebit() { + return debit; + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java new file mode 100644 index 0000000000..968c68987d --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java @@ -0,0 +1,48 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import javax.ws.rs.core.Response; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@JsonTypeName(OutOfStockException.TYPE_NAME) +public class OutOfStockException extends BusinessException implements Exceptional { + + static final String TYPE_NAME = "https://example.org/out-of-stock"; + private static final URI TYPE = URI.create(TYPE_NAME); + + @JsonCreator + public OutOfStockException(@JsonProperty("detail") final String detail) { + super(detail); + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Out of Stock"; + } + + @Override + public Response.StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public String getDetail() { + return getMessage(); + } + + @Override + public ThrowableProblem getCause() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java new file mode 100644 index 0000000000..8ba5051951 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java @@ -0,0 +1,265 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Response.Status.Family; +import javax.ws.rs.core.Response.StatusType; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Objects; + +import static com.jayway.jsonassert.JsonAssert.with; +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.hamcrest.MatcherAssert.assertThat; + +final class ProblemMixInTest { + + private final ObjectMapper mapper = new ObjectMapper() + .registerModule(new ProblemModule()); + + ProblemMixInTest() { + mapper.registerSubtypes(InsufficientFundsProblem.class); + mapper.registerSubtypes(OutOfStockException.class); + } + + @Test + void shouldSerializeDefaultProblem() throws JsonProcessingException { + final Problem problem = Problem.valueOf(Status.NOT_FOUND); + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.*", hasSize(2)) + .assertThat("$.title", is("Not Found")) + .assertThat("$.status", is(404)); + } + + @Test + void shouldSerializeCustomProperties() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("https://example.org/out-of-stock")) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withDetail("Item B00027Y5QG is no longer available") + .with("product", "B00027Y5QG") + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.*", hasSize(5)) + .assertThat("$.product", is("B00027Y5QG")); + } + + @Test + void shouldSerializeProblemCause() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .withDetail("Credit card is expired as of 2015-09-16T00:00:00Z") + .with("since", "2015-09-16T00:00:00Z") + .build()) + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.cause.type", is("https://example.org/expired-credit-card")) + .assertThat("$.cause.title", is("Expired Credit Card")) + .assertThat("$.cause.status", is(400)) + .assertThat("$.cause.detail", is("Credit card is expired as of 2015-09-16T00:00:00Z")) + .assertThat("$.cause.since", is("2015-09-16T00:00:00Z")); + } + + @Test + void shouldNotSerializeStacktraceByDefault() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Foo") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Bar") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertNotDefined("$.stacktrace"); + } + + @Test + void shouldSerializeStacktrace() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Foo") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Bar") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final ObjectMapper mapper = new ObjectMapper() + .registerModule(new ProblemModule().withStackTraces()); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.stacktrace", is(instanceOf(List.class))) + .assertThat("$.stacktrace[0]", is(instanceOf(String.class))); + } + + @Test + void shouldDeserializeDefaultProblem() throws IOException { + final URL resource = getResource("default.json"); + final Problem raw = mapper.readValue(resource, Problem.class); + + assertThat(raw, instanceOf(DefaultProblem.class)); + final DefaultProblem problem = (DefaultProblem) raw; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/not-out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + assertThat(problem, hasFeature("parameters", DefaultProblem::getParameters, hasEntry("product", "B00027Y5QG"))); + } + + @Test + void shouldDeserializeRegisteredExceptional() throws IOException { + final URL resource = getResource("out-of-stock.json"); + final Exceptional exceptional = mapper.readValue(resource, Exceptional.class); + + assertThat(exceptional, instanceOf(OutOfStockException.class)); + final OutOfStockException problem = (OutOfStockException) exceptional; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + void shouldDeserializeUnregisteredExceptional() throws IOException { + final URL resource = getResource("out-of-stock.json"); + final Exceptional exceptional = mapper.readValue(resource, IOProblem.class); + + assertThat(exceptional, instanceOf(IOProblem.class)); + final IOProblem problem = (IOProblem) exceptional; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + void shouldDeserializeSpecificProblem() throws IOException { + final URL resource = getResource("insufficient-funds.json"); + final InsufficientFundsProblem problem = (InsufficientFundsProblem) mapper.readValue(resource, Problem.class); + + assertThat(problem, hasFeature("balance", InsufficientFundsProblem::getBalance, equalTo(10))); + assertThat(problem, hasFeature("debit", InsufficientFundsProblem::getDebit, equalTo(-20))); + } + + @Test + void shouldDeserializeUnknownStatus() throws IOException { + final URL resource = getResource("unknown.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + final StatusType status = problem.getStatus(); + + assertThat(status, hasFeature("status code", StatusType::getStatusCode, equalTo(666))); + assertThat(status, hasFeature("family", StatusType::getFamily, equalTo(Family.OTHER))); + assertThat(status, hasFeature("reason phrase", StatusType::getReasonPhrase, equalTo("Unknown"))); + } + + @Test + void shouldDeserializeUntyped() throws IOException { + final URL resource = getResource("untyped.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + assertThat(problem.getType(), hasToString("about:blank")); + assertThat(problem.getTitle(), is("Something bad")); + assertThat(problem.getStatus(), hasFeature(StatusType::getStatusCode, is(400))); + assertThat(problem.getDetail(), is(nullValue())); + assertThat(problem.getInstance(), is(nullValue())); + } + + @Test + void shouldDeserializeEmpty() throws IOException { + final URL resource = getResource("empty.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + assertThat(problem.getType(), hasToString("about:blank")); + assertThat(problem.getTitle(), is(nullValue())); + assertThat(problem.getStatus(), is(nullValue())); + assertThat(problem.getDetail(), is(nullValue())); + assertThat(problem.getInstance(), is(nullValue())); + } + + @Test + void shouldDeserializeCause() throws IOException { + final URL resource = getResource("cause.json"); + final ThrowableProblem problem = mapper.readValue(resource, ThrowableProblem.class); + + assertThat(problem, hasFeature("cause", Throwable::getCause, is(notNullValue()))); + final DefaultProblem cause = (DefaultProblem) problem.getCause(); + + assertThat(cause, is(notNullValue())); + assertThat(cause, instanceOf(DefaultProblem.class)); + + assertThat(cause, hasFeature("type", Problem::getType, hasToString("https://example.org/expired-credit-card"))); + assertThat(cause, hasFeature("title", Problem::getTitle, equalTo("Expired Credit Card"))); + assertThat(cause, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(cause, hasFeature("detail", Problem::getDetail, is("Credit card is expired as of 2015-09-16T00:00:00Z"))); + assertThat(cause, hasFeature("parameters", Problem::getParameters, hasEntry("since", "2015-09-16T00:00:00Z"))); + } + + @Test + void shouldDeserializeWithProcessedStackTrace() throws IOException { + final URL resource = getResource("cause.json"); + final ThrowableProblem problem = mapper.readValue(resource, ThrowableProblem.class); + + final String stackTrace = getStackTrace(problem); + final String[] stackTraceElements = stackTrace.split("\n"); + + assertThat(stackTraceElements[1], startsWith("\tat org.zalando.problem.ProblemMixInTest")); + } + + private String getStackTrace(final Throwable throwable) { + final StringWriter writer = new StringWriter(); + throwable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } + + private static URL getResource(final String name) { + final ClassLoader loader = Thread.currentThread().getContextClassLoader(); + return Objects.requireNonNull(loader.getResource(name), () -> "resource " + name + " not found."); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java new file mode 100644 index 0000000000..5a8ec516a6 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java @@ -0,0 +1,21 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response.Status; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +final class ProblemModuleTest { + + @Test + void defaultConstructorShouldBuildIndexCorrectly() { + new ProblemModule(); + } + + @Test + void shouldThrowForDuplicateStatusCode() { + assertThrows(IllegalArgumentException.class, () -> new ProblemModule(Status.class, CustomStatus.class)); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java new file mode 100644 index 0000000000..5d6c7b723d --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java @@ -0,0 +1,45 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; + +@SuppressWarnings("ConstantConditions") +final class DefaultProblemTest { + + private final URI type = URI.create("https://example.org/out-of-stock"); + + @Test + void shouldDefaultToAboutBlank() { + final DefaultProblem problem = new DefaultProblem(null, null, null, null, null, null); + assertThat(problem.getType(), hasToString("about:blank")); + } + + @Test + void shouldImplementProblem() { + final DefaultProblem problem = new DefaultProblem(type, "Out of Stock", BAD_REQUEST, + "Item B00027Y5QG is no longer available", + URI.create("https://example.org/e7203fd2-463b-11e5-a823-10ddb1ee7671"), + null); + + problem.set("foo", "bar"); + + assertThat(problem, hasFeature("type", Problem::getType, equalTo(type))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, + is("Item B00027Y5QG is no longer available"))); + assertThat(problem, hasFeature("instance", Problem::getInstance, + hasToString("https://example.org/e7203fd2-463b-11e5-a823-10ddb1ee7671"))); + assertThat(problem, hasFeature(DefaultProblem::getParameters, hasEntry("foo", "bar"))); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java new file mode 100644 index 0000000000..c4267dbc3c --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java @@ -0,0 +1,53 @@ +package org.zalando.problem; + +import com.google.gag.annotation.remark.Hack; +import com.google.gag.annotation.remark.OhNoYouDidnt; +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Hack +@OhNoYouDidnt +class EnforceCoverageTest { + + @Test + void shouldCoverUnreachableThrowStatement() throws Exception { + assertThrows(FakeProblem.class, () -> { + throw new FakeProblem().propagate(); + }); + } + + static final class FakeProblem extends Exception implements Exceptional { + + @Override + public URI getType() { + return URI.create("about:blank"); + } + + @Override + public String getTitle() { + return "Fake"; + } + + @Override + public Response.StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public ThrowableProblem getCause() { + return null; + } + + @Override + public X propagateAs(final Class type) throws X { + return type.cast(this); + } + + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ExceptionalTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ExceptionalTest.java new file mode 100644 index 0000000000..d893339171 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ExceptionalTest.java @@ -0,0 +1,29 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.jupiter.api.Assertions.fail; + +final class ExceptionalTest { + + @Test + void shouldBeAbleToThrowAndCatchThrowableProblem() { + try { + throw unit().propagate(); + } catch (final InsufficientFundsProblem problem) { + assertThat(problem, hasFeature("balance", InsufficientFundsProblem::getBalance, equalTo(10))); + } catch (final OutOfStockProblem problem) { + fail("Should not have been out-of-stock"); + } catch (final Exception e) { + fail("Should not have been unspecific problem"); + } + } + + private Exceptional unit() { + return new InsufficientFundsProblem(10, -20); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java new file mode 100644 index 0000000000..d649d39251 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java @@ -0,0 +1,14 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +final class GenericProblemsTest { + + @Test + void shouldNotBeInstantiable() throws Exception { + assertThrows(Exception.class, GenericProblems::new); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java new file mode 100644 index 0000000000..72bcf430ff --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java @@ -0,0 +1,44 @@ +package org.zalando.problem; + +import javax.ws.rs.core.Response.StatusType; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +public final class InsufficientFundsProblem extends ThrowableProblem { + + static final String TYPE_VALUE = "https://example.org/insufficient-funds"; + static final URI TYPE = URI.create(TYPE_VALUE); + + private final int balance; + private final int debit; + + InsufficientFundsProblem(final int balance, final int debit) { + this.balance = balance; + this.debit = debit; + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Insufficient Funds"; + } + + @Override + public StatusType getStatus() { + return BAD_REQUEST; + } + + int getBalance() { + return balance; + } + + int getDebit() { + return debit; + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/MoreStatusTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/MoreStatusTest.java new file mode 100644 index 0000000000..eb5f9d7065 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/MoreStatusTest.java @@ -0,0 +1,50 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Response.StatusType; +import java.util.stream.Stream; + +import static org.hamcrest.Matchers.emptyOrNullString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.hamcrest.MatcherAssert.assertThat; + +final class MoreStatusTest { + + @Test + void shouldBeDistinctFromStatus() { + Stream.of(MoreStatus.values()).map(StatusType::getStatusCode).forEach(code -> { + final Status status = Status.fromStatusCode(code); + assertThat("Duplicate code: " + code, status, is(nullValue())); + }); + } + + @Test + void shouldHaveFamily() { + Stream.of(MoreStatus.values()).forEach(status -> + assertThat(status, hasFeature("family", StatusType::getFamily, notNullValue()))); + } + + @Test + void shouldHaveReasonPhrase() { + Stream.of(MoreStatus.values()).forEach(status -> + assertThat(status, hasFeature("reason phrase", StatusType::getReasonPhrase, is(not(emptyOrNullString()))))); + } + + @Test + void shouldFindByStatusCode() { + assertThat(MoreStatus.fromStatusCode(422), is(notNullValue())); + } + + @Test + void shouldNotFindByStatusCode() { + assertThat(MoreStatus.fromStatusCode(600), is(nullValue())); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java new file mode 100644 index 0000000000..55c8523f3d --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java @@ -0,0 +1,39 @@ +package org.zalando.problem; + +import javax.ws.rs.core.Response.StatusType; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +public final class OutOfStockProblem extends ThrowableProblem { + + private static final String TYPE_VALUE = "https://example.org/out-of-stock"; + private static final URI TYPE = URI.create(TYPE_VALUE); + + private final String detail; + + public OutOfStockProblem(final String detail) { + this.detail = detail; + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Out of Stock"; + } + + @Override + public StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public String getDetail() { + return detail; + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java new file mode 100644 index 0000000000..3e45c6101b --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java @@ -0,0 +1,134 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ProblemBuilderTest { + + private final URI type = URI.create("https://example.org/out-of-stock"); + + @Test + void shouldCreateEmptyProblem() { + final Problem problem = Problem.builder().build(); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, is(nullValue()))); + assertThat(problem, hasFeature("status", Problem::getStatus, is(nullValue()))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + void shouldCreateProblem() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("type", Problem::getType, is(type))); + assertThat(problem, hasFeature("title", Problem::getTitle, is("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, is(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + void shouldCreateProblemWithDetail() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withDetail("Item B00027Y5QG is no longer available") + .build(); + + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + void shouldCreateProblemWithInstance() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withInstance(URI.create("https://example.com/")) + .build(); + + assertThat(problem, hasFeature("instance", Problem::getInstance, is(URI.create("https://example.com/")))); + } + + @Test + void shouldCreateProblemWithParameters() { + final ThrowableProblem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .with("foo", "bar") + .build(); + + assertThat(problem.getParameters(), hasEntry("foo", "bar")); + } + + @Test + void shouldCreateProblemWithCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, notNullValue())); + + final ThrowableProblem cause = problem.getCause(); + assertThat(cause, hasFeature("type", Problem::getType, hasToString("https://example.org/expired-credit-card"))); + assertThat(cause, hasFeature("title", Problem::getTitle, is("Expired Credit Card"))); + assertThat(cause, hasFeature("status", Problem::getStatus, is(BAD_REQUEST))); + } + + @Test + void shouldThrowOnCustomType() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("type", "foo")); + } + + @Test + void shouldThrowOnCustomTitle() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("title", "foo")); + } + + @Test + void shouldThrowOnCustomStatus() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("status", "foo")); + } + + @Test + void shouldThrowOnCustomDetail() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("detail", "foo")); + } + + @Test + void shouldThrowOnCustomInstance() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("instance", "foo")); + } + + @Test + void shouldThrowOnCustomCause() { + assertThrows(IllegalArgumentException.class, () -> Problem.builder().with("cause", "foo")); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java new file mode 100644 index 0000000000..f26194cc00 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java @@ -0,0 +1,34 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import javax.ws.rs.core.Response.Status; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.hamcrest.MatcherAssert.assertThat; + +final class ProblemStaticFactoryTest { + + @Test + void shouldCreateGenericProblem() { + final Problem problem = Problem.valueOf(Status.NOT_FOUND); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Not Found"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(Status.NOT_FOUND))); + } + + @Test + void shouldCreateGenericProblemWithDetail() { + final Problem problem = Problem.valueOf(Status.NOT_FOUND, "Order 123"); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Not Found"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(Status.NOT_FOUND))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Order 123"))); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemTest.java new file mode 100644 index 0000000000..fb66e6a28a --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ProblemTest.java @@ -0,0 +1,152 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; + +import static java.util.Collections.emptyMap; +import static javax.ws.rs.core.Response.Status.NOT_FOUND; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.hamcrest.MatcherAssert.assertThat; + +final class ProblemTest { + + @Test + void shouldUseDefaultType() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + } + + @Test + void shouldUseDefaultTitle() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("title", Problem::getTitle, is(nullValue()))); + } + + @Test + void shouldUseDefaultStatus() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("status", Problem::getStatus, is(nullValue()))); + } + + @Test + void shouldUseDefaultDetail() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + } + + @Test + void shouldUseDefaultInstance() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + void shouldUseDefaultParameters() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("parameters", Problem::getParameters, is(emptyMap()))); + } + + @Test + void simpleAbstractThrowableProblemShouldBeEmpty() { + final Problem problem = new AbstractThrowableProblem() { + }; + + assertThat(problem, hasFeature(Problem::getType, hasToString("about:blank"))); + } + + @Test + void shouldRenderEmptyProblem() { + final Problem problem = Problem.builder().build(); + assertThat(problem, hasToString("about:blank{}")); + } + + @Test + void shouldRenderType() { + final Problem problem = Problem.builder().withType(URI.create("my-problem")).build(); + assertThat(problem, hasToString("my-problem{}")); + } + + @Test + void shouldRenderTitle() { + final Problem problem = Problem.builder().withTitle("Not Found").build(); + assertThat(problem, hasToString("about:blank{Not Found}")); + } + + @Test + void shouldRenderStatus() { + final Problem problem = Problem.builder().withStatus(NOT_FOUND).build(); + assertThat(problem, hasToString("about:blank{404}")); + } + + @Test + void shouldRenderDetail() { + final Problem problem = Problem.builder().withDetail("Order 123").build(); + assertThat(problem, hasToString("about:blank{Order 123}")); + } + + @Test + void shouldRenderInstance() { + final Problem problem = Problem.valueOf(NOT_FOUND, URI.create("https://example.org/")); + assertThat(problem, hasToString("about:blank{404, Not Found, instance=https://example.org/}")); + } + + @Test + void shouldRenderFully() { + final Problem problem = Problem.valueOf(NOT_FOUND, "Order 123", URI.create("https://example.org/")); + assertThat(problem, hasToString("about:blank{404, Not Found, Order 123, instance=https://example.org/}")); + } + + @Test + void shouldRenderCustomDetailAndInstance() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withTitle("Not Found") + .withStatus(NOT_FOUND) + .withDetail("Order 123") + .withInstance(URI.create("https://example.org/")) + .build(); + + assertThat(problem, hasToString("https://example.org/problem{404, Not Found, Order 123, instance=https://example.org/}")); + } + + @Test + void shouldRenderCustomProperties() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withTitle("Not Found") + .withStatus(NOT_FOUND) + .withDetail("Order 123") + .with("foo", "bar") + .build(); + + assertThat(problem, hasToString("https://example.org/problem{404, Not Found, Order 123, foo=bar}")); + } + + @Test + void shouldRenderCustomPropertiesWhenPrintingStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withStatus(NOT_FOUND) + .with("foo", "bar") + .build(); + + final StringWriter writer = new StringWriter(); + problem.printStackTrace(new PrintWriter(writer)); + + assertThat(writer, hasToString(containsString("https://example.org/problem{404, foo=bar}"))); + } + +} diff --git a/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java new file mode 100644 index 0000000000..81c52869fa --- /dev/null +++ b/src/test/resources/oracle/commits/problem-1b987b88ecb5cc2c8df58ac8eda188fb2d6f5998/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java @@ -0,0 +1,134 @@ +package org.zalando.problem; + +import org.junit.jupiter.api.Test; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.hamcrest.MatcherAssert.assertThat; + +final class ThrowableProblemTest { + + @Test + void shouldReturnThrowableProblemCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, notNullValue())); + } + + @Test + void shouldReturnNullCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, nullValue())); + } + + @Test + void shouldReturnTitleAsMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("message", Throwable::getMessage, is("Preauthorization Failed"))); + } + + @Test + void shouldReturnTitleAndDetailAsMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withDetail("CVC invalid") + .build(); + + assertThat(problem, hasFeature("message", Throwable::getMessage, is("Preauthorization Failed: CVC invalid"))); + } + + @Test + void shouldReturnCausesMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", Throwable::getCause, is(notNullValue()))); + assertThat(problem.getCause(), hasFeature("message", Throwable::getMessage, is("Expired Credit Card"))); + } + + @Test + void shouldPrintStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String stacktrace = getStackTrace(problem); + + assertThat(stacktrace, + startsWith("https://example.org/preauthorization-failed{400, Preauthorization Failed}")); + + assertThat(stacktrace, + containsString("Caused by: https://example.org/expired-credit-card{400, Expired Credit Card}")); + } + + @Test + void shouldProcessStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String stacktrace = getStackTrace(problem); + + assertThat(stacktrace, not(containsString("org.junit"))); + } + + private String getStackTrace(final Throwable throwable) { + final StringWriter writer = new StringWriter(); + throwable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java new file mode 100644 index 0000000000..9c15f84864 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/BusinessException.java @@ -0,0 +1,20 @@ +package org.zalando.problem; + +public abstract class BusinessException extends Exception { + + public BusinessException() { + } + + public BusinessException(final String message) { + super(message); + } + + public BusinessException(final String message, final Throwable cause) { + super(message, cause); + } + + public BusinessException(final Throwable cause) { + super(cause); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java new file mode 100644 index 0000000000..528c071714 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java @@ -0,0 +1,27 @@ +package org.zalando.problem; + +import com.google.gag.annotation.remark.Hack; +import com.google.gag.annotation.remark.OhNoYouDidnt; +import org.junit.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@Hack +@OhNoYouDidnt +public final class EnforceCoverageTest { + + @Test(expected = AbstractThrowableProblem.class) + public void shouldUseMixinConstructor() { + new AbstractThrowableProblemMixIn(URI.create("https://example.org"), "Bad Request", BAD_REQUEST, null, null, null) { + + @Override + void set(final String key, final Object value) { + + } + + }; + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java new file mode 100644 index 0000000000..0c7021d18b --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java @@ -0,0 +1,37 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@JsonTypeName(InsufficientFundsProblem.TYPE_VALUE) +public final class InsufficientFundsProblem extends AbstractThrowableProblem { + + static final String TYPE_VALUE = "https://example.org/insufficient-funds"; + static final URI TYPE = URI.create(TYPE_VALUE); + + private final int balance; + private final int debit; + + @JsonCreator + public InsufficientFundsProblem( + @JsonProperty("balance") final int balance, + @JsonProperty("debit") final int debit) { + super(TYPE, "Insufficient Funds", BAD_REQUEST); + this.balance = balance; + this.debit = debit; + } + + public int getBalance() { + return balance; + } + + public int getDebit() { + return debit; + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java new file mode 100644 index 0000000000..9071ffe120 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/OutOfStockException.java @@ -0,0 +1,48 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import javax.ws.rs.core.Response; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@JsonTypeName(OutOfStockException.TYPE_NAME) +public class OutOfStockException extends BusinessException implements Exceptional { + + public static final String TYPE_NAME = "https://example.org/out-of-stock"; + public static final URI TYPE = URI.create(TYPE_NAME); + + @JsonCreator + public OutOfStockException(@JsonProperty("detail") final String detail) { + super(detail); + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Out of Stock"; + } + + @Override + public Response.StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public String getDetail() { + return getMessage(); + } + + @Override + public ThrowableProblem getCause() { + return null; + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java new file mode 100644 index 0000000000..a4a1829819 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemMixInTest.java @@ -0,0 +1,265 @@ +package org.zalando.problem; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Response.Status.Family; +import javax.ws.rs.core.Response.StatusType; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Objects; + +import static com.jayway.jsonassert.JsonAssert.with; +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public final class ProblemMixInTest { + + private final ObjectMapper mapper = new ObjectMapper() + .registerModule(new ProblemModule()); + + public ProblemMixInTest() { + mapper.registerSubtypes(InsufficientFundsProblem.class); + mapper.registerSubtypes(OutOfStockException.class); + } + + @Test + public void shouldSerializeDefaultProblem() throws JsonProcessingException { + final Problem problem = Problem.valueOf(Status.NOT_FOUND); + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.*", hasSize(2)) + .assertThat("$.title", is("Not Found")) + .assertThat("$.status", is(404)); + } + + @Test + public void shouldSerializeCustomProperties() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("https://example.org/out-of-stock")) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withDetail("Item B00027Y5QG is no longer available") + .with("product", "B00027Y5QG") + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.*", hasSize(5)) + .assertThat("$.product", is("B00027Y5QG")); + } + + @Test + public void shouldSerializeProblemCause() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .withDetail("Credit card is expired as of 2015-09-16T00:00:00Z") + .with("since", "2015-09-16T00:00:00Z") + .build()) + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.cause.type", is("https://example.org/expired-credit-card")) + .assertThat("$.cause.title", is("Expired Credit Card")) + .assertThat("$.cause.status", is(400)) + .assertThat("$.cause.detail", is("Credit card is expired as of 2015-09-16T00:00:00Z")) + .assertThat("$.cause.since", is("2015-09-16T00:00:00Z")); + } + + @Test + public void shouldNotSerializeStacktraceByDefault() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Foo") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Bar") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertNotDefined("$.stacktrace"); + } + + @Test + public void shouldSerializeStacktrace() throws JsonProcessingException { + final Problem problem = Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Foo") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("about:blank")) + .withTitle("Bar") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final ObjectMapper mapper = new ObjectMapper() + .registerModule(new ProblemModule().withStackTraces()); + + final String json = mapper.writeValueAsString(problem); + + with(json) + .assertThat("$.stacktrace", is(instanceOf(List.class))) + .assertThat("$.stacktrace[0]", is(instanceOf(String.class))); + } + + @Test + public void shouldDeserializeDefaultProblem() throws IOException { + final URL resource = getResource("default.json"); + final Problem raw = mapper.readValue(resource, Problem.class); + + assertThat(raw, instanceOf(DefaultProblem.class)); + final DefaultProblem problem = (DefaultProblem) raw; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/not-out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + assertThat(problem, hasFeature("parameters", DefaultProblem::getParameters, hasEntry("product", "B00027Y5QG"))); + } + + @Test + public void shouldDeserializeRegisteredExceptional() throws IOException { + final URL resource = getResource("out-of-stock.json"); + final Exceptional exceptional = mapper.readValue(resource, Exceptional.class); + + assertThat(exceptional, instanceOf(OutOfStockException.class)); + final OutOfStockException problem = (OutOfStockException) exceptional; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + public void shouldDeserializeUnregisteredExceptional() throws IOException { + final URL resource = getResource("out-of-stock.json"); + final Exceptional exceptional = mapper.readValue(resource, IOProblem.class); + + assertThat(exceptional, instanceOf(IOProblem.class)); + final IOProblem problem = (IOProblem) exceptional; + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("https://example.org/out-of-stock"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + public void shouldDeserializeSpecificProblem() throws IOException { + final URL resource = getResource("insufficient-funds.json"); + final InsufficientFundsProblem problem = (InsufficientFundsProblem) mapper.readValue(resource, Problem.class); + + assertThat(problem, hasFeature("balance", InsufficientFundsProblem::getBalance, equalTo(10))); + assertThat(problem, hasFeature("debit", InsufficientFundsProblem::getDebit, equalTo(-20))); + } + + @Test + public void shouldDeserializeUnknownStatus() throws IOException { + final URL resource = getResource("unknown.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + final StatusType status = problem.getStatus(); + + assertThat(status, hasFeature("status code", StatusType::getStatusCode, equalTo(666))); + assertThat(status, hasFeature("family", StatusType::getFamily, equalTo(Family.OTHER))); + assertThat(status, hasFeature("reason phrase", StatusType::getReasonPhrase, equalTo("Unknown"))); + } + + @Test + public void shouldDeserializeUntyped() throws IOException { + final URL resource = getResource("untyped.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + assertThat(problem.getType(), hasToString("about:blank")); + assertThat(problem.getTitle(), is("Something bad")); + assertThat(problem.getStatus(), hasFeature(StatusType::getStatusCode, is(400))); + assertThat(problem.getDetail(), is(nullValue())); + assertThat(problem.getInstance(), is(nullValue())); + } + + @Test + public void shouldDeserializeEmpty() throws IOException { + final URL resource = getResource("empty.json"); + final Problem problem = mapper.readValue(resource, Problem.class); + + assertThat(problem.getType(), hasToString("about:blank")); + assertThat(problem.getTitle(), is(nullValue())); + assertThat(problem.getStatus(), is(nullValue())); + assertThat(problem.getDetail(), is(nullValue())); + assertThat(problem.getInstance(), is(nullValue())); + } + + @Test + public void shouldDeserializeCause() throws IOException { + final URL resource = getResource("cause.json"); + final ThrowableProblem problem = mapper.readValue(resource, ThrowableProblem.class); + + assertThat(problem, hasFeature("cause", Throwable::getCause, is(notNullValue()))); + final DefaultProblem cause = (DefaultProblem) problem.getCause(); + + assertThat(cause, is(notNullValue())); + assertThat(cause, instanceOf(DefaultProblem.class)); + + assertThat(cause, hasFeature("type", Problem::getType, hasToString("https://example.org/expired-credit-card"))); + assertThat(cause, hasFeature("title", Problem::getTitle, equalTo("Expired Credit Card"))); + assertThat(cause, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(cause, hasFeature("detail", Problem::getDetail, is("Credit card is expired as of 2015-09-16T00:00:00Z"))); + assertThat(cause, hasFeature("parameters", Problem::getParameters, hasEntry("since", "2015-09-16T00:00:00Z"))); + } + + @Test + public void shouldDeserializeWithProcessedStackTrace() throws IOException { + final URL resource = getResource("cause.json"); + final ThrowableProblem problem = mapper.readValue(resource, ThrowableProblem.class); + + final String stackTrace = getStackTrace(problem); + final String[] stackTraceElements = stackTrace.split("\n"); + + assertThat(stackTraceElements[1], startsWith("\tat org.zalando.problem.ProblemMixInTest")); + } + + private String getStackTrace(final Throwable throwable) { + final StringWriter writer = new StringWriter(); + throwable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } + + private static URL getResource(final String name) { + final ClassLoader loader = Thread.currentThread().getContextClassLoader(); + return Objects.requireNonNull(loader.getResource(name), () -> "resource " + name + " not found."); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java new file mode 100644 index 0000000000..d3660aa4be --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/jackson-datatype-problem/src/test/java/org/zalando/problem/ProblemModuleTest.java @@ -0,0 +1,19 @@ +package org.zalando.problem; + +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; + +public final class ProblemModuleTest { + + @Test + public void defaultConstructorShouldBuildIndexCorrectly() { + new ProblemModule(); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowForDuplicateStatusCode() { + new ProblemModule(Status.class, CustomStatus.class); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java new file mode 100644 index 0000000000..9790ec449d --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/DefaultProblemTest.java @@ -0,0 +1,45 @@ +package org.zalando.problem; + +import org.junit.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +@SuppressWarnings("ConstantConditions") +public final class DefaultProblemTest { + + private final URI type = URI.create("https://example.org/out-of-stock"); + + @Test + public void shouldDefaultToAboutBlank() { + final DefaultProblem problem = new DefaultProblem(null, null, null, null, null, null); + assertThat(problem.getType(), hasToString("about:blank")); + } + + @Test + public void shouldImplementProblem() { + final DefaultProblem problem = new DefaultProblem(type, "Out of Stock", BAD_REQUEST, + "Item B00027Y5QG is no longer available", + URI.create("https://example.org/e7203fd2-463b-11e5-a823-10ddb1ee7671"), + null); + + problem.set("foo", "bar"); + + assertThat(problem, hasFeature("type", Problem::getType, equalTo(type))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, + is("Item B00027Y5QG is no longer available"))); + assertThat(problem, hasFeature("instance", Problem::getInstance, + hasToString("https://example.org/e7203fd2-463b-11e5-a823-10ddb1ee7671"))); + assertThat(problem, hasFeature(DefaultProblem::getParameters, hasEntry("foo", "bar"))); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java new file mode 100644 index 0000000000..963b09e44e --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/EnforceCoverageTest.java @@ -0,0 +1,50 @@ +package org.zalando.problem; + +import com.google.gag.annotation.remark.Hack; +import com.google.gag.annotation.remark.OhNoYouDidnt; +import org.junit.Test; + +import javax.ws.rs.core.Response; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +@Hack +@OhNoYouDidnt +public class EnforceCoverageTest { + + @Test(expected = FakeProblem.class) + public void shouldCoverUnreachableThrowStatement() throws Exception { + throw new FakeProblem().propagate(); + } + + static final class FakeProblem extends Exception implements Exceptional { + + @Override + public URI getType() { + return URI.create("about:blank"); + } + + @Override + public String getTitle() { + return "Fake"; + } + + @Override + public Response.StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public ThrowableProblem getCause() { + return null; + } + + @Override + public X propagateAs(final Class type) throws X { + return type.cast(this); + } + + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ExceptionalTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ExceptionalTest.java new file mode 100644 index 0000000000..37778705d5 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ExceptionalTest.java @@ -0,0 +1,29 @@ +package org.zalando.problem; + +import org.junit.Test; + +import static org.hamcrest.Matchers.equalTo; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + +public final class ExceptionalTest { + + @Test + public void shouldBeAbleToThrowAndCatchThrowableProblem() { + try { + throw unit().propagate(); + } catch (final InsufficientFundsProblem problem) { + assertThat(problem, hasFeature("balance", InsufficientFundsProblem::getBalance, equalTo(10))); + } catch (final OutOfStockProblem problem) { + fail("Should not have been out-of-stock"); + } catch (final Exception e) { + fail("Should not have been unspecific problem"); + } + } + + private Exceptional unit() { + return new InsufficientFundsProblem(10, -20); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java new file mode 100644 index 0000000000..ae194582e8 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/GenericProblemsTest.java @@ -0,0 +1,12 @@ +package org.zalando.problem; + +import org.junit.Test; + +public final class GenericProblemsTest { + + @Test(expected = Exception.class) + public void shouldNotBeInstantiable() throws Exception { + new GenericProblems(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java new file mode 100644 index 0000000000..9757393119 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/InsufficientFundsProblem.java @@ -0,0 +1,44 @@ +package org.zalando.problem; + +import javax.ws.rs.core.Response.StatusType; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +public final class InsufficientFundsProblem extends ThrowableProblem { + + static final String TYPE_VALUE = "https://example.org/insufficient-funds"; + static final URI TYPE = URI.create(TYPE_VALUE); + + private final int balance; + private final int debit; + + public InsufficientFundsProblem(final int balance, final int debit) { + this.balance = balance; + this.debit = debit; + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Insufficient Funds"; + } + + @Override + public StatusType getStatus() { + return BAD_REQUEST; + } + + public int getBalance() { + return balance; + } + + public int getDebit() { + return debit; + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/MoreStatusTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/MoreStatusTest.java new file mode 100644 index 0000000000..661c87f5ff --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/MoreStatusTest.java @@ -0,0 +1,49 @@ +package org.zalando.problem; + +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Response.StatusType; +import java.util.stream.Stream; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.isEmptyOrNullString; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public final class MoreStatusTest { + + @Test + public void shouldBeDistinctFromStatus() { + Stream.of(MoreStatus.values()).map(StatusType::getStatusCode).forEach(code -> { + final Status status = Status.fromStatusCode(code); + assertThat("Duplicate code: " + code, status, is(nullValue())); + }); + } + + @Test + public void shouldHaveFamily() { + Stream.of(MoreStatus.values()).forEach(status -> + assertThat(status, hasFeature("family", StatusType::getFamily, notNullValue()))); + } + + @Test + public void shouldHaveReasonPhrase() { + Stream.of(MoreStatus.values()).forEach(status -> + assertThat(status, hasFeature("reason phrase", StatusType::getReasonPhrase, not(isEmptyOrNullString())))); + } + + @Test + public void shouldFindByStatusCode() { + assertThat(MoreStatus.fromStatusCode(422), is(notNullValue())); + } + + @Test + public void shouldNotFindByStatusCode() { + assertThat(MoreStatus.fromStatusCode(600), is(nullValue())); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java new file mode 100644 index 0000000000..d372b232b9 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/OutOfStockProblem.java @@ -0,0 +1,39 @@ +package org.zalando.problem; + +import javax.ws.rs.core.Response.StatusType; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +public final class OutOfStockProblem extends ThrowableProblem { + + static final String TYPE_VALUE = "https://example.org/out-of-stock"; + static final URI TYPE = URI.create(TYPE_VALUE); + + private final String detail; + + public OutOfStockProblem(final String detail) { + this.detail = detail; + } + + @Override + public URI getType() { + return TYPE; + } + + @Override + public String getTitle() { + return "Out of Stock"; + } + + @Override + public StatusType getStatus() { + return BAD_REQUEST; + } + + @Override + public String getDetail() { + return detail; + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java new file mode 100644 index 0000000000..cf277c9589 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemBuilderTest.java @@ -0,0 +1,133 @@ +package org.zalando.problem; + +import org.junit.Test; + +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public class ProblemBuilderTest { + + private final URI type = URI.create("https://example.org/out-of-stock"); + + @Test + public void shouldCreateEmptyProblem() { + final Problem problem = Problem.builder().build(); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, is(nullValue()))); + assertThat(problem, hasFeature("status", Problem::getStatus, is(nullValue()))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + public void shouldCreateProblem() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("type", Problem::getType, is(type))); + assertThat(problem, hasFeature("title", Problem::getTitle, is("Out of Stock"))); + assertThat(problem, hasFeature("status", Problem::getStatus, is(BAD_REQUEST))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + public void shouldCreateProblemWithDetail() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withDetail("Item B00027Y5QG is no longer available") + .build(); + + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Item B00027Y5QG is no longer available"))); + } + + @Test + public void shouldCreateProblemWithInstance() { + final Problem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .withInstance(URI.create("https://example.com/")) + .build(); + + assertThat(problem, hasFeature("instance", Problem::getInstance, is(URI.create("https://example.com/")))); + } + + @Test + public void shouldCreateProblemWithParameters() { + final ThrowableProblem problem = Problem.builder() + .withType(type) + .withTitle("Out of Stock") + .withStatus(BAD_REQUEST) + .with("foo", "bar") + .build(); + + assertThat(problem.getParameters(), hasEntry("foo", "bar")); + } + + @Test + public void shouldCreateProblemWithCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, notNullValue())); + + final ThrowableProblem cause = problem.getCause(); + assertThat(cause, hasFeature("type", Problem::getType, hasToString("https://example.org/expired-credit-card"))); + assertThat(cause, hasFeature("title", Problem::getTitle, is("Expired Credit Card"))); + assertThat(cause, hasFeature("status", Problem::getStatus, is(BAD_REQUEST))); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomType() { + Problem.builder().with("type", "foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomTitle() { + Problem.builder().with("title", "foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomStatus() { + Problem.builder().with("status", "foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomDetail() { + Problem.builder().with("detail", "foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomInstance() { + Problem.builder().with("instance", "foo"); + } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowOnCustomCause() { + Problem.builder().with("cause", "foo"); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java new file mode 100644 index 0000000000..bc52e3888b --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemStaticFactoryTest.java @@ -0,0 +1,34 @@ +package org.zalando.problem; + +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public final class ProblemStaticFactoryTest { + + @Test + public void shouldCreateGenericProblem() { + final Problem problem = Problem.valueOf(Status.NOT_FOUND); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Not Found"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(Status.NOT_FOUND))); + } + + @Test + public void shouldCreateGenericProblemWithDetail() { + final Problem problem = Problem.valueOf(Status.NOT_FOUND, "Order 123"); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + assertThat(problem, hasFeature("title", Problem::getTitle, equalTo("Not Found"))); + assertThat(problem, hasFeature("status", Problem::getStatus, equalTo(Status.NOT_FOUND))); + assertThat(problem, hasFeature("detail", Problem::getDetail, is("Order 123"))); + } + +} diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemTest.java new file mode 100644 index 0000000000..917f8c8ff0 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ProblemTest.java @@ -0,0 +1,152 @@ +package org.zalando.problem; + +import org.junit.Test; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; + +import static java.util.Collections.emptyMap; +import static javax.ws.rs.core.Response.Status.NOT_FOUND; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public final class ProblemTest { + + @Test + public void shouldUseDefaultType() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("type", Problem::getType, hasToString("about:blank"))); + } + + @Test + public void shouldUseDefaultTitle() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("title", Problem::getTitle, is(nullValue()))); + } + + @Test + public void shouldUseDefaultStatus() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("status", Problem::getStatus, is(nullValue()))); + } + + @Test + public void shouldUseDefaultDetail() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("detail", Problem::getDetail, is(nullValue()))); + } + + @Test + public void shouldUseDefaultInstance() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("instance", Problem::getInstance, is(nullValue()))); + } + + @Test + public void shouldUseDefaultParameters() { + final Problem problem = new EmptyProblem(); + + assertThat(problem, hasFeature("parameters", Problem::getParameters, is(emptyMap()))); + } + + @Test + public void simpleAbstractThrowableProblemShouldBeEmpty() { + final Problem problem = new AbstractThrowableProblem() { + }; + + assertThat(problem, hasFeature(Problem::getType, hasToString("about:blank"))); + } + + @Test + public void shouldRenderEmptyProblem() { + final Problem problem = Problem.builder().build(); + assertThat(problem, hasToString("about:blank{}")); + } + + @Test + public void shouldRenderType() { + final Problem problem = Problem.builder().withType(URI.create("my-problem")).build(); + assertThat(problem, hasToString("my-problem{}")); + } + + @Test + public void shouldRenderTitle() { + final Problem problem = Problem.builder().withTitle("Not Found").build(); + assertThat(problem, hasToString("about:blank{Not Found}")); + } + + @Test + public void shouldRenderStatus() { + final Problem problem = Problem.builder().withStatus(NOT_FOUND).build(); + assertThat(problem, hasToString("about:blank{404}")); + } + + @Test + public void shouldRenderDetail() { + final Problem problem = Problem.builder().withDetail("Order 123").build(); + assertThat(problem, hasToString("about:blank{Order 123}")); + } + + @Test + public void shouldRenderInstance() { + final Problem problem = Problem.valueOf(NOT_FOUND, URI.create("https://example.org/")); + assertThat(problem, hasToString("about:blank{404, Not Found, instance=https://example.org/}")); + } + + @Test + public void shouldRenderFully() { + final Problem problem = Problem.valueOf(NOT_FOUND, "Order 123", URI.create("https://example.org/")); + assertThat(problem, hasToString("about:blank{404, Not Found, Order 123, instance=https://example.org/}")); + } + + @Test + public void shouldRenderCustomDetailAndInstance() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withTitle("Not Found") + .withStatus(NOT_FOUND) + .withDetail("Order 123") + .withInstance(URI.create("https://example.org/")) + .build(); + + assertThat(problem, hasToString("https://example.org/problem{404, Not Found, Order 123, instance=https://example.org/}")); + } + + @Test + public void shouldRenderCustomProperties() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withTitle("Not Found") + .withStatus(NOT_FOUND) + .withDetail("Order 123") + .with("foo", "bar") + .build(); + + assertThat(problem, hasToString("https://example.org/problem{404, Not Found, Order 123, foo=bar}")); + } + + @Test + public void shouldRenderCustomPropertiesWhenPrintingStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/problem")) + .withStatus(NOT_FOUND) + .with("foo", "bar") + .build(); + + final StringWriter writer = new StringWriter(); + problem.printStackTrace(new PrintWriter(writer)); + + assertThat(writer, hasToString(containsString("https://example.org/problem{404, foo=bar}"))); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java new file mode 100644 index 0000000000..39014bdb85 --- /dev/null +++ b/src/test/resources/oracle/commits/problem-2de9405d52b0626569e411b59ff8deb4e73bb3b6/problem/src/test/java/org/zalando/problem/ThrowableProblemTest.java @@ -0,0 +1,134 @@ +package org.zalando.problem; + +import org.junit.Test; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; + +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.hobsoft.hamcrest.compose.ComposeMatchers.hasFeature; +import static org.junit.Assert.assertThat; + +public final class ThrowableProblemTest { + + @Test + public void shouldReturnThrowableProblemCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, notNullValue())); + } + + @Test + public void shouldReturnNullCause() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("cause", ThrowableProblem::getCause, nullValue())); + } + + @Test + public void shouldReturnTitleAsMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .build(); + + assertThat(problem, hasFeature("message", Throwable::getMessage, is("Preauthorization Failed"))); + } + + @Test + public void shouldReturnTitleAndDetailAsMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withDetail("CVC invalid") + .build(); + + assertThat(problem, hasFeature("message", Throwable::getMessage, is("Preauthorization Failed: CVC invalid"))); + } + + @Test + public void shouldReturnCausesMessage() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + assertThat(problem, hasFeature("cause", Throwable::getCause, is(notNullValue()))); + assertThat(problem.getCause(), hasFeature("message", Throwable::getMessage, is("Expired Credit Card"))); + } + + @Test + public void shouldPrintStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String stacktrace = getStackTrace(problem); + + assertThat(stacktrace, + startsWith("https://example.org/preauthorization-failed{400, Preauthorization Failed}")); + + assertThat(stacktrace, + containsString("Caused by: https://example.org/expired-credit-card{400, Expired Credit Card}")); + } + + @Test + public void shouldProcessStackTrace() { + final ThrowableProblem problem = Problem.builder() + .withType(URI.create("https://example.org/preauthorization-failed")) + .withTitle("Preauthorization Failed") + .withStatus(BAD_REQUEST) + .withCause(Problem.builder() + .withType(URI.create("https://example.org/expired-credit-card")) + .withTitle("Expired Credit Card") + .withStatus(BAD_REQUEST) + .build()) + .build(); + + final String stacktrace = getStackTrace(problem); + + assertThat(stacktrace, not(containsString("org.junit"))); + } + + private String getStackTrace(final Throwable throwable) { + final StringWriter writer = new StringWriter(); + throwable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } + +} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.json b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.json new file mode 100644 index 0000000000..5ec33cc7b2 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4.json @@ -0,0 +1 @@ +{"parentCommitId":"875864fb1bcfe1f05e4d8c5e217ea21874cb340b","currentCommitId":"48776d511a0152f7b9cbe4460c8967bdd5ec3dc4","filesBefore":["api/src/test/java/com/sanction/thunder/models/EmailTest.java","api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java","api/src/test/java/com/sanction/thunder/models/UserTest.java","application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java","application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java","application/src/test/java/com/sanction/thunder/authentication/KeyTest.java","application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java","application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java","application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java","application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java","application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java","application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java","application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java","application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java","application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java","application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java","application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java","application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java","application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java","client/src/test/java/com/sanction/thunder/ThunderClientTest.java"],"filesCurrent":["api/src/test/java/com/sanction/thunder/models/EmailTest.java","api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java","api/src/test/java/com/sanction/thunder/models/UserTest.java","application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java","application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java","application/src/test/java/com/sanction/thunder/authentication/KeyTest.java","application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java","application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java","application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java","application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java","application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java","application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java","application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java","application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java","application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java","application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java","application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java","application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java","application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java","client/src/test/java/com/sanction/thunder/ThunderClientTest.java"],"renamedFilesHint":{},"repositoryDirectoriesBefore":["application/src/test/java/com/sanction/thunder","application/src/test","api/src/test/java/com/sanction/thunder/models","api/src/test","client/src","application/src/test/java/com/sanction/thunder/util","client/src/test/java/com/sanction/thunder","application/src/test/java/com/sanction/thunder/dao","api/src/test/java/com/sanction/thunder","application/src/test/java/com/sanction/thunder/resources","api/src","api/src/test/java","api/src/test/java/com/sanction","client/src/test/java","client/src/test/java/com/sanction","client","api","api/src/test/java/com","client/src/test/java/com","client/src/test","application/src/test/java/com/sanction","application/src/test/java","application/src/test/java/com/sanction/thunder/authentication","application/src","application/src/test/java/com","application","application/src/test/java/com/sanction/thunder/validation","application/src/test/java/com/sanction/thunder/dao/dynamodb","application/src/test/java/com/sanction/thunder/email"],"repositoryDirectoriesCurrent":["application/src/test/java/com/sanction/thunder","application/src/test","api/src/test/java/com/sanction/thunder/models","api/src/test","client/src","application/src/test/java/com/sanction/thunder/util","client/src/test/java/com/sanction/thunder","application/src/test/java/com/sanction/thunder/dao","api/src/test/java/com/sanction/thunder","application/src/test/java/com/sanction/thunder/resources","api/src","api/src/test/java","api/src/test/java/com/sanction","client/src/test/java","client/src/test/java/com/sanction","client","api","api/src/test/java/com","client/src/test/java/com","client/src/test","application/src/test/java/com/sanction","application/src/test/java","application/src/test/java/com/sanction/thunder/authentication","application/src","application/src/test/java/com","application","application/src/test/java/com/sanction/thunder/validation","application/src/test/java/com/sanction/thunder/dao/dynamodb","application/src/test/java/com/sanction/thunder/email"],"commitTime":0,"authoredTime":0,"commitAuthorName":null} \ No newline at end of file diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/EmailTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/EmailTest.java new file mode 100644 index 0000000000..6c4ded0cf1 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/EmailTest.java @@ -0,0 +1,73 @@ +package com.sanction.thunder.models; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.FixtureHelpers; + +import java.util.StringJoiner; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class EmailTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + + private final Email email = new Email("test@test.com", true, "token"); + + @Test + public void testToJson() throws Exception { + String expected = MAPPER.writeValueAsString( + MAPPER.readValue(FixtureHelpers.fixture("fixtures/email.json"), Email.class)); + + Assertions.assertEquals(expected, MAPPER.writeValueAsString(email)); + } + + @Test + public void testFromJson() throws Exception { + Email fromJson = MAPPER.readValue(FixtureHelpers.fixture("fixtures/email.json"), Email.class); + + Assertions.assertEquals(email, fromJson); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + Assertions.assertTrue(email.equals(email)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObjectType() { + Object objectTwo = new Object(); + + Assertions.assertFalse(email.equals(objectTwo)); + } + + @Test + public void testHashCodeSame() { + Email emailOne = new Email("test@test.com", true, "token"); + Email emailTwo = new Email("test@test.com", true, "token"); + + Assertions.assertEquals(emailOne.hashCode(), emailTwo.hashCode()); + } + + @Test + public void testHashCodeDifferent() { + Email emailOne = new Email("test@test.com", true, "token"); + Email emailTwo = new Email("differentTest@test.com", true, "token"); + + Assertions.assertNotEquals(emailOne.hashCode(), emailTwo.hashCode()); + } + + @Test + public void testToString() { + String expected = new StringJoiner(", ", "Email [", "]") + .add(String.format("address=%s", "test@test.com")) + .add(String.format("verified=%b", "true")) + .add(String.format("verificationToken=%s", "token")) + .toString(); + + Assertions.assertEquals(expected, email.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java new file mode 100644 index 0000000000..7754925ddc --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java @@ -0,0 +1,26 @@ +package com.sanction.thunder.models; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class ResponseTypeTest { + + @Test + public void testJsonResponseType() { + Assertions.assertAll("Assert equal JSON response type.", + () -> Assertions.assertEquals(ResponseType.JSON, ResponseType.fromString("json")), + () -> Assertions.assertEquals("json", ResponseType.JSON.toString())); + } + + @Test + public void testHtmlResponseType() { + Assertions.assertAll("Assert equal HTML response type.", + () -> Assertions.assertEquals(ResponseType.HTML, ResponseType.fromString("html")), + () -> Assertions.assertEquals("html", ResponseType.HTML.toString())); + } + + @Test + public void testNullResponseTypeFromString() { + Assertions.assertNull(ResponseType.fromString("unknown")); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/UserTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/UserTest.java new file mode 100644 index 0000000000..4cb6d1a69e --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/api/src/test/java/com/sanction/thunder/models/UserTest.java @@ -0,0 +1,124 @@ +package com.sanction.thunder.models; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.FixtureHelpers; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.StringJoiner; +import java.util.TreeMap; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; + +public class UserTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + private static final Email EMAIL = new Email("test@test.com", true, "hashToken"); + private static final String PASSWORD = "12345"; + private static final Map MULTIPLE_PROPERTY_MAP = new TreeMap<>(); + + private final User emptyPropertiesUser = new User(EMAIL, PASSWORD, Collections.emptyMap()); + private final User multiplePropertiesUser = new User(EMAIL, PASSWORD, MULTIPLE_PROPERTY_MAP); + + @BeforeAll + public static void setup() { + MULTIPLE_PROPERTY_MAP.put("customString", "value"); + MULTIPLE_PROPERTY_MAP.put("customInt", 1); + MULTIPLE_PROPERTY_MAP.put("customDouble", 1.2); + MULTIPLE_PROPERTY_MAP.put("customBoolean", true); + MULTIPLE_PROPERTY_MAP.put("customList", Arrays.asList("hello", "world")); + } + + @Test + public void testToJsonNoProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/no_properties_user.json"), User.class)); + + Assertions.assertEquals(expected, MAPPER.writeValueAsString(emptyPropertiesUser)); + } + + @Test + public void testFromJsonNoProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/no_properties_user.json"), User.class); + + Assertions.assertEquals(emptyPropertiesUser, fromJson); + } + + @Test + public void testToJsonEmptyProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/empty_properties_user.json"),User.class)); + + Assertions.assertEquals(expected, MAPPER.writeValueAsString(emptyPropertiesUser)); + } + + @Test + public void testFromJsonEmptyProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/empty_properties_user.json"), User.class); + + Assertions.assertEquals(emptyPropertiesUser, fromJson); + } + + @Test + public void testToJsonMultipleProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/multiple_properties_user.json"), User.class)); + + Assertions.assertEquals(expected, MAPPER.writeValueAsString(multiplePropertiesUser)); + } + + @Test + public void testFromJsonMultipleProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/multiple_properties_user.json"), User.class); + + Assertions.assertEquals(multiplePropertiesUser, fromJson); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + Assertions.assertTrue(multiplePropertiesUser.equals(multiplePropertiesUser)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObjectType() { + Object objectTwo = new Object(); + + Assertions.assertFalse(multiplePropertiesUser.equals(objectTwo)); + } + + @Test + public void testHashCodeSame() { + User userOne = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + User userTwo = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + + Assertions.assertEquals(userOne.hashCode(), userTwo.hashCode()); + } + + @Test + public void testHashCodeDifferent() { + User userOne = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + User userTwo = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 2)); + + Assertions.assertNotEquals(userOne.hashCode(), userTwo.hashCode()); + } + + @Test + public void testToString() { + String expected = new StringJoiner(", ", "User [", "]") + .add(String.format("email=%s", EMAIL)) + .add(String.format("password=%s", PASSWORD)) + .add(String.format("properties=%s", MULTIPLE_PROPERTY_MAP)) + .toString(); + + Assertions.assertEquals(expected, multiplePropertiesUser.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java new file mode 100644 index 0000000000..b2ab636a86 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java @@ -0,0 +1,95 @@ +package com.sanction.thunder; + +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.health.HealthCheckRegistry; + +import com.sanction.thunder.dao.dynamodb.DynamoDbConfiguration; +import com.sanction.thunder.dao.dynamodb.DynamoDbHealthCheck; +import com.sanction.thunder.email.EmailConfiguration; +import com.sanction.thunder.resources.UserResource; +import com.sanction.thunder.resources.VerificationResource; + +import io.dropwizard.auth.AuthDynamicFeature; +import io.dropwizard.jersey.setup.JerseyEnvironment; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.mockito.ArgumentCaptor; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ThunderApplicationTest { + private final Environment environment = mock(Environment.class); + private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); + private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); + private final MetricRegistry metrics = mock(MetricRegistry.class); + private final ThunderConfiguration config = mock(ThunderConfiguration.class); + private final DynamoDbConfiguration dynamoConfig = mock(DynamoDbConfiguration.class); + private final EmailConfiguration emailConfig = mock(EmailConfiguration.class); + + @SuppressWarnings("unchecked") + private final Bootstrap bootstrap = mock(Bootstrap.class); + + private final ThunderApplication application = new ThunderApplication(); + + @Before + public void setup() { + when(environment.jersey()).thenReturn(jersey); + when(environment.healthChecks()).thenReturn(healthChecks); + when(environment.metrics()).thenReturn(metrics); + + when(dynamoConfig.getEndpoint()).thenReturn("http://localhost"); + when(dynamoConfig.getRegion()).thenReturn("us-east-1"); + when(dynamoConfig.getTableName()).thenReturn("sample-table"); + + when(emailConfig.getEndpoint()).thenReturn("http://localhost"); + when(emailConfig.getRegion()).thenReturn("us-east-1"); + when(emailConfig.getFromAddress()).thenReturn("testAddress@test.com"); + when(emailConfig.getSuccessHtmlPath()).thenReturn(null); + when(emailConfig.getVerificationHtmlPath()).thenReturn(null); + when(emailConfig.getVerificationTextPath()).thenReturn(null); + + // ThunderConfiguration NotNull fields + when(config.getApprovedKeys()).thenReturn(new ArrayList<>()); + when(config.getDynamoConfiguration()).thenReturn(dynamoConfig); + when(config.getEmailConfiguration()).thenReturn(emailConfig); + } + + @Test + public void testInitialize() { + application.initialize(bootstrap); + + // Nothing should happen in the initialize method + } + + @Test + public void testRun() { + ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); + + application.run(config, environment); + + // Verify register was called on jersey and healthChecks + verify(jersey, atLeastOnce()).register(captor.capture()); + verify(healthChecks, times(1)).register(eq("DynamoDB"), any(DynamoDbHealthCheck.class)); + + // Make sure each class that should have been registered on jersey was registered + List values = captor.getAllValues(); + + Assertions.assertAll("Assert correct instance types for runtime arguments.", + () -> Assertions.assertEquals(1, values.stream().filter(v -> v instanceof AuthDynamicFeature).count()), + () -> Assertions.assertEquals(1, values.stream().filter(v -> v instanceof UserResource).count()), + () -> Assertions.assertEquals(1, values.stream().filter(v -> v instanceof VerificationResource).count())); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java new file mode 100644 index 0000000000..00e4004c2a --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java @@ -0,0 +1,57 @@ +package com.sanction.thunder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.google.common.io.Resources; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.validation.PropertyValidationRule; + +import io.dropwizard.configuration.YamlConfigurationFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jersey.validation.Validators; + +import java.io.File; +import java.util.Collections; +import javax.validation.Validator; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class ThunderConfigurationTest { + private final ObjectMapper mapper = Jackson.newObjectMapper(); + private final Validator validator = Validators.newValidator(); + private final YamlConfigurationFactory factory + = new YamlConfigurationFactory<>(ThunderConfiguration.class, validator, mapper, "dw"); + + @Test + public void testFromYaml() throws Exception { + ThunderConfiguration configuration = factory.build( + new File(Resources.getResource("fixtures/config.yaml").toURI())); + + Assertions.assertEquals("test.dynamodb.com", configuration.getDynamoConfiguration().getEndpoint()); + Assertions.assertEquals("test-region-1", configuration.getDynamoConfiguration().getRegion()); + Assertions.assertEquals("test-table", configuration.getDynamoConfiguration().getTableName()); + + Assertions.assertEquals("test.email.com", configuration.getEmailConfiguration().getEndpoint()); + Assertions.assertEquals("test-region-2", configuration.getEmailConfiguration().getRegion()); + Assertions.assertEquals("test@sanctionco.com", configuration.getEmailConfiguration().getFromAddress()); + + Assertions.assertEquals("test-success-page.html", + configuration.getEmailConfiguration().getSuccessHtmlPath()); + Assertions.assertEquals("test-verification-email.html", + configuration.getEmailConfiguration().getVerificationHtmlPath()); + Assertions.assertEquals("test-verification-email.txt", + configuration.getEmailConfiguration().getVerificationTextPath()); + + Assertions.assertEquals(1, configuration.getApprovedKeys().size()); + Assertions.assertEquals( + Collections.singletonList(new Key("test-app", "test-secret")), + configuration.getApprovedKeys()); + + Assertions.assertEquals(1, configuration.getValidationRules().size()); + Assertions.assertEquals( + new PropertyValidationRule("testProperty", "list"), + configuration.getValidationRules().get(0)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java new file mode 100644 index 0000000000..ece3c66024 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java @@ -0,0 +1,54 @@ +package com.sanction.thunder.authentication; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class KeyTest { + + @Test + public void testHashCodeSame() { + Key keyOne = new Key("name", "secret"); + Key keyTwo = new Key("name", "secret"); + + Assertions.assertAll("Assert equal key properties", + () -> Assertions.assertEquals(keyOne.hashCode(), keyTwo.hashCode()), + () -> Assertions.assertEquals(keyOne.getName(), keyTwo.getName()), + () -> Assertions.assertEquals(keyOne.getSecret(), keyTwo.getSecret())); + } + + @Test + public void testHashCodeDifferent() { + Key keyOne = new Key("name", "secret"); + Key keyTwo = new Key("differentName", "differentSecret"); + + Assertions.assertAll("Assert unequal key properties", + () -> Assertions.assertNotEquals(keyOne.hashCode(), keyTwo.hashCode()), + () -> Assertions.assertNotEquals(keyOne.getName(), keyTwo.getName()), + () -> Assertions.assertNotEquals(keyOne.getSecret(), keyTwo.getSecret())); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + Key keyOne = new Key("name", "secret"); + + Assertions.assertTrue(() -> keyOne.equals(keyOne)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObject() { + Key keyOne = new Key("name", "secret"); + Object objectTwo = new Object(); + + Assertions.assertFalse(() -> keyOne.equals(objectTwo)); + } + + @Test + public void testToString() { + Key key = new Key("testKey", "testSecret"); + String expected = "Key [name=testKey, secret=testSecret]"; + + Assertions.assertEquals(expected, key.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java new file mode 100644 index 0000000000..30b0c655cb --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java @@ -0,0 +1,38 @@ +package com.sanction.thunder.authentication; + +import io.dropwizard.auth.basic.BasicCredentials; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class ThunderAuthenticatorTest { + private static final Key key = new Key("application", "secret"); + private static final List keys = Collections.singletonList(key); + + // Test object // + private static final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys); + + @Test + public void testAuthenticateWithValidCredentials() { + BasicCredentials credentials = new BasicCredentials("application", "secret"); + + Optional result = authenticator.authenticate(credentials); + + Assertions.assertAll("Assert valid credentials", + () -> Assertions.assertTrue(result.isPresent()), + () -> Assertions.assertEquals(key, result.get())); + } + + @Test + public void testAuthenticateWithInvalidCredentials() { + BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret"); + + Optional result = authenticator.authenticate(credentials); + + Assertions.assertFalse(() -> result.isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java new file mode 100644 index 0000000000..8f691dc63c --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java @@ -0,0 +1,24 @@ +package com.sanction.thunder.dao; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class DatabaseExceptionTest { + + @Test + public void testDatabaseExceptionCreation() { + DatabaseException exception = new DatabaseException(DatabaseError.USER_NOT_FOUND); + Assertions.assertEquals(DatabaseError.USER_NOT_FOUND, exception.getErrorKind()); + + exception = new DatabaseException("Error", DatabaseError.CONFLICT); + Assertions.assertEquals(DatabaseError.CONFLICT, exception.getErrorKind()); + Assertions.assertEquals("Error", exception.getMessage()); + + exception = new DatabaseException("Error", new Exception(), DatabaseError.DATABASE_DOWN); + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, exception.getErrorKind()); + Assertions.assertEquals("Error", exception.getMessage()); + + exception = new DatabaseException(new Exception(), DatabaseError.REQUEST_REJECTED); + Assertions.assertEquals(DatabaseError.REQUEST_REJECTED, exception.getErrorKind()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java new file mode 100644 index 0000000000..23143b8f1f --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java @@ -0,0 +1,42 @@ +package com.sanction.thunder.dao; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; + +import java.io.IOException; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UsersDaoTest { + private final ObjectMapper mapper = Jackson.newObjectMapper(); + private final ObjectMapper mockedMapper = mock(ObjectMapper.class); + private final User testUser = new User(new Email("test", false, "token"), "password", null); + + @Test + public void testJsonProcessingException() throws Exception { + when(mockedMapper.writeValueAsString(any())).thenThrow(JsonProcessingException.class); + + Assertions.assertThrows(RuntimeException.class, () -> { + UsersDao.toJson(mockedMapper, testUser); + }); + } + + @Test + public void testIoException() throws Exception { + when(mockedMapper.readValue(any(String.class), User.class)).thenThrow(IOException.class); + + Assertions.assertThrows(RuntimeException.class, () -> { + UsersDao.fromJson(mockedMapper, mapper.writeValueAsString(testUser)); + }); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java new file mode 100644 index 0000000000..aebf02f420 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java @@ -0,0 +1,80 @@ +package com.sanction.thunder.dao.dynamodb; + +import com.amazonaws.services.dynamodbv2.document.DynamoDB; +import com.amazonaws.services.dynamodbv2.document.Page; +import com.amazonaws.services.dynamodbv2.document.Table; +import com.amazonaws.services.dynamodbv2.document.TableCollection; +import com.amazonaws.services.dynamodbv2.model.ListTablesResult; + +import com.codahale.metrics.health.HealthCheck; + +import java.util.Collections; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DynamoDbHealthCheckTest extends HealthCheck { + @SuppressWarnings("unchecked") + private static final TableCollection tables = mock(TableCollection.class); + private static final DynamoDB dynamo = mock(DynamoDB.class); + private static final DynamoDbHealthCheck healthCheck = new DynamoDbHealthCheck(dynamo); + + @BeforeAll + public static void setup() { + when(dynamo.listTables()).thenReturn(tables); + } + + @Test + public void testNullDynamoObject() { + Assertions.assertThrows(NullPointerException.class, () -> { + new DynamoDbHealthCheck(null); + }); + } + + @Test + public void testCheckHealthy() { + when(tables.firstPage()).thenReturn( + new Page( + Collections.singletonList(mock(Table.class)), + mock(ListTablesResult.class)) { + @Override + public boolean hasNextPage() { + return false; + } + + @Override + public Page nextPage() { + return null; + } + }); + + Assertions.assertTrue(() -> healthCheck.check().isHealthy()); + } + + @Test + public void testCheckUnhealthy() { + when(tables.firstPage()).thenReturn( + new Page(Collections.emptyList(), mock(ListTablesResult.class)) { + @Override + public boolean hasNextPage() { + return false; + } + + @Override + public Page nextPage() { + return null; + } + }); + + Assertions.assertFalse(() -> healthCheck.check().isHealthy()); + } + + // Not used - exists in order to extend HealthCheck + protected Result check() { + return Result.healthy(); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java new file mode 100644 index 0000000000..e1f5a11994 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java @@ -0,0 +1,342 @@ +package com.sanction.thunder.dao.dynamodb; + +import com.amazonaws.AmazonClientException; +import com.amazonaws.AmazonServiceException; +import com.amazonaws.services.dynamodbv2.document.Expected; +import com.amazonaws.services.dynamodbv2.document.Item; +import com.amazonaws.services.dynamodbv2.document.Table; +import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec; +import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; + +import java.util.Collections; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DynamoDbUsersDaoTest { + private final Table table = mock(Table.class); + private final Item item = mock(Item.class); + private final ObjectMapper mapper = Jackson.newObjectMapper(); + + private final Email email = new Email("email", true, "hashToken"); + + private final User user = new User( + email, "password", + Collections.singletonMap("facebookAccessToken", "fb")); + + private final UsersDao usersDao = new DynamoDbUsersDao(table, mapper); + + @BeforeEach + public void setup() { + when(item.getJSON(anyString())).thenReturn(UsersDao.toJson(mapper, user)); + when(item.getString(anyString())).thenReturn("example"); + + when(item.withString(anyString(), anyString())).thenReturn(item); + when(item.withLong(anyString(), anyLong())).thenReturn(item); + when(item.withJSON(anyString(), anyString())).thenReturn(item); + } + + @Test + public void testSuccessfulInsert() { + User result = usersDao.insert(user); + + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + Assertions.assertEquals(user, result); + } + + @Test + @SuppressWarnings("unchecked") + public void testConflictingInsert() { + when(table.putItem(any(), any())).thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.CONFLICT, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testInsertWithUnsupportedData() { + when(table.putItem(any(), any())).thenThrow(AmazonServiceException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.REQUEST_REJECTED, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testInsertWithDatabaseDown() { + when(table.putItem(any(), any())).thenThrow(AmazonClientException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + public void testSuccessfulFindByEmail() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.findByEmail("email"); + + verify(table, times(1)).getItem(anyString(), anyString()); + Assertions.assertEquals(user, result); + } + + @Test + public void testUnsuccessfulFindByEmail() { + when(table.getItem(anyString(), anyString())).thenReturn(null); + + try { + usersDao.findByEmail("email"); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testFindByEmailDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.findByEmail("email"); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + public void testSuccessfulUpdate() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.update(null, user); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + Assertions.assertEquals(user, result); + } + + @Test + public void testSuccessfulEmailUpdate() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.update("existingEmail", user); + + Assertions.assertEquals(user, result); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + } + + @Test + public void testUpdateGetNotFound() { + when(table.getItem(anyString(), anyString())).thenReturn(null); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdateGetDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutConflict() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.CONFLICT, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutUnsupportedData() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(AmazonServiceException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.REQUEST_REJECTED, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(AmazonClientException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + public void testSuccessfulDelete() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.delete("email"); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + Assertions.assertEquals(user, result); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteGetFailure() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteNotFound() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.deleteItem(any(DeleteItemSpec.class))) + .thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.deleteItem(any(DeleteItemSpec.class))) + .thenThrow(AmazonClientException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + Assertions.assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + + return; + } + + Assertions.fail("Database exception not thrown."); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java new file mode 100644 index 0000000000..965d2ddcc8 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java @@ -0,0 +1,22 @@ +package com.sanction.thunder.email; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class EmailExceptionTest { + + @Test + public void testEmailExceptionCreation() { + EmailException exception = new EmailException(); + Assertions.assertNull(exception.getMessage()); + + exception = new EmailException("Test message"); + Assertions.assertEquals("Test message", exception.getMessage()); + + exception = new EmailException("Test message", new Exception()); + Assertions.assertEquals("Test message", exception.getMessage()); + + exception = new EmailException(new Exception()); + Assertions.assertEquals(Exception.class, exception.getCause().getClass()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java new file mode 100644 index 0000000000..365f1799ae --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java @@ -0,0 +1,94 @@ +package com.sanction.thunder.email; + +import com.google.common.base.Charsets; +import com.google.common.io.Resources; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EmailModuleTest { + private static final EmailConfiguration EMAIL_CONFIG = mock(EmailConfiguration.class); + + @BeforeAll + public static void setup() { + when(EMAIL_CONFIG.getEndpoint()).thenReturn("http://localhost:4567"); + when(EMAIL_CONFIG.getRegion()).thenReturn("us-east-1"); + when(EMAIL_CONFIG.getFromAddress()).thenReturn("test@test.com"); + } + + @Test + public void testProvideSuccessHtmlDefault() throws IOException { + when(EMAIL_CONFIG.getSuccessHtmlPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("success.html"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideSuccessHtml()); + } + + @Test + public void testProvideSuccessHtmlCustom() throws Exception { + when(EMAIL_CONFIG.getSuccessHtmlPath()).thenReturn(new File( + Resources.getResource("fixtures/success-page.html").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/success-page.html"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideSuccessHtml()); + } + + @Test + public void testProvideVerificationHtmlDefault() throws IOException { + when(EMAIL_CONFIG.getVerificationHtmlPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("verification.html"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideVerificationHtml()); + } + + @Test + public void testProvideVerificationHtmlCustom() throws Exception { + when(EMAIL_CONFIG.getVerificationHtmlPath()).thenReturn(new File( + Resources.getResource("fixtures/verification-email.html").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/verification-email.html"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideVerificationHtml()); + } + + @Test + public void testProvideVerificationTextDefault() throws IOException { + when(EMAIL_CONFIG.getVerificationTextPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("verification.txt"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideVerificationText()); + } + + @Test + public void testProvideVerificationTextCustom() throws Exception { + when(EMAIL_CONFIG.getVerificationTextPath()).thenReturn(new File( + Resources.getResource("fixtures/verification-email.txt").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/verification-email.txt"), Charsets.UTF_8); + Assertions.assertEquals(expected, emailModule.provideVerificationText()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java new file mode 100644 index 0000000000..9c2432a13a --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java @@ -0,0 +1,46 @@ +package com.sanction.thunder.email; + +import com.amazonaws.AmazonClientException; +import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; +import com.amazonaws.services.simpleemail.model.SendEmailResult; + +import com.sanction.thunder.models.Email; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EmailServiceTest { + private static final String SUBJECT_STRING = "Account Verification"; + private static final String HTML_BODY_STRING = "HTML"; + private static final String BODY_STRING = "TEXT"; + + private final AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); + private final SendEmailResult result = mock(SendEmailResult.class); + + private final Email mockEmail = new Email("test@test.com", false, "verificationToken"); + + private final EmailService resource = new EmailService(emailService, "testAddress"); + + @Test + @SuppressWarnings("unchecked") + public void testSendEmailAmazonClientException() { + when(emailService.sendEmail(any())).thenThrow(AmazonClientException.class); + + boolean result = resource.sendEmail(mockEmail, SUBJECT_STRING, HTML_BODY_STRING, BODY_STRING); + + Assertions.assertFalse(result); + } + + @Test + public void testSendEmailSuccess() { + when(emailService.sendEmail(any())).thenReturn(result); + + boolean result = resource.sendEmail(mockEmail, SUBJECT_STRING, HTML_BODY_STRING, BODY_STRING); + + Assertions.assertTrue(result); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java new file mode 100644 index 0000000000..1405e8237b --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java @@ -0,0 +1,385 @@ +package com.sanction.thunder.resources; + +import com.codahale.metrics.MetricRegistry; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; +import com.sanction.thunder.validation.PropertyValidator; + +import java.util.Collections; +import javax.ws.rs.core.Response; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UserResourceTest { + private final Email badEmail = new Email("badEmail", false, ""); + private final Email email = new Email("test@test.com", false, ""); + private final User user = new User(email, "password", Collections.emptyMap()); + private final User updatedUser = new User(email, "newPassword", Collections.emptyMap()); + + private final UsersDao usersDao = mock(UsersDao.class); + private final PropertyValidator validator = mock(PropertyValidator.class); + private final MetricRegistry metrics = new MetricRegistry(); + private final Key key = mock(Key.class); + + private final UserResource resource = new UserResource(usersDao, validator, metrics); + + @BeforeEach + public void setup() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(true); + } + + @Test + public void testPostNullUser() { + Response response = resource.postUser(key, null); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserNullEmail() { + User user = new User(null, "password", Collections.emptyMap()); + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserInvalidEmail() { + User user = new User(badEmail, "password", Collections.emptyMap()); + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserInvalidProperties() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(false); + + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserDatabaseDown() { + when(usersDao.insert(any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testPostUserUnsupportedData() { + when(usersDao.insert(any(User.class))).thenThrow( + new DatabaseException(DatabaseError.REQUEST_REJECTED)); + + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.INTERNAL_SERVER_ERROR, response.getStatusInfo()); + } + + @Test + public void testPostUserConflict() { + when(usersDao.insert(any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.CONFLICT)); + + Response response = resource.postUser(key, user); + + Assertions.assertEquals(Response.Status.CONFLICT, response.getStatusInfo()); + } + + @Test + public void testPostUser() { + when(usersDao.insert(any(User.class))).thenReturn(updatedUser); + + Response response = resource.postUser(key, user); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal user when posting.", + () -> Assertions.assertEquals(Response.Status.CREATED, response.getStatusInfo()), + () -> Assertions.assertEquals(updatedUser, result)); + } + + @Test + public void testUpdateNullUser() { + Response response = resource.updateUser(key, "password", null, null); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserNullEmail() { + User user = new User(null, "password", Collections.emptyMap()); + Response response = resource.updateUser(key, "password", email.getAddress(), user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserInvalidEmail() { + User user = new User(badEmail, "password", Collections.emptyMap()); + Response response = resource.updateUser(key, "password", email.getAddress(), user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserWithNullPassword() { + Response response = resource.updateUser(key, null, null, user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserInvalidProperties() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(false); + + Response response = resource.updateUser(key, "password", null, user); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.updateUser(key, "password", null, user); + + Assertions.assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.updateUser(key, "password", null, user); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupUnsupportedData() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.REQUEST_REJECTED)); + + Response response = resource.updateUser(key, "password", null, user); + + Assertions.assertEquals(Response.Status.INTERNAL_SERVER_ERROR, response.getStatusInfo()); + } + + @Test + public void testUpdateUserMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.updateUser(key, "incorrectPassword", null, updatedUser); + + Assertions.assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testUpdateUserNotFound() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + Assertions.assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testUpdateUserConflict() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.CONFLICT)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + Assertions.assertEquals(Response.Status.CONFLICT, response.getStatusInfo()); + } + + @Test + public void testUpdateUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testUpdateUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)).thenReturn(updatedUser); + + Response response = resource.updateUser(key, "password", null, updatedUser); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal user when updating.", + () -> Assertions.assertEquals(Response.Status.OK, response.getStatusInfo()), + () -> Assertions.assertEquals(updatedUser, result)); + } + + @Test + public void testUpdateUserWithNewEmail() { + when(usersDao.findByEmail("existingEmail")).thenReturn(user); + when(usersDao.update("existingEmail", updatedUser)).thenReturn(updatedUser); + + Response response = resource.updateUser(key, "password", "existingEmail", updatedUser); + User result = (User) response.getEntity(); + Assertions.assertAll("Assert equal user when using new email.", + () -> Assertions.assertEquals(Response.Status.OK, response.getStatusInfo()), + () -> Assertions.assertEquals(updatedUser, result)); + } + + @Test + public void testGetUserWithNullEmail() { + Response response = resource.getUser(key, "password", null); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testGetUserWithNullPassword() { + Response response = resource.getUser(key, null, email.getAddress()); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testGetUserNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.getUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testGetUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.getUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testGetUserPasswordMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.getUser(key, "incorrectPassword", email.getAddress()); + + Assertions.assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testGetUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.getUser(key, "password", email.getAddress()); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal user when getting user.", + () -> Assertions.assertEquals(Response.Status.OK, response.getStatusInfo()), + () -> Assertions.assertEquals(user, result)); + } + + @Test + public void testDeleteUserWithNullEmail() { + Response response = resource.deleteUser(key, "password", null); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testDeleteUserWithNullPassword() { + Response response = resource.deleteUser(key, null, email.getAddress()); + + Assertions.assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testDeleteUserLookupNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testDeleteUserLookupDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testDeleteUserPasswordMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.deleteUser(key, "incorrectPassword", email.getAddress()); + + Assertions.assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testDeleteUserNotFound() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testDeleteUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + Assertions.assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testDeleteUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())).thenReturn(user); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal user when deleting.", + () -> Assertions.assertEquals(Response.Status.OK, response.getStatusInfo()), + () -> Assertions.assertEquals(user, result)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java new file mode 100644 index 0000000000..b799847711 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java @@ -0,0 +1,263 @@ +package com.sanction.thunder.resources; + +import com.codahale.metrics.MetricRegistry; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.email.EmailService; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.ResponseType; +import com.sanction.thunder.models.User; + +import java.net.URI; +import java.util.Collections; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class VerificationResourceTest { + private static final String URL = "http://www.test.com/"; + private static final String SUCCESS_HTML = "success!"; + private static final String VERIFICATION_HTML = "Verify"; + private static final String VERIFICATION_TEXT = "Verify"; + + private final EmailService emailService = mock(EmailService.class); + private final MetricRegistry metrics = new MetricRegistry(); + private final UsersDao usersDao = mock(UsersDao.class); + private final Key key = mock(Key.class); + + private static final UriInfo uriInfo = mock(UriInfo.class); + private static final UriBuilder uriBuilder = mock(UriBuilder.class); + + private final User unverifiedMockUser = + new User(new Email("test@test.com", false, "verificationToken"), + "password", Collections.emptyMap()); + private final User verifiedMockUser = + new User(new Email("test@test.com", true, "verificationToken"), + "password", Collections.emptyMap()); + private final User nullDatabaseTokenMockUser = + new User(new Email("test@test.com", false, null), + "password", Collections.emptyMap()); + private final User mismatchedTokenMockUser = + new User(new Email("test@test.com", false, "mismatchedToken"), + "password", Collections.emptyMap()); + + private final VerificationResource resource = + new VerificationResource(usersDao, metrics, emailService, SUCCESS_HTML, VERIFICATION_HTML, + VERIFICATION_TEXT); + + @BeforeAll + public static void setup() throws Exception { + when(uriBuilder.path(anyString())).thenReturn(uriBuilder); + when(uriBuilder.queryParam(anyString(), any())).thenReturn(uriBuilder); + when(uriBuilder.build()).thenReturn(new URI(URL)); + + when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder); + } + + /* Verify User Tests */ + @Test + public void testCreateVerificationEmailWithNullEmail() { + Response response = resource.createVerificationEmail(uriInfo, key, null, "password"); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testCreateVerificationEmailWithNullPassword() { + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", null); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testCreateVerificationEmailFindUserException() { + when(usersDao.findByEmail(anyString())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testCreateVerificationEmailUpdateUserException() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testCreateVerificationEmailSendEmailFailure() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(false); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR); + } + + @Test + public void testCreateVerificationEmailSuccess() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(true); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal email when creating new email", + () -> Assertions.assertEquals(response.getStatusInfo(), Response.Status.OK), + () -> Assertions.assertEquals(unverifiedMockUser, result)); + + // Verify that the correct HTML and Text were used to send the email + verify(emailService).sendEmail( + any(Email.class), eq("Account Verification"), eq(VERIFICATION_HTML), eq(VERIFICATION_TEXT)); + } + + @Test + public void testCreateVerificationEmailCorrectUrl() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(true); + + String verificationHtml = "Verify CODEGEN-URL"; + String verificationText = "Verify CODEGEN-URL"; + VerificationResource resource = new VerificationResource( + usersDao, metrics, emailService, SUCCESS_HTML, verificationHtml, verificationText); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal email when creating URL", + () -> Assertions.assertEquals(response.getStatusInfo(), Response.Status.OK), + () -> Assertions.assertEquals(unverifiedMockUser, result)); + + // Verify that the correct HTML and Text were used to send the email + String expectedVerificationHtml = "Verify " + URL + ""; + String expectedVerificationText = "Verify " + URL; + verify(emailService).sendEmail( + any(Email.class), eq("Account Verification"), + eq(expectedVerificationHtml), eq(expectedVerificationText)); + } + + /* Verify Email Tests */ + @Test + public void testVerifyEmailWithNullEmail() { + Response response = resource.verifyEmail(null, "verificationToken", ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailWithNullToken() { + Response response = resource.verifyEmail("test@test.com", null, ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailFindUserException() { + when(usersDao.findByEmail(anyString())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testVerifyEmailWithNullDatabaseToken() { + when(usersDao.findByEmail(anyString())).thenReturn(nullDatabaseTokenMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR); + } + + @Test + public void testVerifyEmailWithMismatchedToken() { + when(usersDao.findByEmail(anyString())).thenReturn(mismatchedTokenMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailUpdateUserException() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + Assertions.assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testVerifyEmailSuccess() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenReturn(verifiedMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + User result = (User) response.getEntity(); + + Assertions.assertAll("Assert equal email on success", + () -> Assertions.assertEquals(response.getStatusInfo(), Response.Status.OK), + () -> Assertions.assertEquals(verifiedMockUser, result)); + } + + @Test + public void testVerifyEmailWithHtmlResponse() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenReturn(verifiedMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.HTML); + URI result = response.getLocation(); + + Assertions.assertAll("Assert equal email URL on success", + () -> Assertions.assertEquals(response.getStatusInfo(), Response.Status.SEE_OTHER), + () -> Assertions.assertEquals(UriBuilder.fromUri("/verify/success").build(), result)); + } + + /* HTML Success Tests */ + @Test + public void testGetSuccessHtml() { + Response response = resource.getSuccessHtml(); + String result = (String) response.getEntity(); + + Assertions.assertAll("Assert equal response HTML on success", + () -> Assertions.assertEquals(Response.Status.OK, response.getStatusInfo()), + () -> Assertions.assertEquals(SUCCESS_HTML, result)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java new file mode 100644 index 0000000000..67e575c3c7 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java @@ -0,0 +1,26 @@ +package com.sanction.thunder.util; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class EmailUtilitiesTest { + private static final String URL_PLACEHOLDER = "CODEGEN-URL"; + + @Test + public void testReplacePlaceholderNoUrl() { + String contents = "test contents"; + String url = "http://www.test.com"; + + Assertions.assertEquals(contents, EmailUtilities.replaceUrlPlaceholder(contents, url)); + } + + @Test + public void testReplacePlaceholderWithUrl() { + String contents = "test contents " + URL_PLACEHOLDER; + String url = "http://www.test.com"; + + String expected = "test contents " + url; + + Assertions.assertEquals(expected, EmailUtilities.replaceUrlPlaceholder(contents, url)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java new file mode 100644 index 0000000000..41fe1e5bbe --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java @@ -0,0 +1,54 @@ +package com.sanction.thunder.validation; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class PropertyValidationRuleTest { + + @Test + public void testHashCodeSame() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "string"); + PropertyValidationRule ruleTwo = new PropertyValidationRule("name", "string"); + + Assertions.assertAll("Assert equal PropertyValidationRule properties.", + () -> Assertions.assertEquals(ruleOne.hashCode(), ruleTwo.hashCode()), + () -> Assertions.assertEquals(ruleOne.getName(), ruleTwo.getName()), + () -> Assertions.assertEquals(ruleOne.getType(), ruleTwo.getType())); + } + + @Test + public void testHashCodeDifferent() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "string"); + PropertyValidationRule ruleTwo = new PropertyValidationRule("differentName", "integer"); + + Assertions.assertAll("Assert unequal PropertyValidationRule properties.", + () -> Assertions.assertNotEquals(ruleOne.hashCode(), ruleTwo.hashCode()), + () -> Assertions.assertNotEquals(ruleOne.getName(), ruleTwo.getName()), + () -> Assertions.assertNotEquals(ruleOne.getType(), ruleTwo.getType())); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "list"); + + Assertions.assertTrue(ruleOne.equals(ruleOne)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObject() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "map"); + Object objectTwo = new Object(); + + Assertions.assertFalse(ruleOne.equals(objectTwo)); + } + + @Test + public void testToString() { + PropertyValidationRule rule = new PropertyValidationRule("testName", "string"); + String expected = "PropertyValidationRule [name=testName, type=class java.lang.String]"; + + Assertions.assertEquals(expected, rule.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java new file mode 100644 index 0000000000..8d3768cf86 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java @@ -0,0 +1,225 @@ +package com.sanction.thunder.validation; + +import com.google.common.collect.ImmutableMap; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class PropertyValidatorTest { + private final Map properties = new HashMap<>(); + private List validationRules + = Collections.singletonList( + new PropertyValidationRule("firstProperty", "string")); + + @Test + public void testSkipValidation() { + PropertyValidator validator = new PropertyValidator(null); + Map properties = Collections.emptyMap(); + + Assertions.assertTrue(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testInvalidSize() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.emptyMap(); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testMismatchName() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("myProperty", "value"); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* String type */ + @Test + public void testMismatchTypeString() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("firstProperty", 1); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulStringValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("firstProperty", "value"); + + Assertions.assertTrue(validator.isValidPropertiesMap(properties)); + } + + /* Integer type */ + @Test + public void testMismatchTypeInteger() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", "1"); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulIntegerValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Boolean type */ + @Test + public void testMismatchTypeBoolean() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", "false"); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulBooleanValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Boolean type */ + @Test + public void testMismatchTypeDouble() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulDoubleValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* List type */ + @Test + public void testMismatchTypeList() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double"), + new PropertyValidationRule("fifthProperty", "list")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyMap()); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulListValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyList()); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Map type */ + @Test + public void testMismatchTypeMap() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double"), + new PropertyValidationRule("fifthProperty", "list"), + new PropertyValidationRule("sixthProperty", "map")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyList()); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulMapValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyMap()); + + Assertions.assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testGetType() { + Assertions.assertAll("Assert equal return value from getType PropertyValidator method.", + () -> Assertions.assertEquals(String.class, PropertyValidator.getType("string")), + () -> Assertions.assertEquals(Integer.class, PropertyValidator.getType("integer")), + () -> Assertions.assertEquals(Boolean.class, PropertyValidator.getType("boolean")), + () -> Assertions.assertEquals(Double.class, PropertyValidator.getType("double")), + () -> Assertions.assertEquals(List.class, PropertyValidator.getType("list")), + () -> Assertions.assertEquals(Map.class, PropertyValidator.getType("map")), + () -> Assertions.assertEquals(Object.class, PropertyValidator.getType("unknown"))); + } +} diff --git a/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/client/src/test/java/com/sanction/thunder/ThunderClientTest.java b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/client/src/test/java/com/sanction/thunder/ThunderClientTest.java new file mode 100644 index 0000000000..b33d5afdd1 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-48776d511a0152f7b9cbe4460c8967bdd5ec3dc4/client/src/test/java/com/sanction/thunder/ThunderClientTest.java @@ -0,0 +1,237 @@ +package com.sanction.thunder; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.ResponseType; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.junit.DropwizardClientRule; + +import java.io.IOException; +import java.util.Collections; + +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import okhttp3.ResponseBody; + +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class ThunderClientTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + private static final Email email = new Email("test@test.com", true, "hashToken"); + private static final String password = "password"; + private static final User user = new User(email, password, Collections.emptyMap()); + + /** + * Resource to be used as a test double. Requests from the ThunderClient interface + * will be directed here for the unit tests. Use this to verify that all parameters are + * being set correctly. + */ + @Path("/") + @Produces(MediaType.APPLICATION_JSON) + public static final class TestResource { + + /** + * Sample postUser method. The user object must be present. + */ + @POST + @Path("users") + public Response postUser(User user) { + if (user == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.CREATED) + .entity(user).build(); + } + + /** + * Sample updateUser method. The password and user object must be present. + */ + @PUT + @Path("users") + public Response updateUser(@QueryParam("email") String existingEmail, + @HeaderParam("password") String password, + User user) { + if (password == null || password.isEmpty() || user == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample getUser method. The email and password must be present. + */ + @GET + @Path("users") + public Response getUser(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample deleteUser method. The email and password must be present. + */ + @DELETE + @Path("users") + public Response deleteUser(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample sendEmail method. The email and password must be present. + */ + @POST + @Path("verify") + public Response sendEmail(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample verifyUser method. The email and token must be present. + */ + @GET + @Path("verify") + public Response verifyUser(@QueryParam("email") String email, + @QueryParam("token") String token, + @QueryParam("response_type") @DefaultValue("json") + ResponseType responseType) { + if (email == null || email.isEmpty() || token == null || token.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + if (responseType.equals(ResponseType.HTML)) { + return Response.ok("HTML Here").build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + } + + @ClassRule + public static final DropwizardClientRule dropwizard + = new DropwizardClientRule(new TestResource()); + + private final ThunderBuilder builder = + new ThunderBuilder(dropwizard.baseUri().toString() + "/", "userKey", "userSecret"); + private final ThunderClient client = builder.newThunderClient(); + + @Test + @SuppressWarnings("ConstantConditions") + public void testPostUser() throws IOException { + User response = client.postUser(user) + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testUpdateUser() throws IOException { + User response = client.updateUser(user, "email", password) + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testGetUser() throws IOException { + User response = client.getUser("email", password) + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testDeleteUser() throws IOException { + User response = client.deleteUser("email", password) + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testSendVerificationEmail() throws IOException { + User response = client.sendVerificationEmail("email", password) + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUser() throws IOException { + User response = client.verifyUser("email", "token") + .execute() + .body(); + + Assertions.assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUserHtml() throws IOException { + ResponseBody response = client.verifyUser("email", "token", ResponseType.HTML) + .execute() + .body(); + + Assertions.assertEquals("HTML Here", response.string()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUserJson() throws IOException { + ResponseBody response = client.verifyUser("email", "token", ResponseType.JSON) + .execute() + .body(); + + Assertions.assertEquals(user, MAPPER.readValue(response.string(), User.class)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/EmailTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/EmailTest.java new file mode 100644 index 0000000000..66ad51671b --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/EmailTest.java @@ -0,0 +1,77 @@ +package com.sanction.thunder.models; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.FixtureHelpers; + +import java.util.StringJoiner; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class EmailTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + + private final Email email = new Email("test@test.com", true, "token"); + + @Test + public void testToJson() throws Exception { + String expected = MAPPER.writeValueAsString( + MAPPER.readValue(FixtureHelpers.fixture("fixtures/email.json"), Email.class)); + + assertEquals(expected, MAPPER.writeValueAsString(email)); + } + + @Test + public void testFromJson() throws Exception { + Email fromJson = MAPPER.readValue(FixtureHelpers.fixture("fixtures/email.json"), Email.class); + + assertEquals(email, fromJson); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + assertTrue(email.equals(email)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObjectType() { + Object objectTwo = new Object(); + + assertFalse(email.equals(objectTwo)); + } + + @Test + public void testHashCodeSame() { + Email emailOne = new Email("test@test.com", true, "token"); + Email emailTwo = new Email("test@test.com", true, "token"); + + assertEquals(emailOne.hashCode(), emailTwo.hashCode()); + } + + @Test + public void testHashCodeDifferent() { + Email emailOne = new Email("test@test.com", true, "token"); + Email emailTwo = new Email("differentTest@test.com", true, "token"); + + assertNotEquals(emailOne.hashCode(), emailTwo.hashCode()); + } + + @Test + public void testToString() { + String expected = new StringJoiner(", ", "Email [", "]") + .add(String.format("address=%s", "test@test.com")) + .add(String.format("verified=%b", "true")) + .add(String.format("verificationToken=%s", "token")) + .toString(); + + assertEquals(expected, email.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java new file mode 100644 index 0000000000..9d1788db47 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/ResponseTypeTest.java @@ -0,0 +1,26 @@ +package com.sanction.thunder.models; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class ResponseTypeTest { + + @Test + public void testJsonResponseType() { + assertEquals(ResponseType.JSON, ResponseType.fromString("json")); + assertEquals("json", ResponseType.JSON.toString()); + } + + @Test + public void testHtmlResponseType() { + assertEquals(ResponseType.HTML, ResponseType.fromString("html")); + assertEquals("html", ResponseType.HTML.toString()); + } + + @Test + public void testNullResponseTypeFromString() { + assertNull(ResponseType.fromString("unknown")); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/UserTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/UserTest.java new file mode 100644 index 0000000000..6db6a0e9fe --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/api/src/test/java/com/sanction/thunder/models/UserTest.java @@ -0,0 +1,128 @@ +package com.sanction.thunder.models; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.FixtureHelpers; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.StringJoiner; +import java.util.TreeMap; + +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class UserTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + private static final Email EMAIL = new Email("test@test.com", true, "hashToken"); + private static final String PASSWORD = "12345"; + private static final Map MULTIPLE_PROPERTY_MAP = new TreeMap<>(); + + private final User emptyPropertiesUser = new User(EMAIL, PASSWORD, Collections.emptyMap()); + private final User multiplePropertiesUser = new User(EMAIL, PASSWORD, MULTIPLE_PROPERTY_MAP); + + @BeforeClass + public static void setup() { + MULTIPLE_PROPERTY_MAP.put("customString", "value"); + MULTIPLE_PROPERTY_MAP.put("customInt", 1); + MULTIPLE_PROPERTY_MAP.put("customDouble", 1.2); + MULTIPLE_PROPERTY_MAP.put("customBoolean", true); + MULTIPLE_PROPERTY_MAP.put("customList", Arrays.asList("hello", "world")); + } + + @Test + public void testToJsonNoProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/no_properties_user.json"), User.class)); + + assertEquals(expected, MAPPER.writeValueAsString(emptyPropertiesUser)); + } + + @Test + public void testFromJsonNoProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/no_properties_user.json"), User.class); + + assertEquals(emptyPropertiesUser, fromJson); + } + + @Test + public void testToJsonEmptyProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/empty_properties_user.json"),User.class)); + + assertEquals(expected, MAPPER.writeValueAsString(emptyPropertiesUser)); + } + + @Test + public void testFromJsonEmptyProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/empty_properties_user.json"), User.class); + + assertEquals(emptyPropertiesUser, fromJson); + } + + @Test + public void testToJsonMultipleProperties() throws Exception { + String expected = MAPPER.writeValueAsString(MAPPER.readValue( + FixtureHelpers.fixture("fixtures/multiple_properties_user.json"), User.class)); + + assertEquals(expected, MAPPER.writeValueAsString(multiplePropertiesUser)); + } + + @Test + public void testFromJsonMultipleProperties() throws Exception { + User fromJson = MAPPER.readValue( + FixtureHelpers.fixture("fixtures/multiple_properties_user.json"), User.class); + + assertEquals(multiplePropertiesUser, fromJson); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + assertTrue(multiplePropertiesUser.equals(multiplePropertiesUser)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObjectType() { + Object objectTwo = new Object(); + + assertFalse(multiplePropertiesUser.equals(objectTwo)); + } + + @Test + public void testHashCodeSame() { + User userOne = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + User userTwo = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + + assertEquals(userOne.hashCode(), userTwo.hashCode()); + } + + @Test + public void testHashCodeDifferent() { + User userOne = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 1)); + User userTwo = new User(EMAIL, PASSWORD, Collections.singletonMap("customKey", 2)); + + assertNotEquals(userOne.hashCode(), userTwo.hashCode()); + } + + @Test + public void testToString() { + String expected = new StringJoiner(", ", "User [", "]") + .add(String.format("email=%s", EMAIL)) + .add(String.format("password=%s", PASSWORD)) + .add(String.format("properties=%s", MULTIPLE_PROPERTY_MAP)) + .toString(); + + assertEquals(expected, multiplePropertiesUser.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java new file mode 100644 index 0000000000..e2c8742af8 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderApplicationTest.java @@ -0,0 +1,94 @@ +package com.sanction.thunder; + +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.health.HealthCheckRegistry; + +import com.sanction.thunder.dao.dynamodb.DynamoDbConfiguration; +import com.sanction.thunder.dao.dynamodb.DynamoDbHealthCheck; +import com.sanction.thunder.email.EmailConfiguration; +import com.sanction.thunder.resources.UserResource; +import com.sanction.thunder.resources.VerificationResource; + +import io.dropwizard.auth.AuthDynamicFeature; +import io.dropwizard.jersey.setup.JerseyEnvironment; +import io.dropwizard.setup.Bootstrap; +import io.dropwizard.setup.Environment; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ThunderApplicationTest { + private final Environment environment = mock(Environment.class); + private final JerseyEnvironment jersey = mock(JerseyEnvironment.class); + private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class); + private final MetricRegistry metrics = mock(MetricRegistry.class); + private final ThunderConfiguration config = mock(ThunderConfiguration.class); + private final DynamoDbConfiguration dynamoConfig = mock(DynamoDbConfiguration.class); + private final EmailConfiguration emailConfig = mock(EmailConfiguration.class); + + @SuppressWarnings("unchecked") + private final Bootstrap bootstrap = mock(Bootstrap.class); + + private final ThunderApplication application = new ThunderApplication(); + + @Before + public void setup() { + when(environment.jersey()).thenReturn(jersey); + when(environment.healthChecks()).thenReturn(healthChecks); + when(environment.metrics()).thenReturn(metrics); + + when(dynamoConfig.getEndpoint()).thenReturn("http://localhost"); + when(dynamoConfig.getRegion()).thenReturn("us-east-1"); + when(dynamoConfig.getTableName()).thenReturn("sample-table"); + + when(emailConfig.getEndpoint()).thenReturn("http://localhost"); + when(emailConfig.getRegion()).thenReturn("us-east-1"); + when(emailConfig.getFromAddress()).thenReturn("testAddress@test.com"); + when(emailConfig.getSuccessHtmlPath()).thenReturn(null); + when(emailConfig.getVerificationHtmlPath()).thenReturn(null); + when(emailConfig.getVerificationTextPath()).thenReturn(null); + + // ThunderConfiguration NotNull fields + when(config.getApprovedKeys()).thenReturn(new ArrayList<>()); + when(config.getDynamoConfiguration()).thenReturn(dynamoConfig); + when(config.getEmailConfiguration()).thenReturn(emailConfig); + } + + @Test + public void testInitialize() { + application.initialize(bootstrap); + + // Nothing should happen in the initialize method + } + + @Test + public void testRun() { + ArgumentCaptor captor = ArgumentCaptor.forClass(Object.class); + + application.run(config, environment); + + // Verify register was called on jersey and healthChecks + verify(jersey, atLeastOnce()).register(captor.capture()); + verify(healthChecks, times(1)).register(eq("DynamoDB"), any(DynamoDbHealthCheck.class)); + + // Make sure each class that should have been registered on jersey was registered + List values = captor.getAllValues(); + + assertEquals(1, values.stream().filter(v -> v instanceof AuthDynamicFeature).count()); + assertEquals(1, values.stream().filter(v -> v instanceof UserResource).count()); + assertEquals(1, values.stream().filter(v -> v instanceof VerificationResource).count()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java new file mode 100644 index 0000000000..6cbaac8ea2 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/ThunderConfigurationTest.java @@ -0,0 +1,58 @@ +package com.sanction.thunder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.google.common.io.Resources; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.validation.PropertyValidationRule; + +import io.dropwizard.configuration.YamlConfigurationFactory; +import io.dropwizard.jackson.Jackson; +import io.dropwizard.jersey.validation.Validators; + +import java.io.File; +import java.util.Collections; +import javax.validation.Validator; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ThunderConfigurationTest { + private final ObjectMapper mapper = Jackson.newObjectMapper(); + private final Validator validator = Validators.newValidator(); + private final YamlConfigurationFactory factory + = new YamlConfigurationFactory<>(ThunderConfiguration.class, validator, mapper, "dw"); + + @Test + public void testFromYaml() throws Exception { + ThunderConfiguration configuration = factory.build( + new File(Resources.getResource("fixtures/config.yaml").toURI())); + + assertEquals("test.dynamodb.com", configuration.getDynamoConfiguration().getEndpoint()); + assertEquals("test-region-1", configuration.getDynamoConfiguration().getRegion()); + assertEquals("test-table", configuration.getDynamoConfiguration().getTableName()); + + assertEquals("test.email.com", configuration.getEmailConfiguration().getEndpoint()); + assertEquals("test-region-2", configuration.getEmailConfiguration().getRegion()); + assertEquals("test@sanctionco.com", configuration.getEmailConfiguration().getFromAddress()); + + assertEquals("test-success-page.html", + configuration.getEmailConfiguration().getSuccessHtmlPath()); + assertEquals("test-verification-email.html", + configuration.getEmailConfiguration().getVerificationHtmlPath()); + assertEquals("test-verification-email.txt", + configuration.getEmailConfiguration().getVerificationTextPath()); + + assertEquals(1, configuration.getApprovedKeys().size()); + assertEquals( + Collections.singletonList(new Key("test-app", "test-secret")), + configuration.getApprovedKeys()); + + assertEquals(1, configuration.getValidationRules().size()); + assertEquals( + new PropertyValidationRule("testProperty", "list"), + configuration.getValidationRules().get(0)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java new file mode 100644 index 0000000000..6734db6491 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/KeyTest.java @@ -0,0 +1,56 @@ +package com.sanction.thunder.authentication; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class KeyTest { + + @Test + public void testHashCodeSame() { + Key keyOne = new Key("name", "secret"); + Key keyTwo = new Key("name", "secret"); + + assertEquals(keyOne.hashCode(), keyTwo.hashCode()); + assertEquals(keyOne.getName(), keyTwo.getName()); + assertEquals(keyOne.getSecret(), keyTwo.getSecret()); + } + + @Test + public void testHashCodeDifferent() { + Key keyOne = new Key("name", "secret"); + Key keyTwo = new Key("differentName", "differentSecret"); + + assertNotEquals(keyOne.hashCode(), keyTwo.hashCode()); + assertNotEquals(keyOne.getName(), keyTwo.getName()); + assertNotEquals(keyOne.getSecret(), keyTwo.getSecret()); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + Key keyOne = new Key("name", "secret"); + + assertTrue(keyOne.equals(keyOne)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObject() { + Key keyOne = new Key("name", "secret"); + Object objectTwo = new Object(); + + assertFalse(keyOne.equals(objectTwo)); + } + + @Test + public void testToString() { + Key key = new Key("testKey", "testSecret"); + String expected = "Key [name=testKey, secret=testSecret]"; + + assertEquals(expected, key.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java new file mode 100644 index 0000000000..4440b024d4 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/authentication/ThunderAuthenticatorTest.java @@ -0,0 +1,42 @@ +package com.sanction.thunder.authentication; + +import io.dropwizard.auth.AuthenticationException; +import io.dropwizard.auth.basic.BasicCredentials; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class ThunderAuthenticatorTest { + private static final Key key = new Key("application", "secret"); + private static final List keys = Collections.singletonList(key); + + // Test object // + private static final ThunderAuthenticator authenticator = new ThunderAuthenticator(keys); + + @Test + public void testAuthenticateWithValidCredentials() { + BasicCredentials credentials = new BasicCredentials("application", "secret"); + + Optional result = authenticator.authenticate(credentials); + + assertTrue(result.isPresent()); + assertEquals(key, result.get()); + } + + @Test + public void testAuthenticateWithInvalidCredentials() { + BasicCredentials credentials = new BasicCredentials("invalidApplication", "secret"); + + Optional result = authenticator.authenticate(credentials); + + assertFalse(result.isPresent()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java new file mode 100644 index 0000000000..a50ff955f6 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/DatabaseExceptionTest.java @@ -0,0 +1,25 @@ +package com.sanction.thunder.dao; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class DatabaseExceptionTest { + + @Test + public void testDatabaseExceptionCreation() { + DatabaseException exception = new DatabaseException(DatabaseError.USER_NOT_FOUND); + assertEquals(DatabaseError.USER_NOT_FOUND, exception.getErrorKind()); + + exception = new DatabaseException("Error", DatabaseError.CONFLICT); + assertEquals(DatabaseError.CONFLICT, exception.getErrorKind()); + assertEquals("Error", exception.getMessage()); + + exception = new DatabaseException("Error", new Exception(), DatabaseError.DATABASE_DOWN); + assertEquals(DatabaseError.DATABASE_DOWN, exception.getErrorKind()); + assertEquals("Error", exception.getMessage()); + + exception = new DatabaseException(new Exception(), DatabaseError.REQUEST_REJECTED); + assertEquals(DatabaseError.REQUEST_REJECTED, exception.getErrorKind()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java new file mode 100644 index 0000000000..c5eec6ab77 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/UsersDaoTest.java @@ -0,0 +1,37 @@ +package com.sanction.thunder.dao; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; + +import java.io.IOException; + +import org.junit.Test; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UsersDaoTest { + private final ObjectMapper mapper = Jackson.newObjectMapper(); + private final ObjectMapper mockedMapper = mock(ObjectMapper.class); + private final User testUser = new User(new Email("test", false, "token"), "password", null); + + @Test(expected = RuntimeException.class) + public void testJsonProcessingException() throws Exception { + when(mockedMapper.writeValueAsString(any())).thenThrow(JsonProcessingException.class); + + UsersDao.toJson(mockedMapper, testUser); + } + + @Test(expected = RuntimeException.class) + public void testIoException() throws Exception { + when(mockedMapper.readValue(any(String.class), User.class)).thenThrow(IOException.class); + + UsersDao.fromJson(mockedMapper, mapper.writeValueAsString(testUser)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java new file mode 100644 index 0000000000..a0c1aa7b83 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbHealthCheckTest.java @@ -0,0 +1,79 @@ +package com.sanction.thunder.dao.dynamodb; + +import com.amazonaws.services.dynamodbv2.document.DynamoDB; +import com.amazonaws.services.dynamodbv2.document.Page; +import com.amazonaws.services.dynamodbv2.document.Table; +import com.amazonaws.services.dynamodbv2.document.TableCollection; +import com.amazonaws.services.dynamodbv2.model.ListTablesResult; + +import com.codahale.metrics.health.HealthCheck; + +import java.util.Collections; + +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DynamoDbHealthCheckTest extends HealthCheck { + @SuppressWarnings("unchecked") + private static final TableCollection tables = mock(TableCollection.class); + private static final DynamoDB dynamo = mock(DynamoDB.class); + private static final DynamoDbHealthCheck healthCheck = new DynamoDbHealthCheck(dynamo); + + @BeforeClass + public static void setup() { + when(dynamo.listTables()).thenReturn(tables); + } + + @Test(expected = NullPointerException.class) + public void testNullDynamoObject() { + new DynamoDbHealthCheck(null); + } + + @Test + public void testCheckHealthy() { + when(tables.firstPage()).thenReturn( + new Page( + Collections.singletonList(mock(Table.class)), + mock(ListTablesResult.class)) { + @Override + public boolean hasNextPage() { + return false; + } + + @Override + public Page nextPage() { + return null; + } + }); + + assertTrue(healthCheck.check().isHealthy()); + } + + @Test + public void testCheckUnhealthy() { + when(tables.firstPage()).thenReturn( + new Page(Collections.emptyList(), mock(ListTablesResult.class)) { + @Override + public boolean hasNextPage() { + return false; + } + + @Override + public Page nextPage() { + return null; + } + }); + + assertFalse(healthCheck.check().isHealthy()); + } + + // Not used - exists in order to extend HealthCheck + protected Result check() { + return Result.healthy(); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java new file mode 100644 index 0000000000..c22b41a391 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/dao/dynamodb/DynamoDbUsersDaoTest.java @@ -0,0 +1,342 @@ +package com.sanction.thunder.dao.dynamodb; + +import com.amazonaws.AmazonClientException; +import com.amazonaws.AmazonServiceException; +import com.amazonaws.services.dynamodbv2.document.Expected; +import com.amazonaws.services.dynamodbv2.document.Item; +import com.amazonaws.services.dynamodbv2.document.Table; +import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec; +import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; + +import java.util.Collections; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DynamoDbUsersDaoTest { + private final Table table = mock(Table.class); + private final Item item = mock(Item.class); + private final ObjectMapper mapper = Jackson.newObjectMapper(); + + private final Email email = new Email("email", true, "hashToken"); + + private final User user = new User( + email, "password", + Collections.singletonMap("facebookAccessToken", "fb")); + + private final UsersDao usersDao = new DynamoDbUsersDao(table, mapper); + + @Before + public void setup() { + when(item.getJSON(anyString())).thenReturn(UsersDao.toJson(mapper, user)); + when(item.getString(anyString())).thenReturn("example"); + + when(item.withString(anyString(), anyString())).thenReturn(item); + when(item.withLong(anyString(), anyLong())).thenReturn(item); + when(item.withJSON(anyString(), anyString())).thenReturn(item); + } + + @Test + public void testSuccessfulInsert() { + User result = usersDao.insert(user); + + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + assertEquals(user, result); + } + + @Test + @SuppressWarnings("unchecked") + public void testConflictingInsert() { + when(table.putItem(any(), any())).thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.CONFLICT, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testInsertWithUnsupportedData() { + when(table.putItem(any(), any())).thenThrow(AmazonServiceException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.REQUEST_REJECTED, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testInsertWithDatabaseDown() { + when(table.putItem(any(), any())).thenThrow(AmazonClientException.class); + + try { + usersDao.insert(user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + public void testSuccessfulFindByEmail() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.findByEmail("email"); + + verify(table, times(1)).getItem(anyString(), anyString()); + assertEquals(user, result); + } + + @Test + public void testUnsuccessfulFindByEmail() { + when(table.getItem(anyString(), anyString())).thenReturn(null); + + try { + usersDao.findByEmail("email"); + } catch (DatabaseException e) { + assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testFindByEmailDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.findByEmail("email"); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + fail(); + } + + @Test + public void testSuccessfulUpdate() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.update(null, user); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + assertEquals(user, result); + } + + @Test + public void testSuccessfulEmailUpdate() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.update("existingEmail", user); + + assertEquals(user, result); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + } + + @Test + public void testUpdateGetNotFound() { + when(table.getItem(anyString(), anyString())).thenReturn(null); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdateGetDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutConflict() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.CONFLICT, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutUnsupportedData() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(AmazonServiceException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.REQUEST_REJECTED, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUpdatePutDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.putItem(any(), any())).thenThrow(AmazonClientException.class); + + try { + usersDao.update(null, user); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).putItem(any(Item.class), any(Expected.class)); + + return; + } + + fail(); + } + + @Test + public void testSuccessfulDelete() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + + User result = usersDao.delete("email"); + + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + assertEquals(user, result); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteGetFailure() { + when(table.getItem(anyString(), anyString())).thenThrow(AmazonClientException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteNotFound() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.deleteItem(any(DeleteItemSpec.class))) + .thenThrow(ConditionalCheckFailedException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + assertEquals(DatabaseError.USER_NOT_FOUND, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + + return; + } + + fail(); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsuccessfulDeleteDatabaseDown() { + when(table.getItem(anyString(), anyString())).thenReturn(item); + when(table.deleteItem(any(DeleteItemSpec.class))) + .thenThrow(AmazonClientException.class); + + try { + usersDao.delete("email"); + } catch (DatabaseException e) { + assertEquals(DatabaseError.DATABASE_DOWN, e.getErrorKind()); + verify(table, times(1)).getItem(anyString(), anyString()); + verify(table, times(1)).deleteItem(any(DeleteItemSpec.class)); + + return; + } + + fail(); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java new file mode 100644 index 0000000000..374fb2f051 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailExceptionTest.java @@ -0,0 +1,24 @@ +package com.sanction.thunder.email; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class EmailExceptionTest { + + @Test + public void testEmailExceptionCreation() { + EmailException exception = new EmailException(); + assertNull(exception.getMessage()); + + exception = new EmailException("Test message"); + assertEquals("Test message", exception.getMessage()); + + exception = new EmailException("Test message", new Exception()); + assertEquals("Test message", exception.getMessage()); + + exception = new EmailException(new Exception()); + assertEquals(Exception.class, exception.getCause().getClass()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java new file mode 100644 index 0000000000..37d6b9c90c --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailModuleTest.java @@ -0,0 +1,94 @@ +package com.sanction.thunder.email; + +import com.google.common.base.Charsets; +import com.google.common.io.Resources; + +import java.io.File; +import java.io.IOException; + +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EmailModuleTest { + private static final EmailConfiguration EMAIL_CONFIG = mock(EmailConfiguration.class); + + @BeforeClass + public static void setup() { + when(EMAIL_CONFIG.getEndpoint()).thenReturn("http://localhost:4567"); + when(EMAIL_CONFIG.getRegion()).thenReturn("us-east-1"); + when(EMAIL_CONFIG.getFromAddress()).thenReturn("test@test.com"); + } + + @Test + public void testProvideSuccessHtmlDefault() throws IOException { + when(EMAIL_CONFIG.getSuccessHtmlPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("success.html"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideSuccessHtml()); + } + + @Test + public void testProvideSuccessHtmlCustom() throws Exception { + when(EMAIL_CONFIG.getSuccessHtmlPath()).thenReturn(new File( + Resources.getResource("fixtures/success-page.html").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/success-page.html"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideSuccessHtml()); + } + + @Test + public void testProvideVerificationHtmlDefault() throws IOException { + when(EMAIL_CONFIG.getVerificationHtmlPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("verification.html"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideVerificationHtml()); + } + + @Test + public void testProvideVerificationHtmlCustom() throws Exception { + when(EMAIL_CONFIG.getVerificationHtmlPath()).thenReturn(new File( + Resources.getResource("fixtures/verification-email.html").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/verification-email.html"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideVerificationHtml()); + } + + @Test + public void testProvideVerificationTextDefault() throws IOException { + when(EMAIL_CONFIG.getVerificationTextPath()).thenReturn(null); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("verification.txt"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideVerificationText()); + } + + @Test + public void testProvideVerificationTextCustom() throws Exception { + when(EMAIL_CONFIG.getVerificationTextPath()).thenReturn(new File( + Resources.getResource("fixtures/verification-email.txt").toURI()).getAbsolutePath()); + + EmailModule emailModule = new EmailModule(EMAIL_CONFIG); + + String expected = Resources.toString( + Resources.getResource("fixtures/verification-email.txt"), Charsets.UTF_8); + assertEquals(expected, emailModule.provideVerificationText()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java new file mode 100644 index 0000000000..b4cdcec37d --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/email/EmailServiceTest.java @@ -0,0 +1,47 @@ +package com.sanction.thunder.email; + +import com.amazonaws.AmazonClientException; +import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; +import com.amazonaws.services.simpleemail.model.SendEmailResult; + +import com.sanction.thunder.models.Email; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EmailServiceTest { + private static final String SUBJECT_STRING = "Account Verification"; + private static final String HTML_BODY_STRING = "HTML"; + private static final String BODY_STRING = "TEXT"; + + private final AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); + private final SendEmailResult result = mock(SendEmailResult.class); + + private final Email mockEmail = new Email("test@test.com", false, "verificationToken"); + + private final EmailService resource = new EmailService(emailService, "testAddress"); + + @Test + @SuppressWarnings("unchecked") + public void testSendEmailAmazonClientException() { + when(emailService.sendEmail(any())).thenThrow(AmazonClientException.class); + + boolean result = resource.sendEmail(mockEmail, SUBJECT_STRING, HTML_BODY_STRING, BODY_STRING); + + assertFalse(result); + } + + @Test + public void testSendEmailSuccess() { + when(emailService.sendEmail(any())).thenReturn(result); + + boolean result = resource.sendEmail(mockEmail, SUBJECT_STRING, HTML_BODY_STRING, BODY_STRING); + + assertTrue(result); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java new file mode 100644 index 0000000000..b5c2a075ef --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/UserResourceTest.java @@ -0,0 +1,381 @@ +package com.sanction.thunder.resources; + +import com.codahale.metrics.MetricRegistry; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.User; +import com.sanction.thunder.validation.PropertyValidator; + +import java.util.Collections; +import javax.ws.rs.core.Response; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UserResourceTest { + private final Email badEmail = new Email("badEmail", false, ""); + private final Email email = new Email("test@test.com", false, ""); + private final User user = new User(email, "password", Collections.emptyMap()); + private final User updatedUser = new User(email, "newPassword", Collections.emptyMap()); + + private final UsersDao usersDao = mock(UsersDao.class); + private final PropertyValidator validator = mock(PropertyValidator.class); + private final MetricRegistry metrics = new MetricRegistry(); + private final Key key = mock(Key.class); + + private final UserResource resource = new UserResource(usersDao, validator, metrics); + + @Before + public void setup() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(true); + } + + @Test + public void testPostNullUser() { + Response response = resource.postUser(key, null); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserNullEmail() { + User user = new User(null, "password", Collections.emptyMap()); + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserInvalidEmail() { + User user = new User(badEmail, "password", Collections.emptyMap()); + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserInvalidProperties() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(false); + + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testPostUserDatabaseDown() { + when(usersDao.insert(any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testPostUserUnsupportedData() { + when(usersDao.insert(any(User.class))).thenThrow( + new DatabaseException(DatabaseError.REQUEST_REJECTED)); + + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR, response.getStatusInfo()); + } + + @Test + public void testPostUserConflict() { + when(usersDao.insert(any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.CONFLICT)); + + Response response = resource.postUser(key, user); + + assertEquals(Response.Status.CONFLICT, response.getStatusInfo()); + } + + @Test + public void testPostUser() { + when(usersDao.insert(any(User.class))).thenReturn(updatedUser); + + Response response = resource.postUser(key, user); + User result = (User) response.getEntity(); + + assertEquals(Response.Status.CREATED, response.getStatusInfo()); + assertEquals(updatedUser, result); + } + + @Test + public void testUpdateNullUser() { + Response response = resource.updateUser(key, "password", null, null); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserNullEmail() { + User user = new User(null, "password", Collections.emptyMap()); + Response response = resource.updateUser(key, "password", email.getAddress(), user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserInvalidEmail() { + User user = new User(badEmail, "password", Collections.emptyMap()); + Response response = resource.updateUser(key, "password", email.getAddress(), user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserWithNullPassword() { + Response response = resource.updateUser(key, null, null, user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserInvalidProperties() { + when(validator.isValidPropertiesMap(anyMap())).thenReturn(false); + + Response response = resource.updateUser(key, "password", null, user); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.updateUser(key, "password", null, user); + + assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.updateUser(key, "password", null, user); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testUpdateUserLookupUnsupportedData() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.REQUEST_REJECTED)); + + Response response = resource.updateUser(key, "password", null, user); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR, response.getStatusInfo()); + } + + @Test + public void testUpdateUserMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.updateUser(key, "incorrectPassword", null, updatedUser); + + assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testUpdateUserNotFound() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testUpdateUserConflict() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.CONFLICT)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + assertEquals(Response.Status.CONFLICT, response.getStatusInfo()); + } + + @Test + public void testUpdateUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.updateUser(key, "password", null, updatedUser); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testUpdateUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.update(null, updatedUser)).thenReturn(updatedUser); + + Response response = resource.updateUser(key, "password", null, updatedUser); + User result = (User) response.getEntity(); + + assertEquals(Response.Status.OK, response.getStatusInfo()); + assertEquals(updatedUser, result); + } + + @Test + public void testUpdateUserWithNewEmail() { + when(usersDao.findByEmail("existingEmail")).thenReturn(user); + when(usersDao.update("existingEmail", updatedUser)).thenReturn(updatedUser); + + Response response = resource.updateUser(key, "password", "existingEmail", updatedUser); + User result = (User) response.getEntity(); + + assertEquals(Response.Status.OK, response.getStatusInfo()); + assertEquals(updatedUser, result); + } + + @Test + public void testGetUserWithNullEmail() { + Response response = resource.getUser(key, "password", null); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testGetUserWithNullPassword() { + Response response = resource.getUser(key, null, email.getAddress()); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testGetUserNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.getUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testGetUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.getUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testGetUserPasswordMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.getUser(key, "incorrectPassword", email.getAddress()); + + assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testGetUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.getUser(key, "password", email.getAddress()); + User result = (User) response.getEntity(); + + assertEquals(Response.Status.OK, response.getStatusInfo()); + assertEquals(user, result); + } + + @Test + public void testDeleteUserWithNullEmail() { + Response response = resource.deleteUser(key, "password", null); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testDeleteUserWithNullPassword() { + Response response = resource.deleteUser(key, null, email.getAddress()); + + assertEquals(Response.Status.BAD_REQUEST, response.getStatusInfo()); + } + + @Test + public void testDeleteUserLookupNotFound() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testDeleteUserLookupDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testDeleteUserPasswordMismatch() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + + Response response = resource.deleteUser(key, "incorrectPassword", email.getAddress()); + + assertEquals(Response.Status.UNAUTHORIZED, response.getStatusInfo()); + } + + @Test + public void testDeleteUserNotFound() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.USER_NOT_FOUND)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.NOT_FOUND, response.getStatusInfo()); + } + + @Test + public void testDeleteUserDatabaseDown() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + + assertEquals(Response.Status.SERVICE_UNAVAILABLE, response.getStatusInfo()); + } + + @Test + public void testDeleteUser() { + when(usersDao.findByEmail(email.getAddress())).thenReturn(user); + when(usersDao.delete(email.getAddress())).thenReturn(user); + + Response response = resource.deleteUser(key, "password", email.getAddress()); + User result = (User) response.getEntity(); + + assertEquals(Response.Status.OK, response.getStatusInfo()); + assertEquals(user, result); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java new file mode 100644 index 0000000000..3a6f2bd138 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/resources/VerificationResourceTest.java @@ -0,0 +1,258 @@ +package com.sanction.thunder.resources; + +import com.codahale.metrics.MetricRegistry; + +import com.sanction.thunder.authentication.Key; +import com.sanction.thunder.dao.DatabaseError; +import com.sanction.thunder.dao.DatabaseException; +import com.sanction.thunder.dao.UsersDao; +import com.sanction.thunder.email.EmailService; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.ResponseType; +import com.sanction.thunder.models.User; + +import java.net.URI; +import java.util.Collections; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class VerificationResourceTest { + private static final String URL = "http://www.test.com/"; + private static final String SUCCESS_HTML = "success!"; + private static final String VERIFICATION_HTML = "Verify"; + private static final String VERIFICATION_TEXT = "Verify"; + + private final EmailService emailService = mock(EmailService.class); + private final MetricRegistry metrics = new MetricRegistry(); + private final UsersDao usersDao = mock(UsersDao.class); + private final Key key = mock(Key.class); + + private static final UriInfo uriInfo = mock(UriInfo.class); + private static final UriBuilder uriBuilder = mock(UriBuilder.class); + + private final User unverifiedMockUser = + new User(new Email("test@test.com", false, "verificationToken"), + "password", Collections.emptyMap()); + private final User verifiedMockUser = + new User(new Email("test@test.com", true, "verificationToken"), + "password", Collections.emptyMap()); + private final User nullDatabaseTokenMockUser = + new User(new Email("test@test.com", false, null), + "password", Collections.emptyMap()); + private final User mismatchedTokenMockUser = + new User(new Email("test@test.com", false, "mismatchedToken"), + "password", Collections.emptyMap()); + + private final VerificationResource resource = + new VerificationResource(usersDao, metrics, emailService, SUCCESS_HTML, VERIFICATION_HTML, + VERIFICATION_TEXT); + + @BeforeClass + public static void setup() throws Exception { + when(uriBuilder.path(anyString())).thenReturn(uriBuilder); + when(uriBuilder.queryParam(anyString(), any())).thenReturn(uriBuilder); + when(uriBuilder.build()).thenReturn(new URI(URL)); + + when(uriInfo.getBaseUriBuilder()).thenReturn(uriBuilder); + } + + /* Verify User Tests */ + @Test + public void testCreateVerificationEmailWithNullEmail() { + Response response = resource.createVerificationEmail(uriInfo, key, null, "password"); + + assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testCreateVerificationEmailWithNullPassword() { + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", null); + + assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testCreateVerificationEmailFindUserException() { + when(usersDao.findByEmail(anyString())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testCreateVerificationEmailUpdateUserException() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testCreateVerificationEmailSendEmailFailure() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(false); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + + assertEquals(response.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR); + } + + @Test + public void testCreateVerificationEmailSuccess() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(true); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + User result = (User) response.getEntity(); + + assertEquals(response.getStatusInfo(), Response.Status.OK); + assertEquals(unverifiedMockUser, result); + + // Verify that the correct HTML and Text were used to send the email + verify(emailService).sendEmail( + any(Email.class), eq("Account Verification"), eq(VERIFICATION_HTML), eq(VERIFICATION_TEXT)); + } + + @Test + public void testCreateVerificationEmailCorrectUrl() { + when(usersDao.findByEmail(anyString())).thenReturn(unverifiedMockUser); + when(usersDao.update(anyString(), any(User.class))).thenReturn(unverifiedMockUser); + when(emailService.sendEmail(any(Email.class), anyString(), anyString(), anyString())) + .thenReturn(true); + + String verificationHtml = "Verify CODEGEN-URL"; + String verificationText = "Verify CODEGEN-URL"; + VerificationResource resource = new VerificationResource( + usersDao, metrics, emailService, SUCCESS_HTML, verificationHtml, verificationText); + + Response response = resource.createVerificationEmail(uriInfo, key, "test@test.com", "password"); + User result = (User) response.getEntity(); + + assertEquals(response.getStatusInfo(), Response.Status.OK); + assertEquals(unverifiedMockUser, result); + + // Verify that the correct HTML and Text were used to send the email + String expectedVerificationHtml = "Verify " + URL + ""; + String expectedVerificationText = "Verify " + URL; + verify(emailService).sendEmail( + any(Email.class), eq("Account Verification"), + eq(expectedVerificationHtml), eq(expectedVerificationText)); + } + + /* Verify Email Tests */ + @Test + public void testVerifyEmailWithNullEmail() { + Response response = resource.verifyEmail(null, "verificationToken", ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailWithNullToken() { + Response response = resource.verifyEmail("test@test.com", null, ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailFindUserException() { + when(usersDao.findByEmail(anyString())) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testVerifyEmailWithNullDatabaseToken() { + when(usersDao.findByEmail(anyString())).thenReturn(nullDatabaseTokenMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR); + } + + @Test + public void testVerifyEmailWithMismatchedToken() { + when(usersDao.findByEmail(anyString())).thenReturn(mismatchedTokenMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.BAD_REQUEST); + } + + @Test + public void testVerifyEmailUpdateUserException() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenThrow(new DatabaseException(DatabaseError.DATABASE_DOWN)); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + + assertEquals(response.getStatusInfo(), Response.Status.SERVICE_UNAVAILABLE); + } + + @Test + public void testVerifyEmailSuccess() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenReturn(verifiedMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.JSON); + User result = (User) response.getEntity(); + + assertEquals(response.getStatusInfo(), Response.Status.OK); + assertEquals(verifiedMockUser, result); + } + + @Test + public void testVerifyEmailWithHtmlResponse() { + when(usersDao.findByEmail("test@test.com")).thenReturn(unverifiedMockUser); + when(usersDao.update(unverifiedMockUser.getEmail().getAddress(), verifiedMockUser)) + .thenReturn(verifiedMockUser); + + Response response = resource.verifyEmail("test@test.com", "verificationToken", + ResponseType.HTML); + URI result = response.getLocation(); + + assertEquals(response.getStatusInfo(), Response.Status.SEE_OTHER); + assertEquals(UriBuilder.fromUri("/verify/success").build(), result); + } + + /* HTML Success Tests */ + @Test + public void testGetSuccessHtml() { + Response response = resource.getSuccessHtml(); + String result = (String) response.getEntity(); + + assertEquals(Response.Status.OK, response.getStatusInfo()); + assertEquals(SUCCESS_HTML, result); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java new file mode 100644 index 0000000000..006c28d9ef --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/util/EmailUtilitiesTest.java @@ -0,0 +1,27 @@ +package com.sanction.thunder.util; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class EmailUtilitiesTest { + private static final String URL_PLACEHOLDER = "CODEGEN-URL"; + + @Test + public void testReplacePlaceholderNoUrl() { + String contents = "test contents"; + String url = "http://www.test.com"; + + assertEquals(contents, EmailUtilities.replaceUrlPlaceholder(contents, url)); + } + + @Test + public void testReplacePlaceholderWithUrl() { + String contents = "test contents " + URL_PLACEHOLDER; + String url = "http://www.test.com"; + + String expected = "test contents " + url; + + assertEquals(expected, EmailUtilities.replaceUrlPlaceholder(contents, url)); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java new file mode 100644 index 0000000000..df7fa56b35 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidationRuleTest.java @@ -0,0 +1,56 @@ +package com.sanction.thunder.validation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class PropertyValidationRuleTest { + + @Test + public void testHashCodeSame() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "string"); + PropertyValidationRule ruleTwo = new PropertyValidationRule("name", "string"); + + assertEquals(ruleOne.hashCode(), ruleTwo.hashCode()); + assertEquals(ruleOne.getName(), ruleTwo.getName()); + assertEquals(ruleOne.getType(), ruleTwo.getType()); + } + + @Test + public void testHashCodeDifferent() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "string"); + PropertyValidationRule ruleTwo = new PropertyValidationRule("differentName", "integer"); + + assertNotEquals(ruleOne.hashCode(), ruleTwo.hashCode()); + assertNotEquals(ruleOne.getName(), ruleTwo.getName()); + assertNotEquals(ruleOne.getType(), ruleTwo.getType()); + } + + @Test + @SuppressWarnings({"SimplifiableJUnitAssertion", "EqualsWithItself"}) + public void testEqualsSameObject() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "list"); + + assertTrue(ruleOne.equals(ruleOne)); + } + + @Test + @SuppressWarnings("SimplifiableJUnitAssertion") + public void testEqualsDifferentObject() { + PropertyValidationRule ruleOne = new PropertyValidationRule("name", "map"); + Object objectTwo = new Object(); + + assertFalse(ruleOne.equals(objectTwo)); + } + + @Test + public void testToString() { + PropertyValidationRule rule = new PropertyValidationRule("testName", "string"); + String expected = "PropertyValidationRule [name=testName, type=class java.lang.String]"; + + assertEquals(expected, rule.toString()); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java new file mode 100644 index 0000000000..6e84529e81 --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/application/src/test/java/com/sanction/thunder/validation/PropertyValidatorTest.java @@ -0,0 +1,227 @@ +package com.sanction.thunder.validation; + +import com.google.common.collect.ImmutableMap; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class PropertyValidatorTest { + private final Map properties = new HashMap<>(); + private List validationRules + = Collections.singletonList( + new PropertyValidationRule("firstProperty", "string")); + + @Test + public void testSkipValidation() { + PropertyValidator validator = new PropertyValidator(null); + Map properties = Collections.emptyMap(); + + assertTrue(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testInvalidSize() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.emptyMap(); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testMismatchName() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("myProperty", "value"); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* String type */ + @Test + public void testMismatchTypeString() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("firstProperty", 1); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulStringValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = Collections.singletonMap("firstProperty", "value"); + + assertTrue(validator.isValidPropertiesMap(properties)); + } + + /* Integer type */ + @Test + public void testMismatchTypeInteger() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", "1"); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulIntegerValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Boolean type */ + @Test + public void testMismatchTypeBoolean() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", "false"); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulBooleanValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Boolean type */ + @Test + public void testMismatchTypeDouble() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulDoubleValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* List type */ + @Test + public void testMismatchTypeList() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double"), + new PropertyValidationRule("fifthProperty", "list")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyMap()); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulListValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyList()); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + /* Map type */ + @Test + public void testMismatchTypeMap() { + validationRules = Arrays.asList( + new PropertyValidationRule("firstProperty", "string"), + new PropertyValidationRule("secondProperty", "integer"), + new PropertyValidationRule("thirdProperty", "boolean"), + new PropertyValidationRule("fourthProperty", "double"), + new PropertyValidationRule("fifthProperty", "list"), + new PropertyValidationRule("sixthProperty", "map")); + + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyList()); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testSuccessfulMapValidation() { + PropertyValidator validator = new PropertyValidator(validationRules); + Map properties = ImmutableMap.of( + "firstProperty", "value", + "secondProperty", 1, + "thirdProperty", false, + "fourthProperty", 1.0, + "fifthProperty", Collections.emptyMap()); + + assertFalse(validator.isValidPropertiesMap(properties)); + } + + @Test + public void testGetType() { + assertEquals(String.class, PropertyValidator.getType("string")); + assertEquals(Integer.class, PropertyValidator.getType("integer")); + assertEquals(Boolean.class, PropertyValidator.getType("boolean")); + assertEquals(Double.class, PropertyValidator.getType("double")); + assertEquals(List.class, PropertyValidator.getType("list")); + assertEquals(Map.class, PropertyValidator.getType("map")); + assertEquals(Object.class, PropertyValidator.getType("unknown")); + } +} diff --git a/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/client/src/test/java/com/sanction/thunder/ThunderClientTest.java b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/client/src/test/java/com/sanction/thunder/ThunderClientTest.java new file mode 100644 index 0000000000..1e1d851d7d --- /dev/null +++ b/src/test/resources/oracle/commits/thunder-875864fb1bcfe1f05e4d8c5e217ea21874cb340b/client/src/test/java/com/sanction/thunder/ThunderClientTest.java @@ -0,0 +1,238 @@ +package com.sanction.thunder; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sanction.thunder.models.Email; +import com.sanction.thunder.models.ResponseType; +import com.sanction.thunder.models.User; + +import io.dropwizard.jackson.Jackson; +import io.dropwizard.testing.junit.DropwizardClientRule; + +import java.io.IOException; +import java.util.Collections; + +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import okhttp3.ResponseBody; + +import org.junit.ClassRule; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ThunderClientTest { + private static final ObjectMapper MAPPER = Jackson.newObjectMapper(); + private static final Email email = new Email("test@test.com", true, "hashToken"); + private static final String password = "password"; + private static final User user = new User(email, password, Collections.emptyMap()); + + /** + * Resource to be used as a test double. Requests from the ThunderClient interface + * will be directed here for the unit tests. Use this to verify that all parameters are + * being set correctly. + */ + @Path("/") + @Produces(MediaType.APPLICATION_JSON) + public static final class TestResource { + + /** + * Sample postUser method. The user object must be present. + */ + @POST + @Path("users") + public Response postUser(User user) { + if (user == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.CREATED) + .entity(user).build(); + } + + /** + * Sample updateUser method. The password and user object must be present. + */ + @PUT + @Path("users") + public Response updateUser(@QueryParam("email") String existingEmail, + @HeaderParam("password") String password, + User user) { + if (password == null || password.isEmpty() || user == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample getUser method. The email and password must be present. + */ + @GET + @Path("users") + public Response getUser(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample deleteUser method. The email and password must be present. + */ + @DELETE + @Path("users") + public Response deleteUser(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample sendEmail method. The email and password must be present. + */ + @POST + @Path("verify") + public Response sendEmail(@QueryParam("email") String email, + @HeaderParam("password") String password) { + if (email == null || email.isEmpty() || password == null || password.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + + /** + * Sample verifyUser method. The email and token must be present. + */ + @GET + @Path("verify") + public Response verifyUser(@QueryParam("email") String email, + @QueryParam("token") String token, + @QueryParam("response_type") @DefaultValue("json") + ResponseType responseType) { + if (email == null || email.isEmpty() || token == null || token.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(null).build(); + } + + if (responseType.equals(ResponseType.HTML)) { + return Response.ok("HTML Here").build(); + } + + return Response.status(Response.Status.OK) + .entity(user).build(); + } + } + + @ClassRule + public static final DropwizardClientRule dropwizard + = new DropwizardClientRule(new TestResource()); + + private final ThunderBuilder builder = + new ThunderBuilder(dropwizard.baseUri().toString() + "/", "userKey", "userSecret"); + private final ThunderClient client = builder.newThunderClient(); + + @Test + @SuppressWarnings("ConstantConditions") + public void testPostUser() throws IOException { + User response = client.postUser(user) + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testUpdateUser() throws IOException { + User response = client.updateUser(user, "email", password) + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testGetUser() throws IOException { + User response = client.getUser("email", password) + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testDeleteUser() throws IOException { + User response = client.deleteUser("email", password) + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testSendVerificationEmail() throws IOException { + User response = client.sendVerificationEmail("email", password) + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUser() throws IOException { + User response = client.verifyUser("email", "token") + .execute() + .body(); + + assertEquals(user.getEmail(), response.getEmail()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUserHtml() throws IOException { + ResponseBody response = client.verifyUser("email", "token", ResponseType.HTML) + .execute() + .body(); + + assertEquals("HTML Here", response.string()); + } + + @Test + @SuppressWarnings("ConstantConditions") + public void testVerifyUserJson() throws IOException { + ResponseBody response = client.verifyUser("email", "token", ResponseType.JSON) + .execute() + .body(); + + assertEquals(user, MAPPER.readValue(response.string(), User.class)); + } +}