src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
FormetaDecoder extends
DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String record) { parser.parse(record); } FormetaDecoder(); @Override void process(final String record); } | @Test public void testShouldProcessRecords() { decoder.process(RECORD); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("lit1", "value 1"); ordered.verify(receiver).startEntity(" ent1"); ordered.verify(receiver).literal("lit2", "value {x}"); ordered.verify(receiver).literal("lit\\3", "value 2 "); ordered.verify(receiver).endEntity(); ordered.verify(receiver).literal("lit4", "value '3'"); ordered.verify(receiver).endRecord(); } |
FormetaParser { public void parse(final String data) { assert structureParserContext.getEmitter() != null: "No emitter set"; buffer = StringUtil.copyToBuffer(data, buffer); final int bufferLen = data.length(); structureParserContext.reset(); StructureParserState state = StructureParserState.ITEM_NAME; int i = 0; try { for (; i < bufferLen; ++i) { state = state.processChar(buffer[i], structureParserContext); } } catch (final FormatException e) { final String errorMsg = "Parsing error at position " + (i + 1) + ": " + getErrorSnippet(data, i) + ", " + e.getMessage(); throw new FormatException(errorMsg, e); } try { state.endOfInput(structureParserContext); } catch (final FormatException e) { throw new FormatException("Parsing error: " + e.getMessage(), e); } } void setEmitter(final Emitter emitter); Emitter getEmitter(); void parse(final String data); static final int SNIPPET_SIZE; static final String SNIPPET_ELLIPSIS; static final String POS_MARKER_LEFT; static final String POS_MARKER_RIGHT; } | @Test public void testShouldParseConciselyFormattedRecords() { parser.parse(CONCISE_RECORD); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); }
@Test public void testShouldParseVerboselyFormattedRecords() { parser.parse(VERBOSE_RECORD); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); }
@Test public void testShouldParseMultilineFormattedRecords() { parser.parse(MULTILINE_RECORD); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); }
@Test public void testShouldIgnoreItemSeparatorAfterRecord() { parser.parse(CONCISE_RECORD + ", "); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); }
@Test(expected=FormatException.class) public void testShouldFailOnDoubleCloseRecord() { parser.parse("1 { lit: val }}"); }
@Test(expected=FormatException.class) public void testShouldFailOnGarbageAfterRecord() { parser.parse(CONCISE_RECORD + "Garbage"); }
@Test public void testShouldParseInputsContainingMoreThanOneRecord() { parser.parse(CONCISE_RECORD + CONCISE_RECORD); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); verifyRecord(ordered); }
@Test(expected=FormatException.class) public void testShouldFailOnIncompleteRecords() { parser.parse(BROKEN_RECORD); }
@Test public void testShouldRecoverAfterIncompleteRecord() { try { parser.parse(BROKEN_RECORD); } catch (FormatException e) { } parser.parse(CONCISE_RECORD); final InOrder ordered = inOrder(emitter); verifyRecord(ordered); }
@Test public void testShouldParseInputContainingNestedRecords() { parser.parse(OUTER_RECORD); final InOrder ordered = inOrder(emitter); ordered.verify(emitter).startGroup("outer", 0); ordered.verify(emitter).literal("nested", INNER_RECORD, 1); ordered.verify(emitter).literal("note", "I can has nezted records", 1); ordered.verify(emitter).endGroup(0); }
@Test public void testPartialRecord() { parser.parse(PARTIAL_RECORD); final InOrder ordered = inOrder(emitter); verifyRecordContents(ordered, 0); }
@Test(expected=FormatException.class) public void testIncompletePartialRecord() { parser.parse(BROKEN_PARTIAL_RECORD); } |
PicaDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String record) { assert !isClosed(); buffer = StringUtil.copyToBuffer(record, buffer); recordLen = record.length(); if (isRecordEmpty()) { return; } String id = extractRecordId(); if (id == null) { if (!ignoreMissingIdn) { throw new MissingIdException("Record has no id"); } id = ""; } getReceiver().startRecord(id); PicaParserState state = PicaParserState.FIELD_NAME; for (int i = 0; i < recordLen; ++i) { state = state.parseChar(buffer[i], parserContext, isNormalized); } state.endOfInput(parserContext); getReceiver().endRecord(); } PicaDecoder(); PicaDecoder(boolean normalized); void setNormalizedSerialization(boolean normalized); void setIgnoreMissingIdn(final boolean ignoreMissingIdn); boolean getIgnoreMissingIdn(); void setNormalizeUTF8(final boolean normalizeUTF8); boolean getNormalizeUTF8(); void setSkipEmptyFields(final boolean skipEmptyFields); boolean getSkipEmptyFields(); void setTrimFieldNames(final boolean trimFieldNames); boolean getTrimFieldNames(); @Override void process(final String record); } | @Test public void shouldParseRecordStartingWithRecordMarker() { picaDecoder.process( RECORD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordStartingWithFieldMarker() { picaDecoder.process( FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordStartingWithSubfieldMarker() { picaDecoder.process( SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); ordered.verify(receiver).startEntity(""); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordStartingWithEmptySubfield() { picaDecoder.process( SUBFIELD_MARKER + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordStartingWithFieldEndMarker() { picaDecoder.process( FIELD_END_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordStartingWithFieldName() { picaDecoder.process( FIELD_001AT_0_TEST + FIELD_MARKER + FIELD_003AT_0_ID); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordEndingWithRecordMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_001AT_0_TEST + RECORD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify001At0Test(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordEndingWithFieldMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify001At0Test(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordEndingWithSubfieldMarker() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + NAME_A + VALUE_A + SUBFIELD_MARKER + NAME_D + VALUE_D + SUBFIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).literal(NAME_D, VALUE_D); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseRecordEndingWithSubfieldName() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + NAME_A + VALUE_A + SUBFIELD_MARKER + NAME_D); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).literal(NAME_D, ""); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void shouldParseMultiLineRecordFormat() { picaDecoder.process( RECORD_MARKER + FIELD_END_MARKER + FIELD_MARKER + FIELD_001AT_0_TEST + FIELD_END_MARKER + FIELD_MARKER + FIELD_003AT_0_ID + FIELD_END_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify001At0Test(ordered); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); }
@Test public void shouldExtractPicaProductionNumberAfterRecordMarkerAsRecordId() { picaDecoder.process(RECORD_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberAfterFieldMarkerAsRecordId() { picaDecoder.process(FIELD_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberAfterFieldEndMarkerAsRecordId() { picaDecoder.process(FIELD_END_MARKER + FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberFollowedByRecordMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + RECORD_MARKER); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberFollowedByFieldMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + FIELD_MARKER); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberFollowedBySubfieldMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + SUBFIELD_MARKER); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberFollowedByFieldEndMarkerAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID + FIELD_END_MARKER); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractPicaProductionNumberAtRecordEndAsRecordId() { picaDecoder.process(FIELD_003AT_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractLocalProductionNumberAsRecordId() { picaDecoder.process(FIELD_107F_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractCopyControlNumberAsRecordId() { picaDecoder.process(FIELD_203AT_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractCopyControlNumberWithOccurrenceAsRecordId() { picaDecoder.process(FIELD_203AT_01_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test public void shouldExtractCopyControlNumberWithThreeDigitOccurrenceAsRecordId() { picaDecoder.process(FIELD_203AT_100_0_ID); verify(receiver).startRecord(RECORD_ID); }
@Test(expected=MissingIdException.class) public void shouldThrowMissingIdExceptionIfNoRecordIdIsFound() { picaDecoder.process(FIELD_001AT_0_TEST); }
@Test public void shouldNotSkipUnnamedFieldsWithSubFields() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(""); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void shouldSkipUnnamedSubfields() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + SUBFIELD_MARKER + NAME_A + VALUE_A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).startEntity(ENTITY_028A); ordered.verify(receiver).literal(NAME_A, VALUE_A); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); }
@Test public void shouldSkipEmptyFieldsByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); }
@Test public void shouldSkipFieldsWithOnlyUnnamedSubfieldsByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_028A + SUBFIELD_MARKER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); ordered.verify(receiver).endRecord(); verifyNoMoreInteractions(receiver); }
@Test(expected=MissingIdException.class) public void shouldFailIfIdIsMissingByDefault() { picaDecoder.process( FIELD_001AT_0_TEST + FIELD_MARKER); }
@Test public void shouldNotNormalizeUTF8ByDefault() { picaDecoder.process( FIELD_003AT_0_ID + FIELD_MARKER + FIELD_021A_A_UEBER + FIELD_MARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(RECORD_ID); verify003At0ID(ordered); verify021AAUeber(ordered, COMPOSED_UTF8); ordered.verify(receiver).endRecord(); }
@Test public void shouldTrimWhitespaceInFieldNamesByDefault() { picaDecoder.process( " fieldname " + SUBFIELD_MARKER + "0subfield" + FIELD_MARKER + FIELD_003AT_0_ID); verify(receiver).startEntity("fieldname"); } |
TripleCollect extends DefaultObjectPipe<Triple, StreamReceiver> { @Override public void process(final Triple triple) { if (currentSubject == null) { currentSubject = triple.getSubject(); getReceiver().startRecord(currentSubject); } if (currentSubject.equals(triple.getSubject())) { decodeTriple(triple); } else { getReceiver().endRecord(); currentSubject = triple.getSubject(); getReceiver().startRecord(currentSubject); decodeTriple(triple); } } TripleCollect(); @Override void process(final Triple triple); void decodeTriple(final Triple triple); } | @Test public void testShouldBuildRecords() { collect.process(new Triple(REC_ID, NAME, VALUE1)); collect.process(new Triple(REC_ID, NAME, VALUE2)); collect.process(new Triple(REC_ALT_ID, NAME, VALUE1)); collect.closeStream(); final InOrder ordered = Mockito.inOrder(receiver); ordered.verify(receiver).startRecord(REC_ID); ordered.verify(receiver).literal(NAME, VALUE1); ordered.verify(receiver).literal(NAME, VALUE2); ordered.verify(receiver).endRecord(); ordered.verify(receiver).startRecord(REC_ALT_ID); ordered.verify(receiver).literal(NAME, VALUE1); ordered.verify(receiver).endRecord(); }
@Test public void testShouldDecodeEntities() { collect.process(new Triple(REC_ID, ENTITY_NAME, Formeta.GROUP_START +NAME + Formeta.NAME_VALUE_SEPARATOR + VALUE + Formeta.ITEM_SEPARATOR + ENTITY_NAME + Formeta.GROUP_START + NAME + Formeta.NAME_VALUE_SEPARATOR + VALUE + Formeta.GROUP_END + Formeta.GROUP_END, ObjectType.ENTITY)); collect.closeStream(); final InOrder ordered = Mockito.inOrder(receiver); ordered.verify(receiver).startRecord(REC_ID); ordered.verify(receiver).startEntity(ENTITY_NAME); ordered.verify(receiver).literal(NAME, VALUE); ordered.verify(receiver).startEntity(ENTITY_NAME); ordered.verify(receiver).literal(NAME, VALUE); ordered.verify(receiver, Mockito.times(2)).endEntity(); ordered.verify(receiver).endRecord(); } |
TripleObjectWriter extends DefaultObjectReceiver<Triple> { @Override public void process(final Triple triple) { final Path filePath = buildFilePath(triple); ensureParentPathExists(filePath); try(final Writer writer = Files.newBufferedWriter(filePath, encoding)) { writer.write(triple.getObject()); } catch (final IOException e) { throw new MetafactureException(e); } } TripleObjectWriter(final String baseDir); void setEncoding(final String encoding); void setEncoding(final Charset encoding); String getEncoding(); @Override void process(final Triple triple); } | @Test public void shouldWriteObjectOfTripleIntoFile() throws IOException { tripleObjectWriter.process(new Triple(SUBJECT1, PREDICATE, OBJECT1)); tripleObjectWriter.process(new Triple(SUBJECT2, PREDICATE, OBJECT2)); final Path file1 = baseDir.resolve(Paths.get(SUBJECT1, PREDICATE)); final Path file2 = baseDir.resolve(Paths.get(SUBJECT2, PREDICATE)); assertEquals(OBJECT1, readFileContents(file1)); assertEquals(OBJECT2, readFileContents(file2)); }
@Test public void shouldMapStructuredSubjectsToDirectories() throws IOException { tripleObjectWriter.process(new Triple(STRUCTURED_SUBJECT, PREDICATE, OBJECT1)); final Path file = baseDir.resolve(Paths.get(STRUCTURED_SUBJECT_A, STRUCTURED_SUBJECT_B, PREDICATE)); assertEquals(readFileContents(file), OBJECT1); } |
TripleObjectRetriever extends DefaultObjectPipe<Triple, ObjectReceiver<Triple>> { @Override public void process(final Triple triple) { assert !isClosed(); if (triple.getObjectType() != ObjectType.STRING) { return; } final String objectValue = retrieveObjectValue(triple.getObject()); getReceiver().process(new Triple(triple.getSubject(), triple.getPredicate(), objectValue)); } void setDefaultEncoding(final String defaultEncoding); void setDefaultEncoding(final Charset defaultEncoding); String getDefaultEncoding(); @Override void process(final Triple triple); } | @Test public void shouldReplaceObjectValueWithResourceContentRetrievedFromUrl() { tripleObjectRetriever.process(new Triple(SUBJECT, PREDICATE, objectUrl)); verify(receiver).process(new Triple(SUBJECT, PREDICATE, OBJECT_VALUE)); }
@Test public void shouldSkipTriplesWithObjectTypeEntity() { tripleObjectRetriever.process( new Triple(SUBJECT, PREDICATE, ENTITY, ObjectType.ENTITY)); verifyZeroInteractions(receiver); } |
ObjectExceptionCatcher extends
DefaultObjectPipe<T, ObjectReceiver<T>> { @Override public void process(final T obj) { try { getReceiver().process(obj); } catch(final Exception e) { LOG.error("{}'{}' while processing object: {}", logPrefix, e.getMessage(), obj); if (logStackTrace) { final StringWriter stackTraceWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stackTraceWriter)); LOG.error("{}Stack Trace:\n{}", logPrefix, stackTraceWriter.toString()); } } } ObjectExceptionCatcher(); ObjectExceptionCatcher(final String logPrefix); void setLogPrefix(final String logPrefix); String getLogPrefix(); void setLogStackTrace(final boolean logStackTrace); boolean isLogStackTrace(); @Override void process(final T obj); } | @Test public void shouldCatchException() { exceptionCatcher.process("data"); } |
CharMap implements Map<Character, V> { @Override public V get(final Object key) { if (key instanceof Character) { final Character beite = (Character) key; return get(beite.charValue()); } return null; } @SuppressWarnings("unchecked") CharMap(); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(final Object key); @Override boolean containsValue(final Object value); @Override V get(final Object key); V get(final char key); @Override V put(final Character key, final V value); void put(final char key, final V value); void put(final Entry<V>[] table, final char key, final V value); @Override V remove(final Object key); @Override void putAll(final Map<? extends Character, ? extends V> map); @Override void clear(); @Override Set<Character> keySet(); @Override Collection<V> values(); @Override Set<java.util.Map.Entry<Character, V>> entrySet(); } | @Test public void testEmptyMap() { final Map<Character, Integer> map = new CharMap<Integer>(); for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; ++i) { assertNull(map.get(Byte.valueOf(i))); } } |
XmlUtil { public static String escape(final String unescaped) { return escape(unescaped, true); } private XmlUtil(); static String nodeToString(final Node node); static String nodeToString(final Node node,
final boolean omitXMLDecl); static String nodeListToString(final NodeList nodes); static boolean isXmlMimeType(final String mimeType); static String escape(final String unescaped); static String escape(final String unescaped, final boolean escapeUnicode); } | @Test public void escape_shouldEscapeXmlSpecialChars() { final String unescaped = "< > ' & \""; final String result = XmlUtil.escape(unescaped); assertEquals("< > ' & "", result); }
@Test public void escape_shouldNotEscapeAsciiChars() { final String unescaped ="Kafka"; final String result = XmlUtil.escape(unescaped); assertEquals("Kafka", result); }
@Test public void escape_shouldEscapeAllNonAsciiChars() { final String unescaped = "K\u00f8benhavn"; final String result = XmlUtil.escape(unescaped); assertEquals("København", result); }
@Test public void escape_shouldEscapeSurrogatePairsAsSingleEntity() { final String unescaped = "Smile: \ud83d\ude09"; final String result = XmlUtil.escape(unescaped); assertEquals("Smile: 😉", result); } |
Require { public static <T> T notNull(final T object) { return notNull(object, "parameter must not be null"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); } | @Test(expected = IllegalArgumentException.class) public void notNullShouldThrowIllegalArgumentExceptionIfArgIsNull() { Require.notNull(null); }
@Test public void notNullShouldReturnArgIfArgIsNotNull() { final Object obj = new Object(); assertSame(obj, Require.notNull(obj)); } |
Require { public static int notNegative(final int value) { return notNegative(value, "parameter must not be negative"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); } | @Test(expected = IllegalArgumentException.class) public void notNegativeShouldThrowIllegalArgumentExceptionIfArgIsNegative() { Require.notNegative(-1); }
@Test public void notNegativeShouldReturnArgIfArgIsNotNegative() { assertEquals(0, Require.notNegative(0)); } |
HtmlDecoder extends DefaultObjectPipe<Reader, StreamReceiver> { @Override public void process(final Reader reader) { try { StreamReceiver receiver = getReceiver(); receiver.startRecord(UUID.randomUUID().toString()); Document document = Jsoup.parse(IOUtils.toString(reader)); process(document, receiver); receiver.endRecord(); } catch (IOException e) { e.printStackTrace(); } } @Override void process(final Reader reader); } | @Test public void htmlElementsAsEntities() { htmlDecoder.process(new StringReader("<h1>Header</h1><p>Paragraph</p>")); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startEntity("html"); ordered.verify(receiver).startEntity("head"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).startEntity("body"); ordered.verify(receiver).startEntity("h1"); ordered.verify(receiver).literal("value", "Header"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).startEntity("p"); ordered.verify(receiver).literal("value", "Paragraph"); ordered.verify(receiver, times(3)).endEntity(); }
@Test public void nestedEntities() { htmlDecoder.process(new StringReader("<ul><li>Item</li></ul>")); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startEntity("ul"); ordered.verify(receiver).startEntity("li"); ordered.verify(receiver).literal("value", "Item"); ordered.verify(receiver, times(4)).endEntity(); }
@Test public void htmlAttributesAsLiterals() { htmlDecoder.process(new StringReader("<p class=lead>Text")); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startEntity("p"); ordered.verify(receiver).literal("class", "lead"); ordered.verify(receiver).literal("value", "Text"); ordered.verify(receiver, times(3)).endEntity(); }
@Test public void htmlScriptElementData() { htmlDecoder.process(new StringReader("<script type=application/ld+json>{\"id\":\"theId\"}</script>")); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startEntity("script"); ordered.verify(receiver).literal("type", "application/ld+json"); ordered.verify(receiver).literal("value", "{\"id\":\"theId\"}"); ordered.verify(receiver, times(4)).endEntity(); } |
Require { public static void that(final boolean condition) { that(condition, "parameter is not valid"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); } | @Test(expected = IllegalArgumentException.class) public void thatShouldFailIfArgumentIsFalse() { Require.that(false); }
@Test public void thatShouldDoNothingIfArgumentIsTrue() { Require.that(true); } |
Require { public static int validArrayIndex(final int index, final int arrayLength) { return validArrayIndex(index, arrayLength, "array index out of range"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); } | @Test(expected = IndexOutOfBoundsException.class) public void validArrayIndexShouldThrowIndexOutOfBoundsExceptionIfIndexIsNegative() { Require.validArrayIndex(-1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArrayIndexShouldThrowIndexOutOfBoundsExceptionIfIndexIsGreaterThanArrayLength() { Require.validArrayIndex(2, 2); }
@Test public void validArrayIndexShouldDoNothingIfIndexIsWithinArrayBounds() { assertEquals(1, Require.validArrayIndex(1, 2)); } |
Require { public static void validArraySlice(final int sliceFrom, final int sliceLength, final int arrayLength) { validArraySlice(sliceFrom, sliceLength, arrayLength, "array slice out of range"); } private Require(); static T notNull(final T object); static T notNull(final T object, final String message); static int notNegative(final int value); static int notNegative(final int value, final String message); static void that(final boolean condition); static void that(final boolean condition, final String message); static int validArrayIndex(final int index, final int arrayLength); static int validArrayIndex(final int index, final int arrayLength,
final String message); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength); static void validArraySlice(final int sliceFrom,
final int sliceLength, final int arrayLength, final String message); } | @Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfIndexIsNegative() { Require.validArraySlice(-1, 1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfLengthIsNegative() { Require.validArraySlice(0, -1, 2); }
@Test(expected = IndexOutOfBoundsException.class) public void validArraySliceShouldThrowIndexOutOfBoundsExceptionIfIndexPlusLengthIsGreaterThanArrayLength() { Require.validArraySlice(1, 2, 2); }
@Test public void validArraySliceShouldDoNothingIfIndexAndLengthAreWithinArrayBounds() { Require.validArraySlice(0, 1, 2); } |
StringUtil { public static char[] copyToBuffer(final String str, final char[] currentBuffer) { assert str != null; assert currentBuffer != null; assert currentBuffer.length > 0; final int strLen = str.length(); char[] buffer = currentBuffer; int bufferLen = buffer.length; while(strLen > bufferLen) { bufferLen *= 2; } if (bufferLen > buffer.length) { buffer = new char[bufferLen]; } str.getChars(0, strLen, buffer, 0); return buffer; } private StringUtil(); static O fallback(final O value, final O fallbackValue); static String format(final String format, final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final Map<String, String> variables); static String format(final String format, final boolean ignoreMissingVars,
final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final boolean ignoreMissingVars, final Map<String, String> variables); static char[] copyToBuffer(final String str, final char[] currentBuffer); static String repeatChars(final char ch, final int count); } | @Test public void copyToBufferShouldResizeBufferIfNecessary() { final char[] buffer = new char[2]; final String str = STRING_WITH_10_CHARS; final char[] newBuffer = StringUtil.copyToBuffer(str, buffer); assertTrue(newBuffer.length >= str.length()); }
@Test public void copyToBufferShouldReturnBufferContainingTheStringData() { final int bufferLen = STRING_WITH_4_CHARS.length(); char[] buffer = new char[bufferLen]; final String str = STRING_WITH_4_CHARS; buffer = StringUtil.copyToBuffer(str, buffer); assertEquals(STRING_WITH_4_CHARS, String.valueOf(buffer, 0, bufferLen)); } |
StringUtil { public static String format(final String format, final Map<String, String> variables) { return format(format, DEFAULT_VARSTART, DEFAULT_VAREND, true, variables); } private StringUtil(); static O fallback(final O value, final O fallbackValue); static String format(final String format, final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final Map<String, String> variables); static String format(final String format, final boolean ignoreMissingVars,
final Map<String, String> variables); static String format(final String format, final String varStartIndicator, final String varEndIndicator,
final boolean ignoreMissingVars, final Map<String, String> variables); static char[] copyToBuffer(final String str, final char[] currentBuffer); static String repeatChars(final char ch, final int count); } | @Test public void testFormat() { assertEquals(ALOHA_HAWAII, StringUtil.format("${a} ${b}", vars)); assertEquals(ALOHAHAWAII, StringUtil.format("${a}${b}", vars)); assertEquals("Aloha${b", StringUtil.format("${a}${b", vars)); assertEquals("XAloha${b", StringUtil.format("X${a}${b", vars)); assertEquals("XX", StringUtil.format("X${ab}X", vars)); assertEquals(XHULAXHULAX, StringUtil.format("X${bb}X${bb}X", vars)); assertEquals("{a}Hawaii", StringUtil.format("{a}${b}", vars)); assertEquals("Hula$Hula", StringUtil.format("${bb}$${bb}", vars)); }
@Test public void testCustomVarIndicators() { final String varStart = "VAR_START"; final String varEnd = "VAR_END"; assertEquals(ALOHA_HAWAII, StringUtil.format("VAR_STARTaVAR_END VAR_STARTbVAR_END", varStart, varEnd, vars)); assertEquals(ALOHAHAWAII, StringUtil.format("VAR_STARTaVAR_ENDVAR_STARTbVAR_END", varStart, varEnd, vars)); assertEquals("AlohaVAR_STARTb", StringUtil.format("VAR_STARTaVAR_ENDVAR_STARTb", varStart, varEnd, vars)); assertEquals("XAlohaVAR_STARTb", StringUtil.format("XVAR_STARTaVAR_ENDVAR_STARTb", varStart, varEnd, vars)); assertEquals("XX", StringUtil.format("XVAR_STARTabVAR_ENDX", varStart, varEnd, vars)); assertEquals(XHULAXHULAX, StringUtil.format("XVAR_STARTbbVAR_ENDXVAR_STARTbbVAR_ENDX", varStart, varEnd, vars)); assertEquals("{aVAR_ENDHawaii", StringUtil.format("{aVAR_ENDVAR_STARTbVAR_END", varStart, varEnd, vars)); }
@Test(expected=IllegalArgumentException.class) public void testMissingVars() { StringUtil.format("${a}${x}", false, vars); } |
TimeUtil { public static String formatDuration(final long duration) { long major = duration; long minor = 0; int i = -1; while (i < UNIT_FACTORS.length - 1 && major >= UNIT_FACTORS[i + 1]) { long carry = 0; if (i > 0 && minor >= UNIT_FACTORS[i] / 2) { carry = 1; } i += 1; minor = major % UNIT_FACTORS[i] + carry; major /= UNIT_FACTORS[i]; } if (i == 0 || minor == 0) { if (i < 0) { i = BASE_UNIT_INDEX; } return String.format("%d%s", Long.valueOf(major), UNIT_SYMBOLS[i]); } return String.format("%d%s %d%s", Long.valueOf(major), UNIT_SYMBOLS[i], Long.valueOf(minor), UNIT_SYMBOLS[i - 1]); } private TimeUtil(); static String formatDuration(final long duration); static final String[] UNIT_SYMBOLS; static final long[] UNIT_FACTORS; static final int BASE_UNIT_INDEX; static final long HOURS; static final long MINUTES; static final long SECONDS; static final long MILLISECONDS; static final long MICROSECONDS; static final long NANOSECONDS; } | @Test public void testShouldFormatNanoseconds() { final long duration = 29 * TimeUtil.NANOSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("29ns", formattedDuration); }
@Test public void testShouldFormatMicroseconds() { final long duration = 28 * TimeUtil.MICROSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("28µs", formattedDuration); }
@Test public void testShouldFormatSeconds() { final long duration = 10 * TimeUtil.SECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("10s", formattedDuration); }
@Test public void testShouldFormatMinutes() { final long duration = 58 * TimeUtil.MINUTES; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("58min", formattedDuration); }
@Test public void testShouldFormatMicrosecondsPlusNanoseconds() { final long duration = 28 * TimeUtil.MICROSECONDS + 9 * TimeUtil.NANOSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("28µs 9ns", formattedDuration); }
@Test public void testShouldFormatSecondsPlusMilliseconds() { final long duration = 10 * TimeUtil.SECONDS + 8 * TimeUtil.MILLISECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("10s 8ms", formattedDuration); }
@Test public void testShouldRoundDownIfRemainderLessThanHalf() { final long duration = 23 * TimeUtil.MINUTES + 1 * TimeUtil.SECONDS + 499 * TimeUtil.MILLISECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("23min 1s", formattedDuration); }
@Test public void testShouldRoundDownIfNanosecondsLessThanHalf() { final long duration = 23 * TimeUtil.MILLISECONDS + 1 * TimeUtil.MICROSECONDS + 499 * TimeUtil.NANOSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("23ms 1µs", formattedDuration); }
@Test public void testShouldIgnoreSmallerQualifiersWhenRounding() { final long duration = 23 * TimeUtil.MINUTES + 1 * TimeUtil.SECONDS + 501 * TimeUtil.MICROSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("23min 1s", formattedDuration); }
@Test public void testShouldRoundUpIfRemainderGreaterThanHalf() { final long duration = 42 * TimeUtil.MINUTES + 1 * TimeUtil.SECONDS + 501 * TimeUtil.MILLISECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("42min 2s", formattedDuration); }
@Test public void testShouldRoundDownIfNanosecondsGreaterThanHalf() { final long duration = 42 * TimeUtil.MILLISECONDS + 1 * TimeUtil.MICROSECONDS + 501 * TimeUtil.NANOSECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("42ms 2µs", formattedDuration); }
@Test public void testShouldRoundUpIfRemainderIsMidway() { final long duration = 42 * TimeUtil.MINUTES + 1 * TimeUtil.SECONDS + 500 * TimeUtil.MILLISECONDS; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("42min 2s", formattedDuration); }
@Test public void testShouldNotFailIfDurationIsZero() { final long duration = 0L; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("0s", formattedDuration); }
@Test public void testShouldNotFailIfDurationNeedsLargestQuantifier() { final long duration = 1 * TimeUtil.HOURS + 1 * TimeUtil.MINUTES; final String formattedDuration = TimeUtil.formatDuration(duration); assertEquals("1h 1min", formattedDuration); } |
ResourceUtil { public static String readAll(InputStream inputStream, Charset encoding) throws IOException { try (Reader reader = new InputStreamReader(inputStream, encoding)) { return readAll(reader); } } private ResourceUtil(); static InputStream getStream(final String name); static InputStream getStream(final File file); static Reader getReader(final String name); static Reader getReader(final File file); static Reader getReader(final String name, final String encoding); static Reader getReader(final File file, final String encoding); static URL getUrl(final String name); static URL getUrl(final File file); static Properties loadProperties(final String location); static Properties loadProperties(final InputStream stream); static Properties loadProperties(final URL url); static String loadTextFile(final String location); static List<String> loadTextFile(final String location,
final List<String> list); static String readAll(InputStream inputStream, Charset encoding); static String readAll(Reader reader); } | @Test public void readAll_shouldReturnEmptyStringIfStreamIsEmpty() throws IOException { final String result = ResourceUtil.readAll(new StringReader("")); assertTrue(result.isEmpty()); }
@Test public void readAll_shouldReadStreamThatFitsIntoOneBuffer() throws IOException { final String input = repeat("a", BUFFER_SIZE - 1); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); }
@Test public void readAll_shouldReadStreamThatFitsExactlyIntoOneBuffer() throws IOException { final String input = repeat("b", BUFFER_SIZE); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); }
@Test public void readAll_shouldReadStreamThatSpansMultipleBuffers() throws IOException { final String input = repeat("c", BUFFER_SIZE * 2 + 1); final String result = ResourceUtil.readAll(new StringReader(input)); assertEquals(input, result); } |
NamedValue implements Comparable<NamedValue> { @Override public int compareTo(final NamedValue namedValue) { final int first = name.compareTo(namedValue.name); if (first == 0) { return value.compareTo(namedValue.value); } return first; } NamedValue(final String name, final String value); String getName(); String getValue(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(final NamedValue namedValue); @Override String toString(); } | @Test public void testNamedValueCompare(){ final NamedValue namedValue1 = new NamedValue(SMALL, SMALL); final NamedValue namedValue2 = new NamedValue(SMALL, BIG); final NamedValue namedValue3 = new NamedValue(BIG, BIG); final NamedValue namedValue4 = new NamedValue(SMALL, SMALL); Assert.assertTrue(namedValue1.compareTo(namedValue4)==0); Assert.assertTrue(namedValue1.compareTo(namedValue2)==-1); Assert.assertTrue(namedValue2.compareTo(namedValue1)==1); Assert.assertTrue(namedValue2.compareTo(namedValue3)==-1); Assert.assertTrue(namedValue3.compareTo(namedValue2)==1); Assert.assertTrue(namedValue1.compareTo(namedValue4)==0); } |
JsonDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String string) { assert !isClosed(); createParser(string); try { decode(); } catch (final IOException e) { throw new MetafactureException(e); } finally { closeParser(); } } JsonDecoder(); void setArrayMarker(final String arrayMarker); String getArrayMarker(); void setArrayName(final String arrayName); String getArrayName(); void setRecordId(final String recordId); String getRecordId(); void setRecordCount(final int recordCount); int getRecordCount(); void resetRecordCount(); @Override void process(final String string); static final String DEFAULT_ARRAY_MARKER; static final String DEFAULT_ARRAY_NAME; static final String DEFAULT_RECORD_ID; } | @Test public void testShouldProcessEmptyStrings() { jsonDecoder.process(""); verifyZeroInteractions(receiver); }
@Test public void testShouldProcessRecords() { jsonDecoder.process( "{" + "\"lit1\":\"value 1\"," + "\" ent1\":{" + "\"lit2\":\"value {x}\"," + "\"lit\\\\3\":\"value 2 \"" + "}," + "\"lit4\":\"value '3'\"," + "\"lit5\":null" + "}"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("lit1", "value 1"); ordered.verify(receiver).startEntity(" ent1"); ordered.verify(receiver).literal("lit2", "value {x}"); ordered.verify(receiver).literal("lit\\3", "value 2 "); ordered.verify(receiver).endEntity(); ordered.verify(receiver).literal("lit4", "value '3'"); ordered.verify(receiver).literal("lit5", null); ordered.verify(receiver).endRecord(); }
@Test public void testShouldProcessArrays() { jsonDecoder.process( "{" + "\"arr1\":[\"val1\",\"val2\"]," + "\"arr2\":[" + "{" + "\"lit1\":\"val1\"," + "\"lit2\":\"val2\"" + "},{" + "\"lit3\":\"val3\"" + "}" + "]," + "\"arr3\":[" + "[" + "{\"lit4\":\"val4\"}" + "],[" + "{\"lit5\":\"val5\"}" + "]" + "]" + "}"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).startEntity("arr1[]"); ordered.verify(receiver).literal("1", "val1"); ordered.verify(receiver).literal("2", "val2"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).startEntity("arr2[]"); ordered.verify(receiver).startEntity("1"); ordered.verify(receiver).literal("lit1", "val1"); ordered.verify(receiver).literal("lit2", "val2"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).startEntity("2"); ordered.verify(receiver).literal("lit3", "val3"); ordered.verify(receiver, times(2)).endEntity(); ordered.verify(receiver).startEntity("arr3[]"); ordered.verify(receiver).startEntity("1[]"); ordered.verify(receiver).startEntity("1"); ordered.verify(receiver).literal("lit4", "val4"); ordered.verify(receiver, times(2)).endEntity(); ordered.verify(receiver).startEntity("2[]"); ordered.verify(receiver).startEntity("1"); ordered.verify(receiver).literal("lit5", "val5"); ordered.verify(receiver, times(3)).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void testShouldProcessConcatenatedRecords() { jsonDecoder.process( "{\"lit\": \"record 1\"}\n" + "{\"lit\": \"record 2\"}"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("lit", "record 1"); ordered.verify(receiver).endRecord(); ordered.verify(receiver).startRecord("2"); ordered.verify(receiver).literal("lit", "record 2"); ordered.verify(receiver).endRecord(); }
@Test public void testShouldProcessMultipleRecords() { jsonDecoder.process("{\"lit\": \"record 1\"}"); jsonDecoder.process("{\"lit\": \"record 2\"}"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("lit", "record 1"); ordered.verify(receiver).endRecord(); ordered.verify(receiver).startRecord("2"); ordered.verify(receiver).literal("lit", "record 2"); ordered.verify(receiver).endRecord(); }
@Test public void testShouldOnlyParseObjects() { exception.expect(MetafactureException.class); exception.expectMessage("Unexpected token 'VALUE_NULL'"); jsonDecoder.process("null"); }
@Test public void testShouldNotParseIncompleteObjects() { exception.expect(MetafactureException.class); exception.expectMessage("Unexpected end-of-input"); jsonDecoder.process("{"); }
@Test public void testShouldNotParseTrailingContent() { exception.expect(MetafactureException.class); exception.expectMessage("Unexpected token 'VALUE_NULL'"); jsonDecoder.process("{\"lit\":\"value\"}null"); }
@Test public void testShouldNotParseTrailingGarbage() { exception.expect(MetafactureException.class); exception.expectMessage("Unrecognized token 'XXX'"); jsonDecoder.process("{\"lit\":\"value\"}XXX"); } |
DomLoader { public static Document parse(String schemaFile, InputSource input) { final Document document = createEmptyDocument(); final XMLReader pipeline = createXmlFilterPipeline(schemaFile, document); process(new SAXSource(pipeline, input), new DOMResult(document)); removeEmptyTextNodes(document); return document; } private DomLoader(); static Document parse(String schemaFile, InputSource input); } | @Test public void shouldCreateDOM() throws FileNotFoundException, MalformedURLException { final String inputFile = "should-create-dom.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final Node rootNode = document.getDocumentElement(); assertEquals(Node.ELEMENT_NODE, rootNode.getNodeType()); assertEquals("test-schema", rootNode.getNodeName()); }
@Test(expected=MetafactureException.class) public void shouldValidateInputAgainstSchema() throws FileNotFoundException, MalformedURLException { final String inputFile = "should-validate-input-against-schema.xml"; DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); }
@Test public void domShouldNotContainWhitespaceOnlyTextNodes() throws FileNotFoundException, MalformedURLException { final String inputFile = "dom-should-not-contain-whitespace-only-text-nodes.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final NodeList nodes1 = document.getDocumentElement().getChildNodes(); assertEquals(1, nodes1.getLength()); assertEquals(Node.ELEMENT_NODE, nodes1.item(0).getNodeType()); final NodeList nodes2 = nodes1.item(0).getChildNodes(); assertEquals(0, nodes2.getLength()); }
@Test public void domShouldNotContainComments() throws FileNotFoundException, MalformedURLException { final String inputFile = "dom-should-not-contain-comments.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final NodeList nodes = document.getDocumentElement().getChildNodes(); assertEquals(0, nodes.getLength()); }
@Test public void shouldConvertAndAttachCDataNodesToTextNodes() throws FileNotFoundException, MalformedURLException { final String inputFile = "should-convert-and-attach-cdata-nodes-to-text-nodes.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final NodeList nodes = document.getDocumentElement().getFirstChild().getChildNodes(); assertEquals(1, nodes.getLength()); assertEquals(Node.TEXT_NODE, nodes.item(0).getNodeType()); assertEquals("pcdata-cdata-pcdata", nodes.item(0).getNodeValue()); }
@Test public void shouldBeXIncludeAware() throws FileNotFoundException, MalformedURLException { final String inputFile = "should-be-xinclude-aware1.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final Node stringElement = document.getDocumentElement().getFirstChild(); assertEquals(Node.ELEMENT_NODE, stringElement.getNodeType()); assertEquals("string-element", stringElement.getNodeName()); }
@Test public void shouldAnnotateDomWithLocationInformation() throws FileNotFoundException, MalformedURLException { final String inputFile = "should-annotate-dom-with-location-information.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final Node rootNode = document.getDocumentElement(); final Location location1 = (Location) rootNode.getUserData(Location.USER_DATA_ID); assertTrue(location1.getSystemId().endsWith(inputFile)); assertEquals(3, location1.getElementStart().getLineNumber()); assertEquals(57, location1.getElementStart().getColumnNumber()); assertEquals(5, location1.getElementEnd().getLineNumber()); assertEquals(15, location1.getElementEnd().getColumnNumber()); final Node stringElement = document.getDocumentElement().getFirstChild(); final Location location2 = (Location) stringElement.getUserData(Location.USER_DATA_ID); assertTrue(location2.getSystemId().endsWith(inputFile)); assertEquals(4, location2.getElementStart().getLineNumber()); assertEquals(21, location2.getElementStart().getColumnNumber()); assertEquals(4, location2.getElementEnd().getLineNumber()); assertEquals(42, location2.getElementEnd().getColumnNumber()); }
@Ignore @Test public void shouldAnnotateIncludedFilesCorrectly() throws FileNotFoundException, MalformedURLException { final String baseName = "should-annotate-included-files-correctly"; final String inputFile = baseName + "1.xml"; final Document document = DomLoader.parse(SCHEMA_FILE, openStream(inputFile)); final Node rootNode = document.getDocumentElement(); final Location location1 = (Location) rootNode.getUserData(Location.USER_DATA_ID); assertTrue(location1.getSystemId().endsWith(inputFile)); assertEquals(4, location1.getElementStart().getLineNumber()); assertEquals(46, location1.getElementStart().getColumnNumber()); assertEquals(7, location1.getElementEnd().getLineNumber()); assertEquals(15, location1.getElementEnd().getColumnNumber()); final Node stringElement = document.getDocumentElement().getFirstChild(); final Location location2 = (Location) stringElement.getUserData(Location.USER_DATA_ID); assertTrue(location2.getSystemId().endsWith(baseName + "2.xml")); assertEquals(3, location2.getElementStart().getLineNumber()); assertEquals(62, location2.getElementStart().getColumnNumber()); assertEquals(3, location2.getElementEnd().getLineNumber()); assertEquals(62, location2.getElementEnd().getColumnNumber()); } |
Splitter implements StreamPipe<StreamReceiver> { @Override public void resetStream() { buffer.clear(); metamorph.resetStream(); for (final StreamReceiver receiver: receiverMap.values()) { receiver.resetStream(); } } Splitter(final String morphDef); Splitter(final Reader morphDef); Splitter(final Metamorph metamorph); @Override R setReceiver(final R receiver); R setReceiver(final String key, final R receiver); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); @Override void resetStream(); @Override void closeStream(); } | @Test public void shouldPassResetStreamToAllReceivers() { splitter.resetStream(); verify(receiver1).resetStream(); verify(receiver2).resetStream(); } |
Splitter implements StreamPipe<StreamReceiver> { @Override public void closeStream() { buffer.clear(); metamorph.closeStream(); for (final StreamReceiver receiver: receiverMap.values()) { receiver.closeStream(); } } Splitter(final String morphDef); Splitter(final Reader morphDef); Splitter(final Metamorph metamorph); @Override R setReceiver(final R receiver); R setReceiver(final String key, final R receiver); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); @Override void resetStream(); @Override void closeStream(); } | @Test public void shouldPassCloseStreamToAllReceivers() { splitter.closeStream(); verify(receiver1).closeStream(); verify(receiver2).closeStream(); } |
NormalizeUTF8 extends AbstractSimpleStatelessFunction { @Override public String process(final String value) { return Normalizer.normalize(value, Form.NFC); } @Override String process(final String value); } | @Test public void testProcess() { final NormalizeUTF8 normalize = new NormalizeUTF8(); assertEquals("Normalization incorrect", OUTPUT_STR, normalize.process(INPUT_STR)); } |
ISBN extends AbstractSimpleStatelessFunction { @Override public String process(final String value) { String result = cleanse(value); final int size = result.length(); if (verifyCheckDigit && !isValid(result)) { result = errorString; } else if (!(size == ISBN10_SIZE || size == ISBN13_SIZE)) { result = errorString; } else { if (to10 && ISBN13_SIZE == size) { result = isbn13to10(result); } else if (to13 && ISBN10_SIZE == size) { result = isbn10to13(result); } } return result; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); } | @Test public void testProcess(){ final ISBN isbn = new ISBN(); isbn.setTo("isbn13"); assertEquals(ISBN13A, isbn.process(ISBN10A)); isbn.setTo("isbn10"); assertEquals(ISBN10A, isbn.process(ISBN13A)); isbn.setTo("cleanse"); assertEquals(ISBN10A, isbn.process(ISBN10A_DIRTY)); } |
ISBN extends AbstractSimpleStatelessFunction { public static String isbn10to13(final String isbn) { if (isbn.length() != ISBN10_SIZE) { throw new IllegalArgumentException( "isbn must be 10 characters long"); } final String isbn13Data = "978" + isbn.substring(0, ISBN10_SIZE - 1); return isbn13Data + check13(isbn13Data); } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); } | @Test public void testTo13() { assertEquals(ISBN13A, ISBN.isbn10to13(ISBN10A)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidInputTo13() { ISBN.isbn10to13(ISBN_INCORRECT_SIZE3); } |
ISBN extends AbstractSimpleStatelessFunction { public static String isbn13to10(final String isbn) { if (isbn.length() != ISBN13_SIZE) { throw new IllegalArgumentException( "isbn must be 13 characters long"); } final String isbn10Data = isbn.substring(3, 12); return isbn10Data + check10(isbn10Data); } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); } | @Test public void testTo10() { assertEquals(ISBN10A,ISBN.isbn13to10(ISBN13A)); }
@Test(expected = IllegalArgumentException.class) public void testInvalidInputTo10() { ISBN.isbn13to10(ISBN_INCORRECT_SIZE2); } |
ISBN extends AbstractSimpleStatelessFunction { public static String cleanse(final String isbn) { String normValue = isbn.replace('x', 'X'); normValue = DIRT_PATTERN.matcher(normValue).replaceAll(""); final Matcher matcher = ISBN_PATTERN.matcher(normValue); if (matcher.find()) { return matcher.group(); } return ""; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); } | @Test public void testCleanse() { assertEquals(ISBN10A,ISBN.cleanse(ISBN10A_DIRTY)); } |
ISBN extends AbstractSimpleStatelessFunction { public static boolean isValid(final String isbn) { boolean result = false; if (isbn.length() == ISBN10_SIZE) { result = check10(isbn.substring(0, ISBN10_SIZE - 1)) == isbn .charAt(ISBN10_SIZE - 1); } else if (isbn.length() == ISBN13_SIZE) { result = check13(isbn.substring(0, ISBN13_SIZE - 1)) == isbn .charAt(ISBN13_SIZE - 1); } return result; } void setErrorString(final String errorString); @Override String process(final String value); static String cleanse(final String isbn); void setTo(final String toString); static String isbn13to10(final String isbn); static String isbn10to13(final String isbn); static boolean isValid(final String isbn); void setVerifyCheckDigit(final String verifyCheckDigit); } | @Test public void testIsValid() { assertFalse(ISBN.isValid(ISBN_INCORRECT_CHECK13)); assertFalse(ISBN.isValid(ISBN_INCORRECT_CHECK10)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE1)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE2)); assertFalse(ISBN.isValid(ISBN_INCORRECT_SIZE3)); assertTrue(ISBN.isValid(ISBN10B)); assertTrue(ISBN.isValid(ISBN10A)); assertTrue(ISBN.isValid(ISBN13A )); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN10C_DIRTY))); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN13D_DIRTY))); assertTrue(ISBN.isValid(ISBN.cleanse(ISBN10F_DIRTY))); } |
CGXmlHandler extends DefaultXmlPipe<StreamReceiver> { @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) { if (!CGXML_NAMESPACE.equals(uri)) { return; } switch (localName) { case ROOT_TAG: verifyValidVersion(attributes); break; case RECORDS_TAG: break; case RECORD_TAG: emitStartRecord(attributes); break; case ENTITY_TAG: emitStartEntity(attributes); break; case LITERAL_TAG: emitLiteral(attributes); break; default: throw new FormatException("Unexpected element: " + localName); } } @Override void startElement(final String uri, final String localName,
final String qName, final Attributes attributes); @Override void endElement(final String uri, final String localName,
final String qName); static final String CGXML_NAMESPACE; } | @Test(expected = FormatException.class) public void shouldThrowFormatExceptionIfVersionIsNot1() { attributes.addAttribute("", "version", "cgxml:version", "CDATA", "2.0"); cgXmlHandler.startElement(CGXML_NS, "cgxml", "cgxml:cgxml", attributes); }
@Test public void shouldEmitStartRecordWithEmptyIdIfIdAttributeIsMissing() { cgXmlHandler.startElement(CGXML_NS, "record", "cgxml:record", attributes); verify(receiver).startRecord(""); }
@Test(expected = FormatException.class) public void shouldThrowFormatExceptionEmptyNameAttributeIsMissing() { cgXmlHandler.startElement(CGXML_NS, "entity", "cgxml:entity", attributes); }
@Test(expected = FormatException.class) public void shouldThrowFormatExceptionIfLiteralNameAttributeIsMissing() { attributes.addAttribute("", "value", "cgxml:value", "CDATA", "l-val"); cgXmlHandler.startElement(CGXML_NS, "literal", "cgxml:literal", attributes); } |
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { protected static void writeEscaped(final StringBuilder builder, final String str) { builder.append(XmlUtil.escape(str, false)); } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; } | @Test public void shouldOnlyEscapeXmlReservedCharacters() { final StringBuilder builder = new StringBuilder(); SimpleXmlEncoder.writeEscaped(builder , "&<>'\" üäö"); assertEquals("&<>'" üäö", builder.toString()); } |
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setSeparateRoots(final boolean separateRoots) { this.separateRoots = separateRoots; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; } | @Test public void shouldWrapEachRecordInRootTagIfSeparateRootsIsTrue() { simpleXmlEncoder.setSeparateRoots(true); emitTwoRecords(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records><?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record></records>", getResultXml()); }
@Test public void shouldWrapAllRecordsInOneRootTagtIfSeparateRootsIsFalse() { simpleXmlEncoder.setSeparateRoots(false); emitTwoRecords(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records><record><tag>value</tag></record><record><tag>value</tag></record></records>", getResultXml()); } |
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setNamespaces(final Map<String, String> namespaces) { this.namespaces = namespaces; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; } | @Test public void shouldAddNamespaceToRootElement() { final Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("ns", "http: simpleXmlEncoder.setNamespaces(namespaces); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns:ns=\"http: getResultXml()); }
@Test public void shouldAddNamespaceWithEmptyKeyAsDefaultNamespaceToRootTag() { final Map<String, String> namespaces = new HashMap<String, String>(); namespaces.put("", "http: simpleXmlEncoder.setNamespaces(namespaces); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns=\"http: getResultXml()); } |
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setNamespaceFile(final String file) { final Properties properties; try { properties = ResourceUtil.loadProperties(file); } catch (IOException e) { throw new MetafactureException("Failed to load namespaces list", e); } for (final Entry<Object, Object> entry : properties.entrySet()) { namespaces.put(entry.getKey().toString(), entry.getValue().toString()); } } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; } | @Test public void shouldAddNamespaceWithEmptyKeyFromPropertiesFileAsDefaultNamespaceToRootTag() { simpleXmlEncoder.setNamespaceFile("org/metafacture/xml/SimpleXmlEncoderTest_namespaces.properties"); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><records xmlns=\"http: getResultXml()); } |
SimpleXmlEncoder extends DefaultStreamPipe<ObjectReceiver<String>> { public void setWriteRootTag(final boolean writeRootTag) { this.writeRootTag = writeRootTag; } void setRootTag(final String rootTag); void setRecordTag(final String tag); void setNamespaceFile(final String file); void setNamespaceFile(final URL url); void setWriteXmlHeader(final boolean writeXmlHeader); void setXmlHeaderEncoding(final String xmlHeaderEncoding); void setXmlHeaderVersion(final String xmlHeaderVersion); void setWriteRootTag(final boolean writeRootTag); void setSeparateRoots(final boolean separateRoots); void setNamespaces(final Map<String, String> namespaces); @Override void startRecord(final String identifier); @Override void endRecord(); @Override void startEntity(final String name); @Override void endEntity(); @Override void literal(final String name, final String value); static final String ATTRIBUTE_MARKER; static final String DEFAULT_ROOT_TAG; static final String DEFAULT_RECORD_TAG; } | @Test public void shouldNotEmitRootTagIfWriteRootTagIsFalse() { simpleXmlEncoder.setWriteRootTag(false); emitEmptyRecord(); assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><record />", getResultXml()); } |
GenericXmlHandler extends DefaultXmlPipe<StreamReceiver> { @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) { if (inRecord) { writeValue(); getReceiver().startEntity(localName); writeAttributes(attributes); } else if (localName.equals(recordTagName)) { final String identifier = attributes.getValue("id"); if (identifier == null) { getReceiver().startRecord(""); } else { getReceiver().startRecord(identifier); } writeAttributes(attributes); inRecord = true; } } GenericXmlHandler(); @Deprecated GenericXmlHandler(final String recordTagName); void setRecordTagName(String recordTagName); String getRecordTagName(); @Override void startElement(final String uri, final String localName,
final String qName, final Attributes attributes); @Override void endElement(final String uri, final String localName,
final String qName); @Override void characters(final char[] chars, final int start, final int length); static final String DEFAULT_RECORD_TAG; } | @Test public void shouldIgnoreElementsOutsideRecordElement() { genericXmlHandler.startElement("", "ignore-me", "ignore-me", attributes); verifyZeroInteractions(receiver); }
@Test public void shouldEmitEmptyStringIfRecordTagHasNoIdAttribute() { genericXmlHandler.startElement("", "record", "record", attributes); verify(receiver).startRecord(""); }
@Test public void shouldEmitValueOfIdAttribute() { attributes.addAttribute("", "id", "id", "CDATA", "theRecordID"); genericXmlHandler.startElement("", "record", "record", attributes); verify(receiver).startRecord("theRecordID"); }
@Test public void shouldEmitAttributesOnRecordElementAsLiterals() { attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value"); genericXmlHandler.startElement("", "record", "record", attributes); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("attr", "attr-value"); }
@Test public void shouldEmitAttributesOnEntityElementAsLiterals() { genericXmlHandler.startElement("", "record", "record", attributes); attributes.addAttribute("", "attr", "attr", "CDATA", "attr-value"); genericXmlHandler.startElement("", "entity", "entity", attributes); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startEntity("entity"); ordered.verify(receiver).literal("attr", "attr-value"); } |
LineRecorder implements ObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String line) { assert !isClosed(); if (line.matches(recordMarkerRegexp)) { getReceiver().process(record.toString()); record = new StringBuilder(SB_CAPACITY); } else record.append(line + "\n"); } void setRecordMarkerRegexp(final String regexp); @Override void process(final String line); @Override void resetStream(); @Override void closeStream(); @Override R setReceiver(R receiver); } | @Test public void shouldEmitRecords() { lineRecorder.process(RECORD1_PART1); lineRecorder.process(RECORD1_PART2); lineRecorder.process(RECORD1_ENDMARKER); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process( RECORD1_PART1 + LINE_SEPARATOR + RECORD1_PART2 + LINE_SEPARATOR); lineRecorder.process(RECORD2_PART1); lineRecorder.process(RECORD2_PART2); lineRecorder.process(RECORD2_ENDMARKER); ordered.verify(receiver).process( RECORD2_PART1 + LINE_SEPARATOR + RECORD2_PART2 + LINE_SEPARATOR); ordered.verifyNoMoreInteractions(); } |
RegexDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String input) { matcher.reset(input); if (!matcher.find()) { return; } getReceiver().startRecord(getRecordId()); emitRawInputLiteral(input); emitCaptureGroupsAsLiterals(); getReceiver().endRecord(); } RegexDecoder(final String regex); void setRawInputLiteral(final String rawInputLiteral); String getRawInputLiteral(); @Override void process(final String input); static final String ID_CAPTURE_GROUP; } | @Test public void shouldEmitStartAndEndRecordForMatchingInput() { final RegexDecoder regexDecoder = new RegexDecoder(".*"); regexDecoder.setReceiver(receiver); regexDecoder.process("matching input"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(any()); ordered.verify(receiver).endRecord(); }
@Test public void shouldIgnoreNonMatchingInput() { final RegexDecoder regexDecoder = new RegexDecoder("abc"); regexDecoder.setReceiver(receiver); regexDecoder.process("non-matching input"); verifyZeroInteractions(receiver); }
@Test public void shouldUseCaptureGroupNamedIdAsRecordId() { final RegexDecoder regexDecoder = new RegexDecoder("ID:(?<id>.*)"); regexDecoder.setReceiver(receiver); regexDecoder.process("ID:id-123"); verify(receiver).startRecord("id-123"); }
@Test public void shouldUseEmptyStringAsRecordIdIfNoRecordIdCaptureGroupExists() { final RegexDecoder regexDecoder = new RegexDecoder("ID:(?<identifier>.*)"); regexDecoder.setReceiver(receiver); regexDecoder.process("ID:id-123"); verify(receiver).startRecord(""); }
@Test public void shouldUseEmptyStringAsRecordIdIfRecordIdCaptureGroupDoesNotMatch() { final RegexDecoder regexDecoder = new RegexDecoder("ID:(?<id>[0-9]*).*"); regexDecoder.setReceiver(receiver); regexDecoder.process("ID:id-123"); verify(receiver).startRecord(""); }
@Test public void shouldUseGroupNameAsLiteralNameForNamedCaptureGroups() { final RegexDecoder regexDecoder = new RegexDecoder( "foo=(?<foo>[0-9]+),bar=(?<bar>[a-z]+)"); regexDecoder.setReceiver(receiver); regexDecoder.process("foo=1234,bar=abcd"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).literal("foo", "1234"); ordered.verify(receiver).literal("bar", "abcd"); }
@Test public void shouldOutputLiteralsForEachMatchOfPattern() { final RegexDecoder regexDecoder = new RegexDecoder( "foo=(?<foo>[0-9]+),bar=(?<bar>[a-z]+)"); regexDecoder.setReceiver(receiver); regexDecoder.process("foo=1234,bar=abcd,foo=5678,bar=efgh"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).literal("foo", "1234"); ordered.verify(receiver).literal("bar", "abcd"); ordered.verify(receiver).literal("foo", "5678"); ordered.verify(receiver).literal("bar", "efgh"); }
@Test public void shouldIgnoreNonMatchingPartsOfInputString() { final RegexDecoder regexDecoder = new RegexDecoder( "foo=(?<foo>[0-9]+)"); regexDecoder.setReceiver(receiver); regexDecoder.process("foo=1234,bar=abcd,foo=5678,bar=efgh"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).literal("foo", "1234"); ordered.verify(receiver, never()).literal("bar", "abcd"); ordered.verify(receiver).literal("foo", "5678"); ordered.verify(receiver, never()).literal("bar", "efgh"); }
@Test public void shouldIgnoreUnnamedCaptureGroups() { final RegexDecoder regexDecoder = new RegexDecoder( "foo=([0-9]+),bar=(?<bar>[a-z]+)"); regexDecoder.setReceiver(receiver); regexDecoder.process("foo=1234,bar=abcd,foo=5678,bar=efgh"); verify(receiver, never()).literal(any(), eq("1234")); verify(receiver, never()).literal(any(), eq("5678")); } |
LineSplitter extends DefaultObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String lines) { assert !isClosed(); for (final String record : LINE_PATTERN.split(lines)) { getReceiver().process(record); } } @Override void process(final String lines); } | @Test public void shouldSplitInputStringAtNewLines() { lineSplitter.process(PART1 + "\n" + PART2 + "\n" + PART3); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(PART1); ordered.verify(receiver).process(PART2); ordered.verify(receiver).process(PART3); ordered.verifyNoMoreInteractions(); }
@Test public void shouldPassInputWithoutNewLinesUnchanged() { lineSplitter.process(PART1); verify(receiver).process(PART1); verifyNoMoreInteractions(receiver); }
@Test public void shouldOutputEmptyStringsForSequencesOfNewLines() { lineSplitter.process(PART1 + "\n\n" + PART2); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(PART1); ordered.verify(receiver).process(""); ordered.verify(receiver).process(PART2); ordered.verifyNoMoreInteractions(); }
@Test public void shouldOutputEmptyStringForNewLinesAtStartOfTheInput() { lineSplitter.process("\n" + PART1); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(""); ordered.verify(receiver).process(PART1); ordered.verifyNoMoreInteractions(); }
@Test public void shouldNotOutputEmptyStringForNewLinesAtEndOfTheInput() { lineSplitter.process(PART1 + "\n"); verify(receiver).process(PART1); verifyNoMoreInteractions(receiver); } |
UnicodeNormalizer extends
DefaultObjectPipe<String, ObjectReceiver<String>> { @Override public void process(final String str) { assert null != str; assert !isClosed(); getReceiver().process(Normalizer.normalize(str, normalizationForm)); } void setNormalizationForm(final Normalizer.Form normalizationForm); Normalizer.Form getNormalizationForm(); @Override void process(final String str); static final Normalizer.Form DEFAULT_NORMALIZATION_FORM; } | @Test public void testShouldReplaceDiacriticsWithPrecomposedChars() { normalizer.process(STRING_WITH_DIACRITICS); verify(receiver).process(STRING_WITH_PRECOMPOSED_CHARS); } |
PojoDecoder extends DefaultObjectPipe<T, StreamReceiver> { @Override public void process(final T obj) { if (obj == null) { return; } assert !isClosed(); final TypeDecoder typeDecoder = typeDecoderFactory.create(obj.getClass()); getReceiver().startRecord(""); typeDecoder.decodeToStream(getReceiver(), null, obj); getReceiver().endRecord(); } @Override void process(final T obj); } | @Test public void shouldDecodeNullObject() { final PojoDecoder<Object> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); pojoDecoder.process(null); verifyZeroInteractions(receiver); }
@Test public void shouldDecodeEmptyPojo() { final PojoDecoder<EmptyPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); pojoDecoder.process(new EmptyPojo()); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeSimplePojo() { final PojoDecoder<SimplePojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final SimplePojo simplePojo = new SimplePojo(); simplePojo.setFirstField("value1"); simplePojo.secondField = "value2"; pojoDecoder.process(simplePojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("secondField", "value2"); ordered.verify(receiver).literal("firstField", "value1"); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeNestedPojo() { final PojoDecoder<NestedPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final SimplePojo simplePojo = new SimplePojo(); simplePojo.setFirstField("value1"); simplePojo.secondField = "value2"; final NestedPojo nestedPojo = new NestedPojo(); nestedPojo.setInnerPojo(simplePojo); pojoDecoder.process(nestedPojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).startEntity("innerPojo"); ordered.verify(receiver).literal("secondField", "value2"); ordered.verify(receiver).literal("firstField", "value1"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodePojoWithMetafactureSource() { final PojoDecoder<MetafactureSourcePojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final MetafactureSourcePojo mfSourcePojo = new MetafactureSourcePojo(); mfSourcePojo.setMetafactureSourceField( streamReceiver -> streamReceiver.literal("literal", "value")); pojoDecoder.process(mfSourcePojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).startEntity("metafactureSourceField"); ordered.verify(receiver).literal("literal", "value"); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeSimpleArrayPojo() { final PojoDecoder<SimpleArrayPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final String[] valueArray = { "array-value1", "array-value2"}; final SimpleArrayPojo simpleArrayPojo = new SimpleArrayPojo(); simpleArrayPojo.setArrayField(valueArray); pojoDecoder.process(simpleArrayPojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("arrayField", "array-value1"); ordered.verify(receiver).literal("arrayField", "array-value2"); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeSimpleListPojo() { final PojoDecoder<SimpleListPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final List<String> valueList = Arrays.asList("list-value1", "list-value2"); final SimpleListPojo simpleListPojo = new SimpleListPojo(); simpleListPojo.setListField(valueList); pojoDecoder.process(simpleListPojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("listField", "list-value1"); ordered.verify(receiver).literal("listField", "list-value2"); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeSimpleSetPojo() { final PojoDecoder<SimpleSetPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final Set<String> valueSet = new HashSet<>(Arrays.asList( "set-value1", "set-value2")); final SimpleSetPojo simpleSetPojo = new SimpleSetPojo(); simpleSetPojo.setSetField(valueSet); pojoDecoder.process(simpleSetPojo); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("setField", "set-value1"); ordered.verify(receiver).literal("setField", "set-value2"); ordered.verify(receiver).endRecord(); }
@Test public void shouldDecodeSimpleMapPojo() { final PojoDecoder<SimpleMapPojo> pojoDecoder = new PojoDecoder<>(); pojoDecoder.setReceiver(receiver); final Map<String, String> mapField = new HashMap<>(); mapField.put("key1", "value1"); mapField.put("key2", "value2"); final SimpleMapPojo simpleMapPojo = new SimpleMapPojo(); simpleMapPojo.setMapField(mapField); pojoDecoder.process(simpleMapPojo); final ArgumentCaptor<String> nameCaptor = ArgumentCaptor.forClass(String.class); final ArgumentCaptor<String> valueCaptor = ArgumentCaptor.forClass(String.class); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).startEntity("mapField"); ordered.verify(receiver, times(2)).literal( nameCaptor.capture(), valueCaptor.capture()); assertEquals(mapField.get(nameCaptor.getAllValues().get(0)), valueCaptor.getAllValues().get(0)); assertEquals(mapField.get(nameCaptor.getAllValues().get(1)), valueCaptor.getAllValues().get(1)); ordered.verify(receiver).endEntity(); ordered.verify(receiver).endRecord(); } |
MapToStream extends
DefaultObjectPipe<Map<?, ?>, StreamReceiver> { @Override public void process(final Map<?, ?> map) { final Object id = map.get(idKey); if (id == null) { getReceiver().startRecord(""); } else { getReceiver().startRecord(id.toString()); } for (final Map.Entry<?, ?> entry: map.entrySet()) { getReceiver().literal(entry.getKey().toString(), entry.getValue().toString()); } getReceiver().endRecord(); } void setIdKey(final Object idKey); Object getIdKey(); @Override void process(final Map<?, ?> map); } | @Test public void shouldEmitEmptyRecordIfMapIsEmpty() { mapToStream.process(new HashMap<>()); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).endRecord(); }
@Test public void shouldEmitMapEntryAsLiteral() { final Map<String, String> map = new HashMap<>(); map.put("key", "value"); mapToStream.process(map); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord(""); ordered.verify(receiver).literal("key", "value"); ordered.verify(receiver).endRecord(); }
@Test public void shouldEmitAllMapEntriesAsLiterals() { final Map<String, String> map = new HashMap<>(); map.put("key-1", "value-1"); map.put("key-2", "value-2"); mapToStream.process(map); verify(receiver).literal("key-1", "value-1"); verify(receiver).literal("key-2", "value-2"); }
@Test public void shouldUseMapEntryWithDefaultIdNameAsRecordId() { final Map<String, String> map = new HashMap<>(); map.put("_id", "id-1"); mapToStream.process(map); verify(receiver).startRecord("id-1"); }
@Test public void shouldEmitEmptyRecordIdIfNoEntryWithIdKeyIsFoundInMap() { final Map<String, String> map = new HashMap<>(); map.put("noid", "noid"); mapToStream.process(map); verify(receiver).startRecord(""); } |
CsvDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String string) { assert !isClosed(); final String[] parts = parseCsv(string); if(hasHeader){ if(header.length==0){ header = parts; }else if(parts.length==header.length){ getReceiver().startRecord(String.valueOf(++count)); for (int i = 0; i < parts.length; ++i) { getReceiver().literal(header[i], parts[i]); } getReceiver().endRecord(); }else{ throw new IllegalArgumentException( String.format( "wrong number of columns (expected %s, was %s) in input line: %s", header.length, parts.length, string)); } }else{ getReceiver().startRecord(String.valueOf(++count)); for (int i = 0; i < parts.length; ++i) { getReceiver().literal(String.valueOf(i), parts[i]); } getReceiver().endRecord(); } } CsvDecoder(final String separator); CsvDecoder(final char separator); CsvDecoder(); @Override void process(final String string); void setHasHeader(final boolean hasHeader); void setSeparator(final String separator); } | @Test public void testSimple() { decoder.process("a,b,c"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("h1", "a"); ordered.verify(receiver).literal("h2", "b"); ordered.verify(receiver).literal("h3", "c"); ordered.verify(receiver).endRecord(); }
@Test public void testQuoted() { decoder.process("a,\"b1,b2,b3\",c"); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).startRecord("1"); ordered.verify(receiver).literal("h1", "a"); ordered.verify(receiver).literal("h2", "b1,b2,b3"); ordered.verify(receiver).literal("h3", "c"); ordered.verify(receiver).endRecord(); } |
AseqDecoder extends DefaultObjectPipe<String, StreamReceiver> { @Override public void process(final String record) { assert !isClosed(); final String trimedRecord = record.trim(); if (trimedRecord.isEmpty()) { return; } final String[] lines = trimedRecord.split(FIELD_DELIMITER); for (int i = 0; i < lines.length; i++) { final String field = lines[i]; if (i == 0) { getReceiver().startRecord(field.substring(0, 9)); } final String category = field.substring(10, 15).trim(); final String fieldContent = field.substring(18).trim(); if (!fieldContent.startsWith("$$")) { getReceiver().literal(category, fieldContent); } else { getReceiver().startEntity(category); final String[] subfields = fieldContent.split("\\$\\$"); for (final String subfield : subfields) { if (!subfield.isEmpty()) { getReceiver().literal(subfield.substring(0, 1), subfield.substring(1)); } } getReceiver().endEntity(); } } getReceiver().endRecord(); } @Override void process(final String record); } | @Test public void shouldReturnRecordId() { this.aseqDecoder.process(RECORD_ID + FIELD_LDR); final InOrder ordered = inOrder(this.receiver); ordered.verify(this.receiver).startRecord(RECORD_ID); }
@Test public void testShouldParseRecordStartingWithRecordMarker() { this.aseqDecoder.process(RECORD_ID + FIELD_LDR); final InOrder ordered = inOrder(this.receiver); ordered.verify(this.receiver).startRecord(RECORD_ID); verifyLdrTest(ordered); ordered.verify(this.receiver).endRecord(); }
@Test public void testShouldParseRecordWithTwoFields() { this.aseqDecoder.process(RECORD_ID + FIELD_LDR + FIELD_MARKER + RECORD_ID + FIELD_001_a_TEST + FIELD_MARKER + FIELD_200_TEST); final InOrder ordered = inOrder(this.receiver); ordered.verify(this.receiver).startRecord(RECORD_ID); verifyLdrTest(ordered); verify001_a_Test(ordered); verify200(ordered); ordered.verify(this.receiver).endRecord(); } |
DirectoryEntry { char[] getTag() { assert currentPosition < directoryEnd; return buffer.charsAt(currentPosition, TAG_LENGTH); } DirectoryEntry(final Iso646ByteBuffer buffer, final RecordFormat recordFormat,
final int baseAddress); @Override String toString(); } | @Test public void constructor_shouldSetFirstEntryAsCurrentEntry() { assertArrayEquals("001".toCharArray(), directoryEntry.getTag()); } |
DirectoryEntry { boolean endOfDirectoryReached() { return currentPosition >= directoryEnd; } DirectoryEntry(final Iso646ByteBuffer buffer, final RecordFormat recordFormat,
final int baseAddress); @Override String toString(); } | @Test public void endOfDirectoryReached_shouldReturnFalseIfNotAtEndOFDirectory() { assertFalse(directoryEntry.endOfDirectoryReached()); } |
Iso646ByteBuffer { int getLength() { return byteArray.length; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void getLength_shouldReturnRecordLength() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(3, byteBuffer.getLength()); } |
Iso646ByteBuffer { int getFreeSpace() { return byteArray.length - writePosition; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void getFreeSpace_shouldReturnBufferLengthIfNothingWasWritten() { byteBuffer = new Iso646ByteBuffer(5); assertEquals(5, byteBuffer.getFreeSpace()); } |
Iso646ByteBuffer { int distanceTo(final byte byteValue, final int fromIndex) { assert 0 <= fromIndex && fromIndex < byteArray.length; int index = fromIndex; for (; index < byteArray.length; ++index) { if (byteValue == byteArray[index]) { break; } } return index - fromIndex; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void distanceTo_byte_shouldReturnDistanceToFirstMatchingByte() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(2, byteBuffer.distanceTo((byte) 'x', 0)); }
@Test public void distanceTo_byte_shouldReturnDistanceToEndOfBufferIfNoMatchFound() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(3, byteBuffer.distanceTo((byte) 'X', 0)); }
@Test public void distanceTo_byte_shouldReturnZeroIfSearchStartsAtMatchingByte() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(0, byteBuffer.distanceTo((byte) 'T', 0)); }
@Test public void distanceTo_byteArray_shouldReturnDistanceToFirstMatchingByte() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(2, byteBuffer.distanceTo(asBytes("x"), 0)); }
@Test public void distanceTo_byteArray_shouldReturnDistanceToEndOfBufferIfNoMatchFound() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(3, byteBuffer.distanceTo(asBytes("X"), 0)); }
@Test public void distanceTo_byteArray_shouldReturnZeroIfSearchStartsAtMatchingByte() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(0, byteBuffer.distanceTo(asBytes("T"), 0)); }
@Test public void distanceTo_byteArray_shouldReturnDistanceToFirstMatchingByteOfTheBytesArray() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals(1, byteBuffer.distanceTo(asBytes("xu"), 0)); } |
RecordReader extends
DefaultObjectPipe<Reader, ObjectReceiver<String>> { @Override public void process(final Reader reader) { assert !isClosed(); try { boolean nothingRead = true; int size; while ((size = reader.read(buffer)) != -1) { nothingRead = false; int offset = 0; for (int i = 0; i < size; ++i) { if (buffer[i] == separator) { builder.append(buffer, offset, i - offset); offset = i + 1; emitRecord(); } } builder.append(buffer, offset, size - offset); } if (!nothingRead) { emitRecord(); } } catch (final IOException e) { throw new MetafactureException(e); } } void setSeparator(final String separator); void setSeparator(final char separator); char getSeparator(); void setSkipEmptyRecords(final boolean skipEmptyRecords); boolean getSkipEmptyRecords(); @Override void process(final Reader reader); static final char DEFAULT_SEPARATOR; } | @Test public void testShouldUseGlobalSeparatorAsDefaultSeparator() { recordReader.process(new StringReader( RECORD1 + DEFAULT_SEPARATOR + RECORD2 + DEFAULT_SEPARATOR)); final InOrder ordered = inOrder(receiver); ordered.verify(receiver).process(RECORD1); ordered.verify(receiver).process(RECORD2); verifyNoMoreInteractions(receiver); } |
Iso646ByteBuffer { String stringAt(final int fromIndex, final int length, final Charset charset) { return new String(byteArray, fromIndex, length, charset); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void stringAt_shouldReturnEmptyStringIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals("", byteBuffer.stringAt(0, 0, StandardCharsets.UTF_8)); } |
Iso646ByteBuffer { char charAt(final int index) { return byteToChar(index); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void charAt_shouldReturnCharacterAtIndexDecodedAsIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertEquals('T', byteBuffer.charAt(0)); }
@Test(expected = FormatException.class) public void charAt_shouldThrowFormatExceptionIfByteValueIsNotInIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("ü")); byteBuffer.charAt(0); } |
Iso646ByteBuffer { char[] charsAt(final int fromIndex, final int length) { assert length >= 0; assert 0 <= fromIndex && (fromIndex + length) <= byteArray.length; final char[] chars = new char[length]; for (int i = 0; i < length; ++i) { chars[i] = byteToChar(fromIndex + i); } return chars; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void charsAt_shouldReturnBytesAsCharacterArrayDecodedAsIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux Tox")); assertArrayEquals("Tux".toCharArray(), byteBuffer.charsAt(0, 3)); }
@Test(expected = FormatException.class) public void charsAt_shouldThrowFormatExceptionIfByteValueIsNotInIso646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tüx Tox")); byteBuffer.charsAt(0, 4); }
@Test public void charsAt_shouldReturnEmptyCharacterArrayIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); assertArrayEquals(new char[0], byteBuffer.charsAt(0, 0)); } |
Iso646ByteBuffer { byte byteAt(final int index) { return byteArray[index]; } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void byteAt_shouldReturnByteAtIndex() { byteBuffer = new Iso646ByteBuffer(new byte[] { 0x01, 0x02 }); assertEquals(0x02, byteBuffer.byteAt(1)); } |
Iso646ByteBuffer { int parseIntAt(final int index) { return byteToDigit(index); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void parseIntAt_shouldReturnIntValueAtIndex() { byteBuffer = new Iso646ByteBuffer(asBytes("299")); assertEquals(2, byteBuffer.parseIntAt(0)); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNotADigit() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); byteBuffer.parseIntAt(0); }
@Test public void parseIntAt_shouldReturnIntValueForRange() { byteBuffer = new Iso646ByteBuffer(asBytes("299")); assertEquals(299, byteBuffer.parseIntAt(0, 3)); }
@Test public void parseIntAt_shouldReturnZeroIfLengthIsZero() { byteBuffer = new Iso646ByteBuffer(asBytes("123")); assertEquals(0, byteBuffer.parseIntAt(0, 0)); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNotANumber() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux")); byteBuffer.parseIntAt(0, 3); }
@Test(expected = NumberFormatException.class) public void parseIntAt_shouldThrowFormatExceptionIfNumberIsTooLarge() { byteBuffer = new Iso646ByteBuffer(asBytes("123456789123456789")); byteBuffer.parseIntAt(0, 18); } |
FileOpener extends DefaultObjectPipe<String, ObjectReceiver<Reader>> { @Override public void process(final String file) { try { final InputStream fileStream = new FileInputStream(file); try { final InputStream decompressor = compression.createDecompressor(fileStream); try { final Reader reader = new InputStreamReader(new BOMInputStream( decompressor), encoding); getReceiver().process(reader); } catch (final IOException | MetafactureException e) { decompressor.close(); throw e; } } catch (final IOException | MetafactureException e) { fileStream.close(); throw e; } } catch (final IOException e) { throw new MetafactureException(e); } } String getEncoding(); void setEncoding(final String encoding); FileCompression getCompression(); void setCompression(final FileCompression compression); void setCompression(final String compression); @Override void process(final String file); } | @Test public void testUtf8IsDefaultEncoding() throws IOException { assumeFalse("Default encoding is UTF-8: It is not possible to test whether " + "FileOpener sets the encoding to UTF-8 correctly.", StandardCharsets.UTF_8.equals(Charset.defaultCharset())); final File testFile = createTestFile(); final FileOpener opener = new FileOpener(); opener.setReceiver(receiver); opener.process(testFile.getAbsolutePath()); opener.closeStream(); verify(receiver).process(processedObject.capture()); assertEquals(DATA, ResourceUtil.readAll(processedObject.getValue())); } |
Iso646ByteBuffer { @Override public String toString() { return stringAt(0, byteArray.length, Iso646Constants.CHARSET); } Iso646ByteBuffer(final int size); Iso646ByteBuffer(final byte[] byteArray); @Override String toString(); } | @Test public void toString_shouldReturnBufferContentDecodedAsISO646() { byteBuffer = new Iso646ByteBuffer(asBytes("Tux tüt")); assertEquals("Tux t" + ASCII_UNMAPPABLE_CHAR + ASCII_UNMAPPABLE_CHAR + "t", byteBuffer.toString()); } |
Record { public String getRecordId() { if (recordIdFieldStart == RECORD_ID_MISSING) { return null; } final int dataStart = baseAddress + recordIdFieldStart; final int dataLength = buffer.distanceTo(DATA_SEPARATORS, dataStart); return buffer.stringAt(dataStart, dataLength, charset); } Record(final byte[] recordData); RecordFormat getRecordFormat(); char getRecordStatus(); char[] getImplCodes(); char[] getSystemChars(); char getReservedChar(); void setCharset(final Charset charset); Charset getCharset(); String getRecordId(); String getLabel(); void processFields(final FieldHandler fieldHandler); } | @Test public void getIdentifier_shouldReturnRecordIdentifier() { final byte[] data = asBytes("00034SIMPL0000030SYS110R" + "00120\u001e" + "ID\u001e\u001d"); record = new Record(data); assertEquals("ID", record.getRecordId()); }
@Test public void getIdentifier_shouldReturnNullIfRecordHasNoIdentifier() { final byte[] data = asBytes("00034SIMPL0000030SYS110R" + "00220\u001e" + "XY\u001e\u001d"); record = new Record(data); assertNull(record.getRecordId()); } |
Record { public void processFields(final FieldHandler fieldHandler) { this.fieldHandler = Require.notNull(fieldHandler); boolean continuedField = false; directoryEntry.rewind(); while (!directoryEntry.endOfDirectoryReached()) { if (continuedField) { fieldHandler.additionalImplDefinedPart( directoryEntry.getImplDefinedPart()); } else { processField(); } continuedField = directoryEntry.isContinuedField(); directoryEntry.gotoNext(); } this.fieldHandler = null; } Record(final byte[] recordData); RecordFormat getRecordFormat(); char getRecordStatus(); char[] getImplCodes(); char[] getSystemChars(); char getReservedChar(); void setCharset(final Charset charset); Charset getCharset(); String getRecordId(); String getLabel(); void processFields(final FieldHandler fieldHandler); } | @Test public void processFields_shouldCallHandlerReferenceFieldForReferenceFields() { final byte[] data = asBytes("00042SIMPL0000035SYS110R" + "00120" + "00223\u001e" + "ID\u001e" + "XY\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).referenceField(asChars("001"), asChars(""), "ID"); ordered.verify(fieldHandler).referenceField(asChars("002"), asChars(""), "XY"); }
@Test public void processFields_shouldHandleDataFieldsInRecordWithoutIndicatorsAndIdentifiers() { final byte[] data = asBytes("00044SIMPL0000037SYS111R" + "01120X" + "01223Y\u001e" + "F1\u001e" + "F2\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars("X"), asChars("")); ordered.verify(fieldHandler).data(asChars(""), "F1"); ordered.verify(fieldHandler).endDataField(); ordered.verify(fieldHandler).startDataField(asChars("012"), asChars("Y"), asChars("")); ordered.verify(fieldHandler).data(asChars(""), "F2"); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleDataFieldsInRecordWithIndicatorsButWithoutIdentifiers() { final byte[] data = asBytes("00044SIMPL1000035SYS110R" + "01130" + "01234\u001e" + "XF1\u001e" + "YF2\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("X")); ordered.verify(fieldHandler).data(asChars(""), "F1"); ordered.verify(fieldHandler).endDataField(); ordered.verify(fieldHandler).startDataField(asChars("012"), asChars(""), asChars("Y")); ordered.verify(fieldHandler).data(asChars(""), "F2"); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleDataFieldsInRecordWithoutIndicatorsButWithTwoOctetIdentifiers() { final byte[] data = asBytes("00050SIMPL0200035SYS110R" + "01150" + "01295\u001e" + "\u001fXF1\u001e" + "\u001fYF2\u001fZF3\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("")); ordered.verify(fieldHandler).data(asChars("X"), "F1"); ordered.verify(fieldHandler).endDataField(); ordered.verify(fieldHandler).startDataField(asChars("012"), asChars(""), asChars("")); ordered.verify(fieldHandler).data(asChars("Y"), "F2"); ordered.verify(fieldHandler).data(asChars("Z"), "F3"); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleDataFieldsInRecordWithoutIndicatorsButWithOneOctetIdentifiers() { final byte[] data = asBytes("00038SIMPL0100030SYS110R" + "01170\u001e" + "\u001fF1\u001fF2\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("")); ordered.verify(fieldHandler).data(asChars(""), "F1"); ordered.verify(fieldHandler).data(asChars(""), "F2"); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleEmptyDataFieldInRecordWithoutIndicatorsButWithIdentifiers() { final byte[] data = asBytes("00032SIMPL0200030SYS110R" + "01110\u001e" + "\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("")); ordered.verify(fieldHandler, never()).data(any(char[].class), any(String.class)); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleDataFieldsWithoutContentInRecordWithoutIndicatorsButWithIdentifiers() { final byte[] data = asBytes("00036SIMPL0200030SYS110R" + "01150\u001e" + "\u001fX\u001fY\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("")); ordered.verify(fieldHandler).data(asChars("X"), ""); ordered.verify(fieldHandler).data(asChars("Y"), ""); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldHandleDataFieldsInRecordWithIndicatorsAndOctetIdentifiers() { final byte[] data = asBytes("00051SIMPL2200035SYS110R" + "01160" + "01296\u001e" + "AB\u001fX1\u001e" + "CD\u001fY2\u001fZ3\u001e" + "\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars(""), asChars("AB")); ordered.verify(fieldHandler).data(asChars("X"), "1"); ordered.verify(fieldHandler).endDataField(); ordered.verify(fieldHandler).startDataField(asChars("012"), asChars(""), asChars("CD")); ordered.verify(fieldHandler).data(asChars("Y"), "2"); ordered.verify(fieldHandler).data(asChars("Z"), "3"); ordered.verify(fieldHandler).endDataField(); }
@Test public void processFields_shouldConcatenateContinuedReferenceFieldsAndReportAllImplDefinedParts() { final byte[] data = asBytes("00062SIMPL0000046SYS121R" + "001000A" + "001309B" + "002312C\u001e" + "abcdefghijk\u001e" + "XY\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).referenceField(asChars("001"), asChars("A"), "abcdefghijk"); ordered.verify(fieldHandler).additionalImplDefinedPart(asChars("B")); ordered.verify(fieldHandler).referenceField(asChars("002"), asChars("C"), "XY"); }
@Test public void processFields_shouldConcatenateContinuedFieldsAndReportAllImplDefinedParts() { final byte[] data = asBytes("00062SIMPL0000046SYS121R" + "011000A" + "011309B" + "012312C\u001e" + "abcdefghijk\u001e" + "XY\u001e\u001d"); record = new Record(data); record.processFields(fieldHandler); final InOrder ordered = inOrder(fieldHandler); ordered.verify(fieldHandler).startDataField(asChars("011"), asChars("A"), asChars("")); ordered.verify(fieldHandler).data(asChars(""), "abcdefghijk"); ordered.verify(fieldHandler).endDataField(); ordered.verify(fieldHandler).additionalImplDefinedPart(asChars("B")); ordered.verify(fieldHandler).startDataField(asChars("012"), asChars("C"), asChars("")); ordered.verify(fieldHandler).data(asChars(""), "XY"); ordered.verify(fieldHandler).endDataField(); } |
Label { RecordFormat getRecordFormat() { return RecordFormat.create() .withIndicatorLength(getIndicatorLength()) .withIdentifierLength(getIdentifierLength()) .withFieldLengthLength(getFieldLengthLength()) .withFieldStartLength(getFieldStartLength()) .withImplDefinedPartLength(getImplDefinedPartLength()) .build(); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getRecordFormat_shouldReturnRecordFormatObject() { final RecordFormat recordFormat = label.getRecordFormat(); assertNotNull(recordFormat); final RecordFormat expectedFormat = RecordFormat.create() .withIndicatorLength(INDICATOR_LENGTH) .withIdentifierLength(IDENTIFIER_LENGTH) .withFieldStartLength(FIELD_START_LENGTH) .withFieldLengthLength(FIELD_LENGTH_LENGTH) .withImplDefinedPartLength(IMPL_DEFINED_PART_LENGTH) .build(); assertEquals(expectedFormat, recordFormat); } |
Label { int getRecordLength() { return buffer.parseIntAt(RECORD_LENGTH_START, RECORD_LENGTH_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getRecordLength_shouldReturnRecordLength() { assertEquals(RECORD_LENGTH, label.getRecordLength()); } |
Label { char getRecordStatus() { return buffer.charAt(RECORD_STATUS_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getRecordStatus_shouldReturnRecordStatus() { assertEquals(RECORD_STATUS, label.getRecordStatus()); } |
Label { char[] getImplCodes() { return buffer.charsAt(IMPL_CODES_START, IMPL_CODES_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getImplCodes_shouldReturnImplCodes() { assertArrayEquals(IMPL_CODES, label.getImplCodes()); } |
Label { int getIndicatorLength() { return buffer.parseIntAt(INDICATOR_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getIndicatorLength_shouldReturnIndicatorLength() { assertEquals(INDICATOR_LENGTH, label.getIndicatorLength()); } |
Label { int getIdentifierLength() { return buffer.parseIntAt(IDENTIFIER_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getIdentifierLength_shouldReturnIdentifierLength() { assertEquals(IDENTIFIER_LENGTH, label.getIdentifierLength()); } |
Label { int getBaseAddress() { return buffer.parseIntAt(BASE_ADDRESS_START, BASE_ADDRESS_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getBaseAddress_shouldReturnBaseAddress() { assertEquals(BASE_ADDRESS, label.getBaseAddress()); } |
Label { char[] getSystemChars() { return buffer.charsAt(SYSTEM_CHARS_START, SYSTEM_CHARS_LENGTH); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getSystemChars_shouldReturnUserSystemChars() { assertArrayEquals(SYSTEM_CHARS, label.getSystemChars()); } |
Label { int getFieldLengthLength() { return buffer.parseIntAt(FIELD_LENGTH_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getFieldLengthLength_shouldReturnFieldLengthLength() { assertEquals(FIELD_LENGTH_LENGTH, label.getFieldLengthLength()); } |
Label { int getFieldStartLength() { return buffer.parseIntAt(FIELD_START_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getFieldStartLength_shouldReturnFieldStartLength() { assertEquals(FIELD_START_LENGTH, label.getFieldStartLength()); } |
Label { int getImplDefinedPartLength() { return buffer.parseIntAt(IMPL_DEFINED_PART_LENGTH_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getImplDefinedPartLength_shouldReturnImplDefinedPartLength() { assertEquals(IMPL_DEFINED_PART_LENGTH, label.getImplDefinedPartLength()); } |
Label { char getReservedChar() { return buffer.charAt(RESERVED_CHAR_POS); } Label(final Iso646ByteBuffer buffer); @Override String toString(); } | @Test public void getReservedChar_shouldReturnReservedChar() { assertEquals(RESERVED_CHAR, label.getReservedChar()); } |
OptimizerBenchmark { public static void main(String... args) { setDebugLevel(Level.SEVERE); System.err.println("benchtmark"); (new OptimizerBenchmark()).runBenchmarks(); } static void main(String... args); void runBenchmarks(); OptimizationStrategy createStrategy(String which); static void setDebugLevel(Level newLvl); } | @Test public void testMain() { System.out.println("main"); String[] args = new String[]{}; OptimizerBenchmark.main(args); } |
CDep { public static void main(@NotNull String[] args) { int result; try { result = new CDep(AnsiConsole.out, AnsiConsole.err, true).go(args, false); resetAnsiColors(); } catch (Throwable e) { resetAnsiColors(); e.printStackTrace(System.err); result = 1; } System.exit(result); } CDep(@NotNull PrintStream out, @NotNull PrintStream err, boolean ansi); static void main(@NotNull String[] args); } | @Test public void lintUsage() throws Exception { assertThat(main("lint")).contains("Usage:"); }
@Test public void lintBoost() throws Exception { main(main("lint", "com.github.jomof:boost:1.0.63-rev18" )); }
@Test public void callerID() throws Exception { main(main("lint", "com.github.jomof:boost:1.0.63-rev18", "--caller-id", "cdep-unit-tests" )); }
@Test public void lintSomeKnownLibraries() throws Exception { main(main("lint", "com.github.jomof:sqlite:3.16.2-rev25", "com.github.jomof:boost:1.0.63-rev18", "com.github.jomof:sdl2:2.0.5-rev11")); }
@Test public void testVersion() throws Exception { assertThat(main("--version")).contains(BuildInfo.PROJECT_VERSION); }
@Test public void missingConfigurationFile() throws Exception { new File(".test-files/empty-folder").mkdirs(); assertThat(main("-wf", ".test-files/empty-folder")).contains("configuration file"); }
@Test public void workingFolderFlag() throws Exception { assertThat(main("--working-folder", "non-existing-blah")).contains("non-existing-blah"); }
@Test public void runCurl() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/runVectorial/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples, ndk-build]\ndependencies:" + "\n- compile: com.github.gpx1000:curl:7.56.0\n", yaml, StandardCharsets.UTF_8); String result = main("-wf", yaml.getParent()); System.out.printf(result); }
@Test public void runBoringSSL() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/runVectorial/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples, ndk-build]\ndependencies:" + "\n- compile: com.github.gpx1000:boringssl:0.0.0\n", yaml, StandardCharsets.UTF_8); String result = main("-wf", yaml.getParent()); System.out.printf(result); }
@Test public void wfFlag() throws Exception { assertThat(main("-wf", "non-existing-blah")).contains("non-existing-blah"); }
@Test public void testMissingGithubCoordinate() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/runMathfu/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github.jomof:mathfoo:1.0.2-rev7\n", yaml, StandardCharsets.UTF_8); try { String result = main("-wf", yaml.getParent()); System.out.printf(result); fail("Expected an exception"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Could not resolve 'com.github.jomof:mathfoo:1.0.2-rev7'. It doesn't exist."); assertThat(e.errorInfo.file).endsWith("cdep.yml"); assertThat(e.errorInfo.code).endsWith("c35a5b0"); } }
@Test public void startupInfo() throws Exception { String result = main("startup-info"); System.out.printf(result); }
@Test public void unfindableLocalFile() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/unfindableLocalFile/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n", yaml, StandardCharsets.UTF_8); try { main("-wf", yaml.getParent()); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist."); assertThat(e.errorInfo.file).endsWith("cdep.yml"); assertThat(e.errorInfo.code).isEqualTo("c35a5b0"); } }
@Test public void emptyCdepYml() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/emptyCdepYml/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("", yaml, StandardCharsets.UTF_8); try { String result = main("-wf", yaml.getParent()); System.out.print(result); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e.getMessage()).endsWith("cdep.yml was empty"); assertThat(e.errorInfo.file).endsWith("cdep.yml"); assertThat(e.errorInfo.line).isNull(); assertThat(e.errorInfo.code).isEqualTo("137b0ec"); } }
@Test public void sqlite() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/firebase/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); String result = main("-wf", yaml.getParent()); System.out.printf(result); }
@Test public void testGeneratedModulesFolder() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/testGeneratedModulesFolder/cdep.yml"); deleteDirectory(yaml.getParentFile()); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); File modulesFolder = new File(yaml.getParentFile(), "my-modules"); String result = main("-wf", yaml.getParent(), "-gmf", modulesFolder.getAbsolutePath()); System.out.printf(result); assertThat(modulesFolder.exists()).isTrue(); assertThat(modulesFolder.isDirectory()).isTrue(); File cdepOutput = new File(modulesFolder, "modules").getAbsoluteFile(); cdepOutput = new File(cdepOutput, "cdep-dependencies-config.cmake"); assertThat(cdepOutput.exists()).isTrue(); assertThat(cdepOutput.isFile()).isTrue(); }
@Test public void testOverrideBuildSystem() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/testOverrideBuildSystem/cdep.yml"); deleteDirectory(yaml.getParentFile()); yaml.getParentFile().mkdirs(); Files.write("builders: [ndkBuild]\n" + "dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); File modulesFolder = new File(yaml.getParentFile(), "my-modules"); String result = main("-wf", yaml.getParent(), "-gmf", modulesFolder.getAbsolutePath(), "--builder", "cmake"); System.out.printf(result); assertThat(modulesFolder.exists()).isTrue(); assertThat(modulesFolder.isDirectory()).isTrue(); File cdepOutput = new File(modulesFolder, "modules").getAbsoluteFile(); cdepOutput = new File(cdepOutput, "cdep-dependencies-config.cmake"); assertThat(cdepOutput.exists()).isTrue(); assertThat(cdepOutput.isFile()).isTrue(); }
@Test public void testUnknownOverrideBuildSystem() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/testUnknownOverrideBuildSystem/cdep.yml"); deleteDirectory(yaml.getParentFile()); yaml.getParentFile().mkdirs(); Files.write("builders: [ndkBuild]\n" + "dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); File modulesFolder = new File(yaml.getParentFile(), "my-modules"); try { main("-wf", yaml.getParent(), "-gmf", modulesFolder.getAbsolutePath(), "--builder", "unknown-build-system"); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Builder unknown-build-system is not recognized."); } }
@Test public void testUnknownOverrideBuildSystemNoBuilders() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/testUnknownOverrideBuildSystem/cdep.yml"); deleteDirectory(yaml.getParentFile()); yaml.getParentFile().mkdirs(); Files.write("dependencies:\n" + "- compile: com.github.jomof:sqlite:3.16.2-rev45\n", yaml, StandardCharsets.UTF_8); File modulesFolder = new File(yaml.getParentFile(), "my-modules"); try { main("-wf", yaml.getParent(), "-gmf", modulesFolder.getAbsolutePath(), "--builder", "unknown-build-system"); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Builder unknown-build-system is not recognized."); } }
@Test public void oldBoost() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/oldBoost-12/cdep.yml"); yaml.getParentFile().delete(); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake]\n" + "dependencies:\n" + "- compile: com.github.jomof:boost:1.0.63-rev10\n", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); try { String result = main("-wf", yaml.getParent()); System.out.printf(result); fail("Expected exception"); } catch (CDepRuntimeException e) { assertThat(e.errorInfo.file).endsWith("cdep-manifest.yml"); } File sha256 = new File(yaml.getParentFile(), "cdep.sha256"); assertThat(sha256.exists()).isFalse(); }
@Test public void showEmptyManifest() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/firebase/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); String result = main("-wf", yaml.getParent()); System.out.printf(result); }
@Test public void download() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/download/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); }
@Test public void mergeTwo() throws Exception { File output = new File(".test-files/mergeTwo/merged-manifest.yml"); output.delete(); String text = main("merge", "com.github.jomof:sqlite/iOS:3.16.2-rev33", "com.github.jomof:sqlite/android:3.16.2-rev33", output.toString()); System.out.printf(text); }
@Test public void alternateDownloadFoldersRelativePath1() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/alternateDownloadFolders1/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: my-downloaded-packages\n" + "generatedModulesFolder: my-modules\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(new File(yaml.getParent(), "my-downloaded-packages").isDirectory()).isTrue(); assertThat(new File(yaml.getParent(), "my-modules").isDirectory()).isTrue(); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); }
@Test public void alternateDownloadFoldersRelativePath2() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/alternateDownloadFolders2/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: ./my-downloaded-packages\n" + "generatedModulesFolder: ./my-modules\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(new File(yaml.getParent(), "my-downloaded-packages").isDirectory()).isTrue(); assertThat(new File(yaml.getParent(), "my-modules").isDirectory()).isTrue(); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); }
@Test public void alternateDownloadFoldersRelativePath3() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/alternateDownloadFolders3/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: ./my-downloaded-packages/nested\n" + "generatedModulesFolder: ./my-modules/nested\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(new File(yaml.getParent(), "my-downloaded-packages/nested").isDirectory()).isTrue(); assertThat(new File(yaml.getParent(), "my-modules/nested").isDirectory()).isTrue(); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); }
@Test public void alternateDownloadFoldersAbsolutePath() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/alternateDownloadFolders1/cdep.yml"); File downloadFolder = new File(yaml.getParent(), "my-downloaded-packages"); File modulesFolder = new File(yaml.getParent(), "my-modules"); yaml.getParentFile().mkdirs(); String text = "builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: {DOWNLOAD}\n" + "generatedModulesFolder: {GENERATED}\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n"; text = text.replace("{DOWNLOAD}", downloadFolder.getCanonicalPath()); text = text.replace("{GENERATED}", modulesFolder.getCanonicalPath()); Files.write(text, yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(downloadFolder.isDirectory()).isTrue(); assertThat(modulesFolder.isDirectory()).isTrue(); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); }
@Test public void redownload() throws Exception { CDepYml config = new CDepYml(); File yaml = new File(".test-files/redownload/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("redownload", "-wf", yaml.getParent()); System.out.printf(result); assertThat(result).contains("Redownload"); }
@Test public void fetch() throws Exception { File folder = new File(".test-files/fetch"); folder.mkdirs(); String result = main("fetch", "com.github.jomof:low-level-statistics:0.0.16", "com.github" + ".jomof:low-level-statistics:0.0.16", "-wf", folder.toString()); System.out.printf(result); assertThat(result).contains("Fetch complete"); }
@Test public void fetchArchive() throws Exception { File folder = new File(".test-files/fetchArchive"); deleteDirectory(folder); folder.mkdirs(); File yaml = new File(folder, "cdep.yml"); File downloadFolder = new File(yaml.getParent(), "my-downloaded-packages"); File modulesFolder = new File(yaml.getParent(), "my-modules"); yaml.getParentFile().mkdirs(); String text = "builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: {DOWNLOAD}\n" + "generatedModulesFolder: {GENERATED}\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n"; text = text.replace("{DOWNLOAD}", downloadFolder.getCanonicalPath()); text = text.replace("{GENERATED}", modulesFolder.getCanonicalPath()); Files.write(text, yaml, StandardCharsets.UTF_8); String result = main("fetch-archive", "com.github.jomof:low-level-statistics:0.0.22", "https: "2035", "1661c899dee3b7cf1bb3e376c1cd504a156a4658904d8554a84db4e5a71ade49", "-wf", folder.toString()); System.out.printf(result); assertThat(result).contains("Downloading"); assertThat(result).contains("low-level-statistics-android-platform-21-armeabi"); }
@Test public void checkArchiveSentinel() throws Exception { File yaml = new File(".test-files/checkArchiveSentinel/cdep.yml"); File downloadFolder = new File(yaml.getParent(), "my-downloaded-packages"); File modulesFolder = new File(yaml.getParent(), "my-modules"); yaml.getParentFile().mkdirs(); String text = "builders: [cmake, cmakeExamples]\n" + "downloadedPackagesFolder: {DOWNLOAD}\n" + "generatedModulesFolder: {GENERATED}\n" + "dependencies:\n" + "- compile: com.github.jomof:low-level-statistics:0.0.16\n"; text = text.replace("{DOWNLOAD}", downloadFolder.getCanonicalPath()); text = text.replace("{GENERATED}", modulesFolder.getCanonicalPath()); Files.write(text, yaml, StandardCharsets.UTF_8); main("-wf", yaml.getParent()); String result = main("download", "-wf", yaml.getParent()); System.out.printf(result); assertThat(downloadFolder.isDirectory()).isTrue(); assertThat(modulesFolder.isDirectory()).isTrue(); assertThat(result).doesNotContain("Redownload"); assertThat(result).contains("Generating"); File sentinel = new File(downloadFolder, "exploded/com.github.jomof/low-level-statistics/0.0.16/low-level-statistics-android-platform-21.zip/cdep-archive.yml"); assertThat(sentinel.isFile()).isTrue(); }
@Test public void fetchNotFound() throws Exception { File folder = new File(".test-files/fetch"); folder.mkdirs(); try { main("fetch", "com.github.jomof:low-level-statistics-y:0.0.16", "-wf", folder.toString()); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Could not resolve 'com.github.jomof:low-level-statistics-y:0.0.16'. It doesn't exist."); assertThat(e.errorInfo.code).isEqualTo("c35a5b0"); } }
@Test public void createHashes() throws Exception { File yaml = new File(".test-files/simpleDependency/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); String text = main("create", "hashes", "-wf", yaml.getParent()); assertThat(text).contains("Created cdep.sha256"); File hashFile = new File(".test-files/simpleDependency/cdep.sha256"); assertThat(hashFile.isFile()); }
@Test public void betterMessageForLibVsLibs() throws Exception { File manifest = new File(".test-files/betterMessageForLibVsLibs/cdep-manifest.yml"); manifest.delete(); manifest.getParentFile().mkdirs(); Files.write("coordinate:\n" + " groupId: com.github.test\n" + " artifactId: testlib\n" + " version: 0.0.0\n" + "license:\n" + " name: \"Apache 2.0\"\n" + "android:\n" + " dependencies:\n" + " archives:\n" + " - file: libtestlibs.zip\n" + " size: 1625375\n" + " ndk: r13b\n" + " runtime: c++\n" + " platform: 12\n" + " abi: armeabi\n" + " lib: libtestlib.a", manifest, StandardCharsets.UTF_8); try { main("lint", manifest.getPath()); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Could not parse manifest. The field 'lib' could not be created. Should it be 'libs'?"); assertThat(e.errorInfo.file).contains("cdep-manifest.yml"); assertThat(e.errorInfo.code).isEqualTo("bd4fadb"); assertThat(e.errorInfo.line).isEqualTo(null); return; } fail("Expected an exception"); }
@Test public void checkThatHashesWork() throws Exception { File yaml = new File(".test-files/checkThatHashesWork/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); File hashes = new File(".test-files/checkThatHashesWork/cdep.sha256"); Files.write("- coordinate: com.github.jomof:low-level-statistics:0.0.16\n " + "sha256: dogbone", hashes, StandardCharsets.UTF_8); try { main("-wf", yaml.getParent()); fail("Expected failure"); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("SHA256 of cdep-manifest.yml for package 'com.github.jomof:low-level-statistics:0.0.16' " + "does not agree with constant in cdep.sha256. Something changed."); assertThat(e.errorInfo.file).endsWith("cdep-manifest.yml"); assertThat(e.errorInfo.line).isEqualTo(3); assertThat(e.errorInfo.code).isEqualTo("1cb1fa8"); } }
@Test public void noDependencies() throws Exception { CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/simpleDependency/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n", yaml, StandardCharsets.UTF_8); String result1 = main("-wf", yaml.getParent()); System.out.printf(result1); assertThat(result1).contains("Nothing"); }
@Test public void dumpIsSelfHost() throws Exception { System.out.printf("%s\n", System.getProperty("user.home")); CDepYml config = new CDepYml(); System.out.printf(new Yaml().dump(config)); File yaml = new File(".test-files/simpleConfiguration/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]", yaml, StandardCharsets.UTF_8); String result1 = main("show", "manifest", "-wf", yaml.getParent()); yaml.delete(); Files.write(result1, yaml, StandardCharsets.UTF_8); System.out.print(result1); String result2 = main("show", "manifest", "-wf", yaml.getParent()); assertThat(result2).isEqualTo(result1); }
@Test public void testNakedCall() throws Exception { main(); }
@Test public void showFolders() throws Exception { String result = main("show", "folders"); System.out.printf(result); }
@Test public void showInclude() throws Exception { String result = main("show", "include", "com.github.jomof:boost:1.0.63-rev21"); assertThat(result).contains(".zip"); System.out.printf(result); }
@Test public void showIncludeNoCoordinate() throws Exception { String result = main("show", "include"); assertThat(result).contains("Usage: show include {coordinate}"); System.out.printf(result); }
@Test public void help() throws Exception { String result = main("--help"); System.out.printf(result); assertThat(result).contains("show folders"); }
@Test public void testWrapper() throws Exception { File testFolder = new File(".test-files/testWrapper"); File redistFolder = new File(testFolder, "redist"); File workingFolder = new File(testFolder, "working"); File cdepFile = new File(redistFolder, "cdep"); File cdepBatFile = new File(redistFolder, "cdep.bat"); File cdepYmlFile = new File(redistFolder, "cdep.yml"); File bootstrapJar = new File(redistFolder, "bootstrap/wrapper/bootstrap.jar"); redistFolder.mkdirs(); workingFolder.mkdirs(); bootstrapJar.getParentFile().mkdirs(); Files.write("cdepFile content", cdepFile, Charset.defaultCharset()); Files.write("cdepBatFile content", cdepBatFile, Charset.defaultCharset()); Files.write("cdepYmlFile content", cdepYmlFile, Charset.defaultCharset()); Files.write("bootstrapJar content", bootstrapJar, Charset.defaultCharset()); System.setProperty("io.cdep.appname", new File(redistFolder, "cdep.bat").getAbsolutePath()); String result; try { result = main("wrapper", "-wf", workingFolder.toString()); } finally { System.setProperty("io.cdep.appname", "rando-test-folder"); } System.out.print(result); assertThat(result).contains("Installing cdep"); File cdepToFile = new File(workingFolder, "cdep"); File cdepBatToFile = new File(workingFolder, "cdep.bat"); File cdepYmlToFile = new File(workingFolder, "cdep.yml"); File bootstrapJarToFile = new File(workingFolder, "bootstrap/wrapper/bootstrap.jar"); assertThat(cdepToFile.isFile()).isTrue(); assertThat(cdepBatToFile.isFile()).isTrue(); assertThat(cdepYmlToFile.isFile()).isTrue(); assertThat(bootstrapJarToFile.isFile()).isTrue(); }
@Test public void testWrapperSelfOverwrite() throws Exception { File testFolder = new File(".test-files/testWrapperSelfOverwrite"); File redistFolder = new File(testFolder, "redist"); File cdepFile = new File(redistFolder, "cdep"); File cdepBatFile = new File(redistFolder, "cdep.bat"); File cdepYmlFile = new File(redistFolder, "cdep.yml"); File bootstrapJar = new File(redistFolder, "bootstrap/wrapper/bootstrap.jar"); redistFolder.mkdirs(); bootstrapJar.getParentFile().mkdirs(); Files.write("cdepFile content", cdepFile, Charset.defaultCharset()); Files.write("cdepBatFile content", cdepBatFile, Charset.defaultCharset()); Files.write("cdepYmlFile content", cdepYmlFile, Charset.defaultCharset()); Files.write("bootstrapJar content", bootstrapJar, Charset.defaultCharset()); System.setProperty("io.cdep.appname", new File(redistFolder, "cdep.bat").getAbsolutePath()); String result; try { result = main("wrapper", "-wf", redistFolder.toString()); } catch (CDepRuntimeException e) { assertThat(e).hasMessage("Install source and destination are the same"); assertThat(e.errorInfo.code).isEqualTo("5ffdb7c"); return; } finally { System.setProperty("io.cdep.appname", "rando-test-folder"); } fail("Expected failure"); }
@Test public void mergeTwoWithDifferentHash() throws Exception { File left = new File(".test-files/mergeTwo/merged-manifest-left.yml"); File right = new File(".test-files/mergeTwo/merged-manifest-right.yml"); File merged = new File(".test-files/mergeTwo/merged-manifest-merged.yml"); left.delete(); right.delete(); merged.delete(); merged.getParentFile().mkdirs(); Files.write("coordinate:\n" + " groupId: com.github.jomof\n" + " artifactId: sdl2\n" + " version: 2.0.5-rev26\n" + "interfaces:\n" + " headers:\n" + " file: headers.zip\n" + " sha256: e7e61f29f9480209f1cad71c4d4f7cec75d63e7a457bbe9da0ac26a64ad5751b-left\n" + " size: 338812\n" + " include: include", left, StandardCharsets.UTF_8); Files.write("coordinate:\n" + " groupId: com.github.jomof\n" + " artifactId: sdl2\n" + " version: 2.0.5-rev26\n" + "interfaces:\n" + " headers:\n" + " file: headers.zip\n" + " sha256: e7e61f29f9480209f1cad71c4d4f7cec75d63e7a457bbe9da0ac26a64ad5751-right\n" + " size: 338812\n" + " include: include", right, StandardCharsets.UTF_8); merged.getParentFile().mkdirs(); String text = main("merge", left.toString(), right.toString(), merged.toString()); System.out.printf(text); String mergedText = FileUtils.readAllText(merged); System.out.printf(mergedText); assertThat(mergedText).contains("-right"); }
@Test public void localPathsWork() throws Exception { File yaml = new File(".test-files/localPathsWork/cdep.yml"); yaml.getParentFile().mkdirs(); Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: com.github" + ".jomof:low-level-statistics:0.0.16\n", yaml, StandardCharsets.UTF_8); String resultRemote = main("-wf", yaml.getParent()); String localPath = main("show", "local", "com.github.jomof:low-level-statistics:0.0.16"); assertThat(localPath).contains("cdep-manifest.yml"); Files.write(String.format("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: %s\n", localPath), yaml, StandardCharsets.UTF_8); String resultLocal = main("-wf", yaml.getParent(), "-df", new File(yaml.getParent(), "downloads").getPath()); System.out.print(resultLocal); resultLocal = main("-wf", yaml.getParent()); System.out.print(resultLocal); }
@Test public void fullfill() throws Exception { String text = main("fullfill", "../third_party/stb", "1.0.0", "../third_party/stb/cdep/cdep-manifest-divide.yml", "../third_party/stb/cdep/cdep-manifest-c_lexer.yml"); System.out.printf(text); }
@Test public void mergeHeaders() throws Exception { File output = new File(".test-files/mergeHeaders/merged-manifest.yml"); File zip = new File(".test-files/mergeHeaders/headers.zip"); zip.getParentFile().mkdirs(); Files.write("xyz", zip, StandardCharsets.UTF_8); output.delete(); String text = main("merge", "headers", "com.github.jomof:sqlite:3.16.2-rev48", zip.toString(), "include", output.toString()); assertThat(text).doesNotContain("Usage"); assertThat(text).contains("Merged com.github.jomof:sqlite:3.16.2-rev48 and "); System.out.printf(text); System.out.printf(FileUtils.readAllText(output)); }
@Test public void mergeFirstMissing() throws Exception { File output = new File(".test-files/mergeFirstMissing/merged-manifest.yml"); output.delete(); assertThat(main("merge", "non:existing:1.2.3", "com.github.jomof:firebase/admob:2.1.3-rev8", output.toString())).contains ("Manifest for 'non:existing:1.2.3' didn't exist"); }
@Test public void mergeTwo1() throws Exception { File output = new File(".test-files/mergeTwo1/merged-manifest.yml"); output.delete(); assertThat(main("merge", "com.github.jomof:sqlite/iOS:3.16.2-rev26", "com.github.jomof:sqlite/android:3.16.2-rev26", output .toString())).contains("Merged 2 manifests into"); }
@Test public void mergeTwo2() throws Exception { File output = new File(".test-files/mergeTwo2/merged-manifest.yml"); output.delete(); assertThat(main("merge", "com.github.jomof:cmakeify/iOS:0.0.219", "com.github.jomof:cmakeify/android:0.0.219", output .toString())).contains("Merged 2 manifests into"); } |
StringUtils { public static boolean isNumeric(@NotNull String str) { for (char c : str.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); static boolean isNullOrEmpty(@Nullable String value); } | @Test public void isNumeric() throws Exception { assertThat(StringUtils.isNumeric("x")).isFalse(); assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNumber() { assertThat(StringUtils.isNumeric("1")).isTrue(); }
@Test public void checkIsNotNumber() { assertThat(StringUtils.isNumeric("x")).isFalse(); } |
StringUtils { public static String joinOn(String delimiter, @NotNull Object array[]) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length; ++i) { if (i != 0) { sb.append(delimiter); } sb.append(array[i]); } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); static boolean isNullOrEmpty(@Nullable String value); } | @Test public void joinOn() throws Exception { assertThat(StringUtils.joinOn("+", "1", "2", "3")).isEqualTo("1+2+3"); }
@Test public void joinOn1() throws Exception { assertThat(StringUtils.joinOn("+", new Integer[]{1, 2, 3})).isEqualTo("1+2+3"); }
@Test public void joinOn2() throws Exception { List<String> list = new ArrayList<>(); list.add("1"); list.add("3"); assertThat(StringUtils.joinOn("+", list)).isEqualTo("1+3"); } |
StringUtils { public static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings) { StringBuilder sb = new StringBuilder(); int i = 0; for (String string : strings) { if (string == null || string.isEmpty()) { continue; } if (i != 0) { sb.append(delimiter); } sb.append(string); ++i; } return sb.toString(); } static boolean isNumeric(@NotNull String str); static String joinOn(String delimiter, @NotNull Object array[]); static String joinOn(String delimiter, @NotNull Collection<String> strings); static String joinOn(String delimiter, @NotNull String ... strings); static String joinOnSkipNullOrEmpty(String delimiter, @NotNull String ... strings); @NotNull static String nullToEmpty(@Nullable String value); @NotNull static String[] singletonArrayOrEmpty(@Nullable String value); @NotNull static String whitespace(int indent); @NotNull static String safeFormat(@NotNull String format, Object ... args); static boolean containsAny(@NotNull String value, @NotNull String chars); @NotNull static String firstAvailable(@NotNull String value, int n); static boolean startsWithAny(@NotNull String value, @NotNull String chars); static boolean isNullOrEmpty(@Nullable String value); } | @Test public void joinOnSkipNull() throws Exception { assertThat(StringUtils.joinOnSkipNullOrEmpty("+", "1", null, "3")).isEqualTo("1+3"); } |
Invariant { public static void require(boolean check, @NotNull String format, Object... parameters) { if (check) { return; } ErrorInfo errorInfo = getBestErrorInfo(format, parameters); report(new CDepRuntimeException(safeFormat(format, parameters), errorInfo)); } static void registerYamlFile(String file); static void registerYamlNodes(String file, Map<Object, Node> yamlNodes); static void pushErrorCollectionScope(boolean showOutput); static List<CDepRuntimeException> popErrorCollectionScope(); static int errorsInScope(); static void fail(@NotNull String format); static void fail(@NotNull String format, Object... parameters); static void require(boolean check, @NotNull String format, Object... parameters); static boolean failIf(boolean check, @NotNull String format, Object... parameters); static void require(boolean check); } | @Test public void testRequireFalse() { try { require(false); throw new RuntimeException("Expected an exception"); } catch (RuntimeException e) { assertThat(e).hasMessage("Invariant violation"); } }
@Test public void testRequireTrue() { require(true); } |
CDepManifestYmlUtils { public static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml) { new Checker().visit(cdepManifestYml, CDepManifestYml.class); } @NotNull static String convertManifestToString(@NotNull CDepManifestYml manifest); @NotNull static CDepManifestYml convertStringToManifest(@NotNull String url, @NotNull String content); static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml); @NotNull static List<HardNameDependency> getTransitiveDependencies(@NotNull CDepManifestYml cdepManifestYml); } | @Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("archiveMissingSha256", "Archive com.github.jomof:vectorial:0.0.0 is missing sha256"); expected.put("sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("archiveMissingFile", "Archive com.github.jomof:vectorial:0.0.0 is missing file"); expected.put("templateWithNullArchives", "Package 'com.github.jomof:firebase/app:${version}' " + "has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile", "Package 'com.github.jomof:firebase/app:${version}' has " + "malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from archive1.zip given the information in the manifest"); expected.put("fuzz1", "Manifest was missing coordinate"); expected.put("fuzz2", "Manifest was missing coordinate"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { String key = manifest.name; String expectedFailure = expected.get(key); try { CDepManifestYmlUtils.checkManifestSanity(manifest.resolved.cdepManifestYml); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (!e.getMessage().equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void testTwoWayMergeSanity() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("archiveMissingFile-archiveMissingFile", "Archive com.github.jomof:vectorial:0.0.0 is missing file"); expected.put("archiveMissingSha256-archiveMissingSha256", "Archive com.github.jomof:vectorial:0.0.0 is missing sha256"); expected.put("sqliteLinuxMultiple-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-sqlite", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-singleABI", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinuxMultiple-sqliteLinux", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize-archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("admob-admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("sqlite-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("singleABISqlite-singleABISqlite", "Package 'com.github.jomof:sqlite:3.16.2-rev45' contains multiple references to the same archive file " + "'sqlite-android-cxx-platform-12-armeabi.zip'"); expected.put("singleABI-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("singleABI-singleABI", "Package 'com.github.jomof:sqlite:0.0.0' contains multiple references to the same archive file " + "'sqlite-android-cxx-platform-12-armeabi.zip'"); expected.put("sqliteLinux-sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteLinux-sqliteLinux", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("sqliteiOS-sqliteiOS", "Package 'com.github.jomof:sqlite:3.16.2-rev33' contains multiple references to the same archive file " + "'sqlite-ios-platform-iPhoneOS-architecture-armv7-sdk-9.3.zip'"); expected.put("templateWithNullArchives-templateWithNullArchives", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithNullArchives-templateWithOnlyFile", "Package 'com.github.jomof:" + "firebase/app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile-templateWithNullArchives", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("templateWithOnlyFile-templateWithOnlyFile", "Package 'com.github.jomof:firebase/" + "app:${version}' has malformed version, expected major.minor.point[-tweak] but there were no dots"); expected.put("sqlite-sqlite", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("sqlite-singleABI", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("sqliteAndroid-sqliteAndroid", "Android archive com.github.jomof:sqlite:3.16.2-rev33 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12.zip given the information in the manifest"); expected.put("singleABI-sqlite", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("singleABI-singleABI", "Android archive com.github.jomof:sqlite:0.0.0 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("indistinguishableAndroidArchives-indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from archive1.zip given the information in the manifest"); expected.put("singleABISqlite-singleABISqlite", "Android archive com.github.jomof:sqlite:3.16.2-rev45 file sqlite-android-cxx-platform-12-armeabi.zip is indistinguishable at build time from sqlite-android-cxx-platform-12-armeabi.zip given the information in the manifest"); expected.put("re2-re2", "Android archive com.github.jomof:re2:17.3.1-rev13 file re2-21-armeabi.zip is indistinguishable at build time from re2-21-armeabi.zip given the information in the manifest"); expected.put("fuzz1-fuzz1", "Manifest was missing coordinate"); expected.put("fuzz2-fuzz2", "Manifest was missing coordinate"); expected.put("openssl-openssl", "Android archive com.github.jomof:openssl:1.0.1-e-rev6 file openssl-android-stlport-21-armeabi.zip is indistinguishable at build time from openssl-android-stlport-21-armeabi.zip given the information in the manifest"); expected.put("opencv-opencv", "Android archive com.github.jomof:opencv:3.2.0-rev2 file opencv-android-12-arm64-v8a.zip is indistinguishable at build time from opencv-android-12-arm64-v8a.zip given the information in the manifest"); expected.put("boringSSLAndroid-boringSSLAndroid", "Android archive com.github.gpx1000:boringssl:0.0.0 file boringssl-armeabi.zip is indistinguishable at build time from boringssl-armeabi.zip given the information in the manifest"); expected.put("zlibAndroid-zlibAndroid", "Android archive com.github.gpx1000:zlib:1.2.11 file zlib-armeabi.zip is indistinguishable at build time from zlib-armeabi.zip given the information in the manifest"); boolean somethingUnexpected = false; for (ResolvedManifests.NamedManifest manifest1 : ResolvedManifests.all()) { for (ResolvedManifests.NamedManifest manifest2 : ResolvedManifests.all()) { if(Objects.equals(manifest1.name, "curlAndroid") || Objects.equals(manifest2.name, "curlAndroid")) continue; String key = manifest1.name + "-" + manifest2.name; String expectedFailure = expected.get(key); CDepManifestYml manifest; try { manifest = MergeCDepManifestYmls.merge(manifest1.resolved.cdepManifestYml, manifest2.resolved.cdepManifestYml); } catch (RuntimeException e) { continue; } try { CDepManifestYmlUtils.checkManifestSanity(manifest); if (expectedFailure != null) { TestCase.fail("Expected a failure."); } } catch (RuntimeException e) { String actual = e.getMessage(); if (!actual.equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, actual); somethingUnexpected = true; } } } } if (somethingUnexpected) { throw new RuntimeException("Saw unexpected results. See console."); } } |
CDepManifestYmlUtils { @NotNull public static CDepManifestYml convertStringToManifest(@NotNull String url, @NotNull String content) { Invariant.registerYamlFile(url); Yaml yaml = new Yaml(new Constructor(CDepManifestYml.class)); CDepManifestYml manifest; byte[] bytes = content.getBytes(StandardCharsets.UTF_8); try { manifest = (CDepManifestYml) yaml.load(new ByteArrayInputStream(bytes)); if (manifest != null) { manifest.sourceVersion = CDepManifestYmlVersion.vlatest; } } catch (YAMLException e) { try { manifest = V3Reader.convertStringToManifest(content); } catch (YAMLException e2) { if (!tryCreateSensibleParseError(e, 0)) { require(false, e.toString()); } return new CDepManifestYml(EMPTY_COORDINATE); } } require(manifest != null, "Manifest was empty"); assert manifest != null; manifest = new ConvertNullToDefaultRewriter().visitCDepManifestYml(manifest); Node nodes = yaml.compose(new InputStreamReader(new ByteArrayInputStream(bytes))); SnakeYmlUtils.mapAndRegisterNodes(url, manifest, nodes); return manifest; } @NotNull static String convertManifestToString(@NotNull CDepManifestYml manifest); @NotNull static CDepManifestYml convertStringToManifest(@NotNull String url, @NotNull String content); static void checkManifestSanity(@NotNull CDepManifestYml cdepManifestYml); @NotNull static List<HardNameDependency> getTransitiveDependencies(@NotNull CDepManifestYml cdepManifestYml); } | @Test public void readPartial() throws IOException { File file = new File("../third_party/stb/cdep/cdep-manifest-divide.yml"); CDepManifestYml partial = CDepManifestYmlUtils.convertStringToManifest(file.getAbsolutePath(), FileUtils.readAllText(file)); } |
CMakeGenerator { @NotNull public String create() { append("# GENERATED FILE. DO NOT EDIT.\n"); append(readCmakeLibraryFunctions()); for (Coordinate coordinate : table.orderOfReferences) { StatementExpression findFunction = table.getFindFunction(coordinate); indent = 0; visit(findFunction); require(indent == 0); } append("\nfunction(add_all_cdep_dependencies target)\n"); for (Coordinate coordinate : table.orderOfReferences) { StatementExpression findFunction = table.getFindFunction(coordinate); FindModuleExpression finder = getFindFunction(findFunction); String function = getAddDependencyFunctionName(finder.coordinate); append(" %s(${target})\n", function); } append("endfunction(add_all_cdep_dependencies)\n"); return sb.toString(); } CMakeGenerator(@NotNull GeneratorEnvironment environment, @NotNull FunctionTableExpression table); void generate(); @NotNull String create(); } | @Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { String capture = CDepManifestYmlUtils.convertManifestToString(any); CDepManifestYml readAny = CDepManifestYmlUtils.convertStringToManifest("fuzz-test.yml", capture); try { Invariant.pushErrorCollectionScope(false); BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(new ResolvedManifest(new URL("https: FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); } finally { Invariant.popErrorCollectionScope(); } } }); }
@Test public void testBoost() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); System.out.printf(result); }
@Test public void testRequires() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.multipleRequires().manifest); FunctionTableExpression table = builder.build(); String result = new CMakeGenerator(environment, table).create(); System.out.printf(result); boolean headerOnly = result.contains("target_compile_features(${target} PUBLIC cxx_auto_type cxx_decltype)"); boolean archive = result.contains("INTERFACE_COMPILE_FEATURES cxx_auto_type cxx_decltype"); assert(headerOnly || archive); }
@Test public void testCurl() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); builder.addManifest(ResolvedManifests.curlAndroid().manifest); FunctionTableExpression table = builder.build(); String script = new CMakeGenerator(environment, table).create(); System.out.printf(script); } |
CxxLanguageStandardRewritingVisitor extends RewritingVisitor { @Override protected Expression visitModuleExpression(@NotNull ModuleExpression expr) { ModuleArchiveExpression archive = expr.archive; CxxLanguageFeatures requires[] = archive.requires; if (requires.length == 0) { return super.visitModuleExpression(expr); } archive = new ModuleArchiveExpression(archive.file, archive.sha256, archive.size, archive.include, archive.includePath, archive.libs, archive.libraryPaths, archive.completionSentinel, new CxxLanguageFeatures[0]); List<ConstantExpression> features = new ArrayList<>(); for (CxxLanguageFeatures require : requires) { features.add(constant(require)); } int minimumLanguageStandard = 0; for (CxxLanguageFeatures require : requires) { minimumLanguageStandard = Math.max( minimumLanguageStandard, require.standard); } List<StatementExpression> exprs = new ArrayList<>(); exprs.add( ifSwitch( supportsCompilerFeatures(), requiresCompilerFeatures(array(features.toArray(new ConstantExpression[requires.length]))), requireMinimumCxxCompilerStandard(constant(minimumLanguageStandard)))); exprs.add(archive); return new MultiStatementExpression(exprs.toArray(new StatementExpression[exprs.size()])); } } | @Test public void testSimple() throws Exception { GlobalBuildEnvironmentExpression globals = new GlobalBuildEnvironmentExpression(); CxxLanguageStandardRewritingVisitor rewriter = new CxxLanguageStandardRewritingVisitor(); rewriter.visit(globals); ModuleArchiveExpression archive = makeArchive(CxxLanguageFeatures.cxx_alignof); ModuleExpression module = new ModuleExpression(archive, new LinkedHashSet<Coordinate>()); Expression result = ((MultiStatementExpression) rewriter.visitModuleExpression(module)).statements[0]; InterpretingVisitor interpreter = new InterpretingVisitor(); Object callvalue = interpreter.visit(result); assertThat(callvalue.getClass()).isEqualTo(CxxLanguageFeatures[].class); }
@Test public void testSimpleStandard17() throws Exception { GlobalBuildEnvironmentExpression globals = new GlobalBuildEnvironmentExpression(); CxxLanguageStandardRewritingVisitor rewriter = new CxxLanguageStandardRewritingVisitor(); rewriter.visit(globals); ModuleArchiveExpression archive = makeArchive(CxxLanguageFeatures.cxx_std_17); ModuleExpression module = new ModuleExpression(archive, new LinkedHashSet<Coordinate>()); Expression result = ((MultiStatementExpression) rewriter.visitModuleExpression(module)).statements[0]; InterpretingVisitor interpreter = new InterpretingVisitor(); Object callvalue = interpreter.visit(result); assertThat(callvalue.getClass()).isEqualTo(CxxLanguageFeatures[].class); } |
NdkBuildGenerator extends AbstractNdkBuildGenerator { public String generate(FunctionTableExpression expr) { expr = (FunctionTableExpression) new JoinedFileToStringRewriter("(", ")").visitFunctionTableExpression(expr); visit(expr); return sb.toString(); } NdkBuildGenerator(@NotNull GeneratorEnvironment environment); String generate(FunctionTableExpression expr); } | @Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { String capture = CDepManifestYmlUtils.convertManifestToString(any); CDepManifestYml readAny = CDepManifestYmlUtils.convertStringToManifest("fuzz-test.yml", capture); try { Invariant.pushErrorCollectionScope(false); BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(new ResolvedManifest(new URL("https: FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); } finally { Invariant.popErrorCollectionScope(); } } }); }
@Test public void testBoost() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testOpenssl() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.openssl().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testOpencv() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.opencv().manifest); FunctionTableExpression table = builder.build(); String script = new NdkBuildGenerator(environment).generate(table); System.out.print(script); }
@Test public void testMultiple() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.boost().manifest); builder.addManifest(ResolvedManifests.sqliteAndroid().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testRequires() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.multipleRequires().manifest); FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); }
@Test public void testCurl() throws Exception { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); builder.addManifest(ResolvedManifests.curlAndroid().manifest); FunctionTableExpression table = builder.build(); String script = new NdkBuildGenerator(environment).generate(table); System.out.printf(script); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("admob", "Reference com.github.jomof:firebase/app:2.1.3-rev8 was not found, " + "needed by com.github.jomof:firebase/admob:2.1.3-rev8"); expected.put("fuzz1", "Could not parse main manifest coordinate []"); boolean unexpectedFailures = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { BuildFindModuleFunctionTable builder = new BuildFindModuleFunctionTable(); if(Objects.equals(manifest.name, "curlAndroid")) { builder.addManifest(ResolvedManifests.zlibAndroid().manifest); builder.addManifest(ResolvedManifests.boringSSLAndroid().manifest); } builder.addManifest(manifest.resolved); String expectedFailure = expected.get(manifest.name); try { FunctionTableExpression table = builder.build(); new NdkBuildGenerator(environment).generate(table); if (expectedFailure != null) { fail("Expected failure"); } } catch (RuntimeException e) { if (expectedFailure == null || !expectedFailure.equals(e.getMessage())) { System.out.printf("expected.put(\"%s\", \"%s\")\n", manifest.name, e.getMessage()); unexpectedFailures = true; } } } if (unexpectedFailures) { throw new RuntimeException("Unexpected failures. See console."); } } |
GithubStyleUrlCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String baseUrl = match.group(1); String segments[] = baseUrl.split("\\."); String groupId = ""; for (int i = 0; i < segments.length; ++i) { groupId += segments[segments.length - i - 1]; groupId += "."; } String user = match.group(2); groupId += user; String artifactId = match.group(3); Version version = new Version(match.group(4)); String subArtifact = match.group(5); if (subArtifact.length() > 0) { require(subArtifact.startsWith("-"), "Url is incorrectly formed at '%s': %s", subArtifact, coordinate); artifactId += "/" + subArtifact.substring(1); } Coordinate provisionalCoordinate = new Coordinate(groupId, artifactId, version); CDepManifestYml cdepManifestYml = environment.tryGetManifest(provisionalCoordinate, new URL(coordinate)); if (cdepManifestYml == null) { return null; } if (errorsInScope() > 0) { return null; } require(groupId.equals(cdepManifestYml.coordinate.groupId), "groupId '%s' from manifest did not agree with github url %s", cdepManifestYml.coordinate.groupId, coordinate); require(artifactId.startsWith(cdepManifestYml.coordinate.artifactId), "artifactId '%s' from manifest did not agree with '%s' from github url %s", artifactId, cdepManifestYml.coordinate.artifactId, coordinate); require(version.equals(cdepManifestYml.coordinate.version), "version '%s' from manifest did not agree with version %s github url %s", cdepManifestYml.coordinate.version, version, coordinate); return new ResolvedManifest(new URL(coordinate), cdepManifestYml); } return null; } @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); } | @Test public void testSimple() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("cmakeify"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("0.0.81"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(8); }
@Test public void testCompound() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(21); }
@Test public void testMissing() throws Exception { ResolvedManifest resolved = new GithubStyleUrlCoordinateResolver().resolve(environment, new SoftNameDependency ("https: assertThat(resolved).isNull(); } |
GithubMultipackageCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String domain = match.group(1); String project = match.group(2); String artifact = match.group(3); String version = match.group(4); String subArtifact = ""; if (artifact.contains("/")) { int pos = artifact.indexOf("/"); subArtifact = "-" + artifact.substring(pos + 1); artifact = artifact.substring(0, pos); } String manifest = String.format("https: domain, project, artifact, version, subArtifact); return urlResolver.resolve(environment, new SoftNameDependency(manifest)); } return null; } GithubMultipackageCoordinateResolver(); @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); } | @Test public void testCompound() throws Exception { final ManifestProvider manifestProvider = new ManifestProvider() { @Override public CDepManifestYml tryGetManifest(Coordinate coordinate, URL remoteArchive) throws IOException, NoSuchAlgorithmException { assertThat(remoteArchive.toString()).isEqualTo( "https: return new CDepManifestYml(coordinate); } }; ResolvedManifest resolved = new GithubMultipackageCoordinateResolver() .resolve( manifestProvider, new SoftNameDependency("com.github.google.cdep:firebase/database:2.1.3-rev5")); assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.google.cdep"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); } |
GithubReleasesCoordinateResolver extends CoordinateResolver { @Nullable @Override public ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency) throws IOException, NoSuchAlgorithmException { String coordinate = dependency.compile; assert coordinate != null; Matcher match = pattern.matcher(coordinate); if (match.find()) { String user = match.group(1); String artifactId = match.group(2); String version = match.group(3); String subArtifact = ""; if (artifactId.contains("/")) { int pos = artifactId.indexOf("/"); subArtifact = "-" + artifactId.substring(pos + 1); artifactId = artifactId.substring(0, pos); } String manifest = String.format("https: user, artifactId, version, subArtifact); return urlResolver.resolve(environment, new SoftNameDependency(manifest)); } return null; } GithubReleasesCoordinateResolver(); GithubReleasesCoordinateResolver(CoordinateResolver urlResolver); @Nullable @Override ResolvedManifest resolve(@NotNull ManifestProvider environment, @NotNull SoftNameDependency dependency); } | @Test public void testCompound() throws Exception { ResolvedManifest resolved = new GithubReleasesCoordinateResolver().resolve(environment, new SoftNameDependency("com.github" + ".jomof:firebase/database:2.1.3-rev5")); assert resolved != null; assert resolved.cdepManifestYml.coordinate != null; assertThat(resolved.cdepManifestYml.coordinate.groupId).isEqualTo("com.github.jomof"); assertThat(resolved.cdepManifestYml.coordinate.artifactId).isEqualTo("firebase/database"); assertThat(resolved.cdepManifestYml.coordinate.version.value).isEqualTo("2.1.3-rev5"); assert resolved.cdepManifestYml.android != null; assert resolved.cdepManifestYml.android.archives != null; assertThat(resolved.cdepManifestYml.android.archives.length).isEqualTo(21); } |
Fullfill { @NotNull public static List<File> multiple( GeneratorEnvironment environment, @NotNull File templates[], File outputFolder, @NotNull File sourceFolder, String version) throws IOException, NoSuchAlgorithmException { List<File> result = new ArrayList<>(); CDepManifestYml manifests[] = new CDepManifestYml[templates.length]; File layout = new File(outputFolder, "layout"); if (!layout.isDirectory()) { layout.mkdirs(); } File staging = new File(outputFolder, "staging"); if (!staging.isDirectory()) { staging.mkdirs(); } for (int i = 0; i < manifests.length; ++i) { String body = FileUtils.readAllText(templates[i]); manifests[i] = CDepManifestYmlUtils.convertStringToManifest(templates[i].getAbsolutePath(), body); } SubstituteStringsRewriter substitutor = new SubstituteStringsRewriter() .replace("${source}", sourceFolder.getAbsolutePath()) .replace("${layout}", layout.getAbsolutePath()) .replace("${version}", version); for (int i = 0; i < manifests.length; ++i) { manifests[i] = substitutor.visitCDepManifestYml(manifests[i]); } Resolver resolver = new Resolver(environment); ResolutionScope scope = new ResolutionScope(); infoln("Fullfilling %s manifests", templates.length); for (int i = 0; i < manifests.length; ++i) { Coordinate coordinate = manifests[i].coordinate; FillMissingFieldsBasedOnFilepathRewriter filler = new FillMissingFieldsBasedOnFilepathRewriter(); infoln(" guessing archive details from path names in %s", coordinate); manifests[i] = filler.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } ZipFilesRewriter zipper = new ZipFilesRewriter(layout, staging); infoln(" zipping files referenced in %s", coordinate); manifests[i] = zipper.visitCDepManifestYml(manifests[i]); result.addAll(zipper.getZips()); if (errorsInScope() > 0) { return result; } FileHashAndSizeRewriter hasher = new FileHashAndSizeRewriter(layout); infoln(" computing hashes and file sizes of archives in %s", coordinate); manifests[i] = hasher.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } DependencyHashRewriter dependencyHasher = new DependencyHashRewriter(environment); infoln(" hashing dependencies in %s", coordinate); manifests[i] = dependencyHasher.visitCDepManifestYml(manifests[i]); if (errorsInScope() > 0) { return result; } File output = new File(layout, templates[i].getName()); infoln(" writing manifest file %s", new File(".") .toURI().relativize(output.toURI()).getPath()); String body = CDepManifestYmlUtils.convertManifestToString(manifests[i]); FileUtils.writeTextToFile(output, body); result.add(output); if (errorsInScope() > 0) { return result; } infoln(" checking sanity of result %s", coordinate); CDepManifestYml readFromDisk = CDepManifestYmlUtils.convertStringToManifest(output.getAbsolutePath(), FileUtils.readAllText(output)); CDepManifestYmlEquality.areDeeplyIdentical(manifests[i], readFromDisk); if (errorsInScope() > 0) { return result; } CDepManifestYmlUtils.checkManifestSanity(manifests[i]); SoftNameDependency softname = new SoftNameDependency(coordinate.toString()); scope.addUnresolved(softname); scope.recordResolved( softname, new ResolvedManifest(output.toURI().toURL(), manifests[i]), CDepManifestYmlUtils.getTransitiveDependencies(manifests[i])); if (errorsInScope() > 0) { return result; } } infoln(" checking consistency of all manifests"); resolver.resolveAll(scope); BuildFindModuleFunctionTable table = new BuildFindModuleFunctionTable(); GeneratorEnvironmentUtils.addAllResolvedToTable(table, scope); table.build(); if (errorsInScope() > 0) { return result; } return result; } @NotNull static List<File> multiple(
GeneratorEnvironment environment,
@NotNull File templates[],
File outputFolder,
@NotNull File sourceFolder,
String version); } | @Test public void testBasicSTB() throws Exception { File templates[] = templates( new File("../third_party/stb/cdep/")); File output = new File(".test-files/testBasicSTB").getAbsoluteFile(); Fullfill.multiple(environment, templates, output, new File("../third_party/stb"), "1.2.3"); }
@Test public void testBasicTinyDir() throws Exception { File templates[] = templates( new File("../third_party/tinydir/")); File output = new File(".test-files/testBasicTinyDir").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/tinydir"), "1.2.3"); assertThat(result).hasSize(2); }
@Test public void testBasicVectorial() throws Exception { File templates[] = templates( new File("../third_party/vectorial/cdep")); File output = new File(".test-files/testBasicVectorial").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/vectorial"), "1.2.3"); assertThat(result).hasSize(2); }
@Test public void testBasicMathFu() throws Exception { File templates[] = templates( new File("../third_party/mathfu/cdep")); File output = new File(".test-files/testBasicMathFu").getAbsoluteFile(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/mathfu"), "1.2.3"); assertThat(result).hasSize(2); File manifestFile = new File(output, "layout"); manifestFile = new File(manifestFile, "cdep-manifest.yml"); CDepManifestYml manifest = CDepManifestYmlUtils.convertStringToManifest(manifestFile.getAbsolutePath(), FileUtils.readAllText(manifestFile)); assertThat(manifest.dependencies[0].sha256).isNotNull(); assertThat(manifest.dependencies[0].sha256).isNotEmpty(); }
@Test public void testMiniFirebase() throws Exception { File templates[] = new File[]{ new File("../third_party/mini-firebase/cdep-manifest-app.yml"), new File("../third_party/mini-firebase/cdep-manifest-database.yml") }; File output = new File(".test-files/testMiniFirebase").getAbsoluteFile(); output.delete(); List<File> result = Fullfill.multiple(environment, templates, output, new File("../third_party/mini-firebase/firebase_cpp_sdk"), "1.2.3"); File manifestFile = new File(output, "layout"); manifestFile = new File(manifestFile, "cdep-manifest-database.yml"); CDepManifestYml manifest = CDepManifestYmlUtils.convertStringToManifest(manifestFile.getAbsolutePath(), FileUtils.readAllText(manifestFile)); assertThat(manifest.dependencies[0].sha256).isNotNull(); assertThat(manifest.dependencies[0].sha256).isNotEmpty(); if(manifest.android != null) assertThat(manifest.android.archives[0].file.contains("+")).isFalse(); }
@Test public void testSqlite() throws Exception { ResolvedManifests.TestManifest manifest = ResolvedManifests.sqlite(); File outputFolder = new File(".test-files/TestFullfill/testSqlite").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); }
@Test public void testRe2() throws Exception { ResolvedManifests.TestManifest manifest = ResolvedManifests.sqlite(); File outputFolder = new File(".test-files/TestFullfill/re2").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); List<File> results = Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); CDepManifestYml result = CDepManifestYmlUtils.convertStringToManifest(results.get(0).getAbsolutePath(), FileUtils.readAllText(results.get(0))); assertThat(result).hasCoordinate(new Coordinate("com.github.jomof", "sqlite", new Version("0.0.0"))); assertThat(result).hasArchiveNamed("sqlite-android-gnustl-platform-21.zip"); }
@Test public void testAllResolvedManifests() throws Exception { Map<String, String> expected = new LinkedHashMap<>(); expected.put("sqliteLinuxMultiple", "Package 'com.github.jomof:sqlite:0.0.0' has multiple linux archives. Only one is allowed."); expected.put("archiveMissingSize", "Archive com.github.jomof:vectorial:0.0.0 is missing size or it is zero"); expected.put("indistinguishableAndroidArchives", "Android archive com.github.jomof:firebase/app:0.0.0 file archive2.zip is indistinguishable at build time from " + "archive1.zip given the information in the manifest"); expected.put("archiveMissingSha256", "Could not hash file bob.zip because it didn't exist"); expected.put("archiveMissingFile", "Package 'com.github.jomof:vectorial:0.0.0' does not contain any files"); expected.put("admob", "Archive com.github.jomof:firebase/admob:2.1.3-rev8 is missing include"); expected.put("fuzz1", "Dependency had no compile field"); boolean unexpectedFailure = false; for (ResolvedManifests.NamedManifest manifest : ResolvedManifests.all()) { File outputFolder = new File(".test-files/TestFullfill/testAllResolvedManifests/" + manifest.name).getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); String key = manifest.name; String expectedFailure = expected.get(key); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); FileUtils.writeTextToFile(manifestFile, manifest.body); try { Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); if (expectedFailure != null) { require(false, "Expected failure in %s: '%s'", manifest.name, expectedFailure); } } catch (CDepRuntimeException e) { if (e.getMessage() == null) { throw e; } if (e.getMessage().contains("Could not zip file")) { continue; } if (!e.getMessage().equals(expectedFailure)) { System.out.printf("expected.put(\"%s\", \"%s\");\n", key, e.getMessage()); unexpectedFailure = true; } } } if (unexpectedFailure) { throw new RuntimeException("Unexpected failures. See console."); } }
@Test public void fuzzTest() { QuickCheck.forAll(new CDepManifestYmlGenerator(), new AbstractCharacteristic<CDepManifestYml>() { @Override protected void doSpecify(CDepManifestYml any) throws Throwable { File outputFolder = new File(".test-files/TestFullfill/fuzzTest/" + "fuzzTest").getAbsoluteFile(); outputFolder.delete(); outputFolder.mkdirs(); File manifestFile = new File(outputFolder, "cdep-manifest.yml"); String body = CDepManifestYmlUtils.convertManifestToString(any); FileUtils.writeTextToFile(manifestFile, body); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream originalOut = null; PrintStream originalErr = null; try { Invariant.pushErrorCollectionScope(true); originalOut = IO.setOut(ps); originalErr = IO.setErr(ps); Fullfill.multiple( environment, new File[]{manifestFile}, new File(outputFolder, "output"), new File(outputFolder, "source"), "1.2.3"); } catch(Throwable e) { System.out.print(body); throw e; } finally { IO.setOut(originalOut); IO.setErr(originalErr); Invariant.popErrorCollectionScope(); } } }); } |
AllocateConnAndTaskStrategyByConsistentHash implements AllocateConnAndTaskStrategy { @Override public ConnAndTaskConfigs allocate(List<String> allWorker, String curWorker, Map<String, ConnectKeyValue> connectorConfigs, Map<String, List<ConnectKeyValue>> taskConfigs) { ConnAndTaskConfigs allocateResult = new ConnAndTaskConfigs(); if (null == allWorker || 0 == allWorker.size()) { return allocateResult; } Collection<ClientNode> cidNodes = allWorker.stream().map(ClientNode::new).collect(Collectors.toList()); ConsistentHashRouter router = getRouter(cidNodes); connectorConfigs.entrySet().stream().filter(task -> curWorker.equals(router.routeNode(task.getKey()).getKey())) .forEach(task -> allocateResult.getConnectorConfigs().put(task.getKey(), task.getValue())); for (Map.Entry<String, List<ConnectKeyValue>> connector : taskConfigs.entrySet()) { connector.getValue().stream().filter(kv -> curWorker.equals(router.routeNode(kv.toString()).getKey())) .forEach(allocateResult.getTaskConfigs().computeIfAbsent(connector.getKey(), k -> new ArrayList<>())::add); } log.debug("allocate result: " + allocateResult); return allocateResult; } AllocateConnAndTaskStrategyByConsistentHash(); @Override ConnAndTaskConfigs allocate(List<String> allWorker, String curWorker,
Map<String, ConnectKeyValue> connectorConfigs, Map<String, List<ConnectKeyValue>> taskConfigs); } | @Test public void testAllocate() { AllocateConnAndTaskStrategyByConsistentHash strategy = new AllocateConnAndTaskStrategyByConsistentHash(); List<String> allWorker = new ArrayList<String>() { { add("workId1"); add("workId2"); add("workId3"); } }; Map<String, ConnectKeyValue> connectorConfigs = new HashMap<String, ConnectKeyValue>() { { put("connectorConfig1", new ConnectKeyValue()); put("connectorConfig2", new ConnectKeyValue()); put("connectorConfig3", new ConnectKeyValue()); } }; List<ConnectKeyValue> connectKVs = new ArrayList<>(); for (int i = 0; i < 6; i++) { ConnectKeyValue kv = new ConnectKeyValue(); kv.put("index", i); connectKVs.add(kv); } List<ConnectKeyValue> taskConfig1 = new ArrayList<ConnectKeyValue>() { { add(connectKVs.get(0)); } }; List<ConnectKeyValue> taskConfig2 = new ArrayList<ConnectKeyValue>() { { add(connectKVs.get(1)); add(connectKVs.get(2)); } }; List<ConnectKeyValue> taskConfig3 = new ArrayList<ConnectKeyValue>() { { add(connectKVs.get(3)); add(connectKVs.get(4)); add(connectKVs.get(5)); } }; Map<String, List<ConnectKeyValue>> taskConfigs = new HashMap<String, List<ConnectKeyValue>>() { { put("connectorConfig1", taskConfig1); put("connectorConfig2", taskConfig2); put("connectorConfig3", taskConfig3); } }; Set<String> connectorChecks = new HashSet<>(); Map<String, List<ConnectKeyValue>> taskChecks = new HashMap<>(); taskConfigs.keySet().stream().forEach(key -> { taskChecks.put(key, new ArrayList<>()); }); for (String worker : allWorker) { ConnAndTaskConfigs allocate = strategy.allocate(allWorker, worker, connectorConfigs, taskConfigs); assertNotNull(allocate); allocate.getConnectorConfigs().keySet().forEach(key -> { assertFalse(connectorChecks.contains(key)); connectorChecks.add(key); }); allocate.getTaskConfigs().forEach((connectorName, allocatedTasks) -> { List<ConnectKeyValue> checkKVs = taskChecks.computeIfAbsent(connectorName, k -> new ArrayList<>()); allocatedTasks.forEach(task -> { assertFalse(checkKVs.contains(task)); checkKVs.add(task); }); }); } assertEquals(connectorConfigs.size(), connectorChecks.size()); long cnt = taskChecks.entrySet().stream().flatMap(entry -> entry.getValue().stream()).count(); assertEquals(6, cnt); } |
KafkaSourceConnector extends SourceConnector { @Override public Class<? extends Task> taskClass() { return KafkaSourceTask.class; } KafkaSourceConnector(); @Override String verifyAndSetConfig(KeyValue config); @Override void start(); @Override void stop(); @Override void pause(); @Override void resume(); @Override Class<? extends Task> taskClass(); @Override List<KeyValue> taskConfigs(); } | @Test public void taskClassTest() { assertEquals(connector.taskClass(), KafkaSourceTask.class); } |
KafkaSourceConnector extends SourceConnector { @Override public List<KeyValue> taskConfigs() { if (connectConfig == null) { return new ArrayList<KeyValue>(); } log.info("Source Connector taskConfigs enter"); List<KeyValue> configs = new ArrayList<>(); int task_num = connectConfig.getInt(ConfigDefine.TASK_NUM); log.info("Source Connector taskConfigs: task_num:" + task_num); for (int i = 0; i < task_num; ++i) { KeyValue config = new DefaultKeyValue(); config.put(ConfigDefine.BOOTSTRAP_SERVER, connectConfig.getString(ConfigDefine.BOOTSTRAP_SERVER)); config.put(ConfigDefine.TOPICS, connectConfig.getString(ConfigDefine.TOPICS)); config.put(ConfigDefine.GROUP_ID, connectConfig.getString(ConfigDefine.GROUP_ID)); config.put(ConfigDefine.CONNECTOR_CLASS, connectConfig.getString(ConfigDefine.CONNECTOR_CLASS)); config.put(ConfigDefine.SOURCE_RECORD_CONVERTER, connectConfig.getString(ConfigDefine.SOURCE_RECORD_CONVERTER)); configs.add(config); } return configs; } KafkaSourceConnector(); @Override String verifyAndSetConfig(KeyValue config); @Override void start(); @Override void stop(); @Override void pause(); @Override void resume(); @Override Class<? extends Task> taskClass(); @Override List<KeyValue> taskConfigs(); } | @Test public void taskConfigsTest() { assertEquals(connector.taskConfigs().size(), 0); KeyValue keyValue = new DefaultKeyValue(); for (String requestKey : ConfigDefine.REQUEST_CONFIG) { keyValue.put(requestKey, requestKey); } keyValue.put(ConfigDefine.TASK_NUM,1); connector.verifyAndSetConfig(keyValue); assertEquals(connector.taskConfigs().get(0).getString(ConfigDefine.TOPICS), keyValue.getString(ConfigDefine.TOPICS)); } |
ActivemqSourceTask extends SourceTask { @Override public Collection<SourceDataEntry> poll() { List<SourceDataEntry> res = new ArrayList<>(); try { Message message = replicator.getQueue().poll(1000, TimeUnit.MILLISECONDS); if (message != null) { Object[] payload = new Object[] {config.getDestinationType(), config.getDestinationName(), getMessageContent(message)}; SourceDataEntry sourceDataEntry = new SourceDataEntry(sourcePartition, null, System.currentTimeMillis(), EntryType.CREATE, null, null, payload); res.add(sourceDataEntry); } } catch (Exception e) { log.error("activemq task poll error, current config:" + JSON.toJSONString(config), e); } return res; } @Override Collection<SourceDataEntry> poll(); @Override void start(KeyValue props); @Override void stop(); @Override void pause(); @Override void resume(); @SuppressWarnings("unchecked") ByteBuffer getMessageContent(Message message); } | @Test public void pollTest() throws Exception { ActivemqSourceTask task = new ActivemqSourceTask(); TextMessage textMessage = new ActiveMQTextMessage(); textMessage.setText("hello rocketmq"); Replicator replicatorObject = Mockito.mock(Replicator.class); BlockingQueue<Message> queue = new LinkedBlockingQueue<>(); Mockito.when(replicatorObject.getQueue()).thenReturn(queue); Field replicator = ActivemqSourceTask.class.getDeclaredField("replicator"); replicator.setAccessible(true); replicator.set(task, replicatorObject); Field config = ActivemqSourceTask.class.getDeclaredField("config"); config.setAccessible(true); config.set(task, new Config()); queue.put(textMessage); Collection<SourceDataEntry> list = task.poll(); Assert.assertEquals(list.size(), 1); list = task.poll(); Assert.assertEquals(list.size(), 0); } |
Replicator { public void start() throws Exception { processor = new PatternProcessor(this); processor.start(); LOGGER.info("Replicator start succeed"); } Replicator(Config config); void start(); void stop(); void commit(Message message, boolean isComplete); Config getConfig(); BlockingQueue<Message> getQueue(); } | @Test(expected = RuntimeException.class) public void startTest() throws Exception { replicator.start(); } |
Replicator { public void stop() throws Exception { processor.stop(); } Replicator(Config config); void start(); void stop(); void commit(Message message, boolean isComplete); Config getConfig(); BlockingQueue<Message> getQueue(); } | @Test public void stop() throws Exception { replicator.stop(); Mockito.verify(patternProcessor, Mockito.times(1)).stop(); } |
Replicator { public Config getConfig() { return this.config; } Replicator(Config config); void start(); void stop(); void commit(Message message, boolean isComplete); Config getConfig(); BlockingQueue<Message> getQueue(); } | @Test public void getConfigTest() { Assert.assertEquals(replicator.getConfig(), config); } |
RabbitMQPatternProcessor extends PatternProcessor { public ConnectionFactory connectionFactory() { RMQConnectionFactory connectionFactory = new RMQConnectionFactory(); try { List<String> urlList = new ArrayList<>(); urlList.add(config.getBrokerUrl()); connectionFactory.setUris(urlList); } catch (JMSException e) { throw new DataConnectException(ErrorCode.START_ERROR_CODE, e.getMessage(), e); } return connectionFactory; } RabbitMQPatternProcessor(Replicator replicator); ConnectionFactory connectionFactory(); } | @Test public void connectionFactory() { RabbitmqConfig rabbitmqConfig = new RabbitmqConfig(); rabbitmqConfig.setRabbitmqUrl("amqp: Replicator replicator = new Replicator(rabbitmqConfig, null); RabbitMQPatternProcessor patternProcessor = new RabbitMQPatternProcessor(replicator); assertEquals(RMQConnectionFactory.class, patternProcessor.connectionFactory().getClass()); } |
RabbitmqSourceTask extends BaseJmsSourceTask { @Override public Config getConfig() { return new RabbitmqConfig(); } PatternProcessor getPatternProcessor(Replicator replicator); @Override Config getConfig(); } | @Test public void getConfig() { RabbitmqSourceTask task = new RabbitmqSourceTask(); assertEquals(task.getConfig().getClass() , RabbitmqConfig.class); } |
RabbitmqSourceConnector extends BaseJmsSourceConnector { @Override public Class<? extends Task> taskClass() { return RabbitmqSourceTask.class; } @Override Class<? extends Task> taskClass(); Set<String> getRequiredConfig(); } | @Test public void taskClass() { assertEquals( RabbitmqSourceTask.class, rabbitmqSourceConnector.taskClass()); } |
RabbitmqSourceConnector extends BaseJmsSourceConnector { public Set<String> getRequiredConfig() { return RabbitmqConfig.REQUEST_CONFIG; } @Override Class<? extends Task> taskClass(); Set<String> getRequiredConfig(); } | @Test public void getRequiredConfig() { assertEquals( RabbitmqConfig.REQUEST_CONFIG , rabbitmqSourceConnector.getRequiredConfig()); } |
FileAndPropertyUtil { public static void string2FileNotSafe(final String str, final String fileName) throws IOException { File file = new File(fileName); File fileParent = file.getParentFile(); if (fileParent != null) { fileParent.mkdirs(); } FileWriter fileWriter = null; try { fileWriter = new FileWriter(file); fileWriter.write(str); } catch (IOException e) { throw e; } finally { if (fileWriter != null) { fileWriter.close(); } } } static void string2File(final String str, final String fileName); static void string2FileNotSafe(final String str, final String fileName); static String file2String(final String fileName); static String file2String(final File file); static void properties2Object(final Properties p, final Object object); } | @Test public void testString2FileNotSafe() throws Exception { FileAndPropertyUtil.string2FileNotSafe(str, filePath); String s = FileAndPropertyUtil.file2String(filePath); assertEquals(str, s); } |
FileAndPropertyUtil { public static void properties2Object(final Properties p, final Object object) { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { String mn = method.getName(); if (mn.startsWith("set")) { try { String tmp = mn.substring(4); String first = mn.substring(3, 4); String key = first.toLowerCase() + tmp; String property = p.getProperty(key); if (property != null) { Class<?>[] pt = method.getParameterTypes(); if (pt != null && pt.length > 0) { String cn = pt[0].getSimpleName(); Object arg = null; if (cn.equals("int") || cn.equals("Integer")) { arg = Integer.parseInt(property); } else if (cn.equals("long") || cn.equals("Long")) { arg = Long.parseLong(property); } else if (cn.equals("double") || cn.equals("Double")) { arg = Double.parseDouble(property); } else if (cn.equals("boolean") || cn.equals("Boolean")) { arg = Boolean.parseBoolean(property); } else if (cn.equals("float") || cn.equals("Float")) { arg = Float.parseFloat(property); } else if (cn.equals("String")) { arg = property; } else { continue; } method.invoke(object, arg); } } } catch (Throwable ignored) { } } } } static void string2File(final String str, final String fileName); static void string2FileNotSafe(final String str, final String fileName); static String file2String(final String fileName); static String file2String(final File file); static void properties2Object(final Properties p, final Object object); } | @Test public void testProperties2Object() { Properties properties = new Properties(); properties.setProperty("key1", "1"); properties.setProperty("key2", "2000"); properties.setProperty("key3", "3.0"); properties.setProperty("key4", "4"); class TestObject { private String key1; private String key2; private String key3; private String key4; public String getKey1() { return key1; } public void setKey1(String key1) { this.key1 = key1; } public String getKey2() { return key2; } public void setKey2(String key2) { this.key2 = key2; } public String getKey3() { return key3; } public void setKey3(String key3) { this.key3 = key3; } public String getKey4() { return key4; } public void setKey4(String key4) { this.key4 = key4; } } TestObject testObject = new TestObject(); FileAndPropertyUtil.properties2Object(properties, testObject); assertEquals("1", testObject.getKey1()); assertEquals("2000", testObject.getKey2()); assertEquals("3.0", testObject.getKey3()); assertEquals("4", testObject.getKey4()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.