@Test public void testExecute() throws Exception { RosetteApiWrapper rosAPI = new RosetteApiWrapper("apiKey"); String tag = "testTag"; String description = "testDescription"; String processorType = "testProcessorType"; String inputField = "testInputField"; String targetField = "testTargetField"; RosetteAbstractProcessor processor = new RosetteAbstractProcessor(rosAPI, tag, description, processorType, inputField, targetField); IngestDocument ingestDocument = new IngestDocument("testId", "testType"); ingestDocument.setFieldValue(inputField, "This is a test input text."); IngestDocument result = processor.execute(ingestDocument); assertNotNull(result); assertFalse(result.hasField(targetField)); assertEquals("This is a test input text.", result.getFieldValue(inputField, String.class)); }
@Test public void testFormatToUserFriendlyFormat() { Date date = new Date(); String expected = DateFormat.getDateInstance(DateFormat.FULL).format(date); String actual = DateHelper.formatToUserFriendlyFormat(date); assertEquals(expected, actual); }
@Test public void testHasDescription() { UiLesson uiLesson = new UiLesson(); uiLesson.setDescription("This is a lesson description."); assertTrue(uiLesson.hasDescription()); }
@Test public void testNormalize() { NormContinuous normContinuous = new NormContinuous(0, 100); FieldValue value = FieldValueUtil.create(50); FieldValue normalizedValue = NormalizationUtil.normalize(normContinuous, value); double expectedValue = 0.5; double delta = 0.0001; assertEquals(expectedValue, normalizedValue.asNumber().doubleValue(), delta); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testGetResultDataType() { DataType left = DataType.INTEGER; DataType right = DataType.DOUBLE; DataType expected = DataType.NUMERIC; assertEquals(expected, TypeUtil.getResultDataType(left, right)); }
@Test public void testDenormalize() { NormContinuous normContinuous = new NormContinuous(); List<LinearNorm> linearNorms = new ArrayList<>(); linearNorms.add(new LinearNorm(0, 0)); linearNorms.add(new LinearNorm(1, 1)); normContinuous.setLinearNorms(linearNorms); double value = 0.5; double expected = 0.5; double result = NormalizationUtil.denormalize(normContinuous, value); assertEquals(expected, result, 0.0001); }
@Test public void testMatch() { Table<Integer, String, String> table = HashBasedTable.create(); table.put(1, "name", "John"); table.put(1, "age", "30"); table.put(2, "name", "Jane"); table.put(2, "age", "25"); Map<String, FieldValue> values = new HashMap<>(); values.put("name", new FieldValue("John")); values.put("age", new FieldValue("30")); Map<String, String> expected = table.row(1); Map<String, String> actual = InlineTableUtil.match(table, values); assertEquals(expected, actual); }
@Test public void testIsZero() { assertTrue(VerificationUtil.isZero(0, 0.0001)); assertTrue(VerificationUtil.isZero(0.0, 0.0001)); assertTrue(VerificationUtil.isZero(0.00009, 0.0001)); assertFalse(VerificationUtil.isZero(0.00011, 0.0001)); assertFalse(VerificationUtil.isZero(1, 0.0001)); assertFalse(VerificationUtil.isZero(-1, 0.0001)); }
@Test public void testEvaluateConstant() { Constant constant = new Constant("test", DataType.STRING); EvaluationContext context = new EvaluationContext(); FieldValue result = ExpressionUtil.evaluateConstant(constant, context); assertEquals(DataType.STRING, result.getDataType()); assertEquals("test", result.getValue()); }
@Test public void testUnmarshal() { FieldName name1 = new FieldName("test"); FieldName name2 = FieldName.unmarshal("test"); assertEquals(name1, name2); }
@Test public void testEvaluateSimilarity() { ComparisonMeasure comparisonMeasure = new ComparisonMeasure(new SimpleMatching()); List<ComparisonField> comparisonFields = new ArrayList<>(); comparisonFields.add(new ComparisonField("field1")); comparisonFields.add(new ComparisonField("field2")); comparisonFields.add(new ComparisonField("field3")); BitSet flags = new BitSet(); flags.set(0); flags.set(2); BitSet referenceFlags = new BitSet(); referenceFlags.set(0); referenceFlags.set(1); Double result = MeasureUtil.evaluateSimilarity(comparisonMeasure, comparisonFields, flags, referenceFlags); assertEquals(0.5, result, 0.001); }
@Test public void testParse() { assertEquals("hello", TypeUtil.parse(DataType.STRING, "hello")); assertEquals(123, TypeUtil.parse(DataType.INTEGER, "123")); assertEquals(3.14f, TypeUtil.parse(DataType.FLOAT, "3.14"), 0.001); assertEquals(2.71828, TypeUtil.parse(DataType.DOUBLE, "2.71828"), 0.00001); assertTrue((boolean) TypeUtil.parse(DataType.BOOLEAN, "true")); assertFalse((boolean) TypeUtil.parse(DataType.BOOLEAN, "false")); assertEquals(LocalDate.of(2021, 10, 31), TypeUtil.parse(DataType.DATE, "2021-10-31")); assertEquals(LocalTime.of(12, 30, 45), TypeUtil.parse(DataType.TIME, "12:30:45")); assertEquals(LocalDateTime.of(2021, 10, 31, 12, 30, 45), TypeUtil.parse(DataType.DATE_TIME, "2021-10-31T12:30:45")); assertEquals(new DaysSinceDate(TypeUtil.YEAR_1960, LocalDate.of(2021, 10, 31)), TypeUtil.parse(DataType.DATE_DAYS_SINCE_1960, "18923")); assertEquals(new DaysSinceDate(TypeUtil.YEAR_1970, LocalDate.of(2021, 10, 31)), TypeUtil.parse(DataType.DATE_DAYS_SINCE_1970, "18923")); assertEquals(new DaysSinceDate(TypeUtil.YEAR_1980, LocalDate.of(2021, 10, 31)), TypeUtil.parse(DataType.DATE_DAYS_SINCE_1980, "18923")); assertEquals(new SecondsSinceMidnight(45045), TypeUtil.parse(DataType.TIME_SECONDS, "12:30:45")); assertEquals(new SecondsSinceDate(TypeUtil.YEAR_1960, LocalDateTime.of(2021, 10, 31, 12, 30, 45)), TypeUtil.parse(DataType.DATE_TIME_SECONDS_SINCE_1960, "1646145045")); assertEquals(new SecondsSinceDate(TypeUtil.YEAR_1970, LocalDateTime.of(2021, 10, 31, 12, 30, 45)), TypeUtil.parse(DataType.DATE_TIME_SECONDS_SINCE_1970, "1635694245")); assertEquals(new SecondsSinceDate(TypeUtil.YEAR_1980, LocalDateTime.of(2021, 10, 31, 12, 30, 45)), TypeUtil.parse(DataType.DATE_TIME_SECONDS_SINCE_1980, "1577667045")); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil functionUtil = new FunctionUtil(); FieldValue result = functionUtil.evaluate(apply, values, context); assertNotNull(result); }
@Test public void testBinaryXor() { assertTrue(PredicateUtil.binaryXor(true, false)); assertTrue(PredicateUtil.binaryXor(false, true)); assertFalse(PredicateUtil.binaryXor(true, true)); assertFalse(PredicateUtil.binaryXor(false, false)); assertNull(PredicateUtil.binaryXor(true, null)); assertNull(PredicateUtil.binaryXor(null, false)); assertNull(PredicateUtil.binaryXor(null, null)); }
@Test public void testDecode() { Object obj = new Object(); Object result = EvaluatorUtil.decode(obj); assertEquals(obj, result); Computable computable = new Computable() { @Override public Object getResult() { return "result"; } }; Object decoded = EvaluatorUtil.decode(computable); assertEquals("result", decoded); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil functionUtil = new FunctionUtil(); FieldValue result = functionUtil.evaluate(apply, values, context); assertNotNull(result); }
@Test public void testMatch() { Table<Integer, String, String> table = HashBasedTable.create(); table.put(1, "name", "John"); table.put(1, "age", "30"); table.put(2, "name", "Jane"); table.put(2, "age", "25"); Map<String, FieldValue> values = new HashMap<>(); values.put("name", new FieldValue("John")); values.put("age", new FieldValue("30")); Map<String, String> expected = table.row(1); Map<String, String> actual = InlineTableUtil.match(table, values); assertEquals(expected, actual); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testEvaluateMapValues() { MapValues mapValues = new MapValues(DataType.STRING, "missing"); mapValues.addFieldColumnPair(new FieldColumnPair("field1", "column1")); mapValues.addFieldColumnPair(new FieldColumnPair("field2", "column2")); EvaluationContext context = new EvaluationContext(); context.setFieldValue("field1", new FieldValue("value1")); context.setFieldValue("field2", new FieldValue("value2")); FieldValue result = ExpressionUtil.evaluateMapValues(mapValues, context); Map<String, FieldValue> expectedValues = new LinkedHashMap<>(); expectedValues.put("column1", new FieldValue("value1")); expectedValues.put("column2", new FieldValue("value2")); FieldValue expected = DiscretizationUtil.mapValue(mapValues, expectedValues); assertEquals(expected, result); }
@Test public void testEvaluateNormContinuous() { NormContinuous normContinuous = new NormContinuous(); normContinuous.setField("field"); normContinuous.setMapMissingTo(0.0); EvaluationContext context = new EvaluationContext(); context.setFieldValue("field", FieldValueUtil.create(10.0)); FieldValue result = ExpressionUtil.evaluateNormContinuous(normContinuous, context); assertEquals(1.0, result.asDouble(), 0.001); }
@Test public void testNormalize() { NormContinuous normContinuous = new NormContinuous(0, 100); FieldValue value = FieldValueUtil.create(50); FieldValue normalizedValue = NormalizationUtil.normalize(normContinuous, value); double expectedValue = 0.5; double delta = 0.0001; assertEquals(expectedValue, normalizedValue.asNumber().doubleValue(), delta); }
@Test public void testCast() { Object value = "123"; assertEquals("123", TypeUtil.cast(DataType.STRING, value)); value = 123; assertEquals(123, TypeUtil.cast(DataType.INTEGER, value)); value = 1.23f; assertEquals(1.23f, TypeUtil.cast(DataType.FLOAT, value)); value = 1.23; assertEquals(1.23, TypeUtil.cast(DataType.DOUBLE, value)); value = true; assertEquals(true, TypeUtil.cast(DataType.BOOLEAN, value)); value = "2021-10-01"; assertEquals(LocalDate.parse("2021-10-01"), TypeUtil.cast(DataType.DATE, value)); value = "10:30:00"; assertEquals(LocalTime.parse("10:30:00"), TypeUtil.cast(DataType.TIME, value)); value = "2021-10-01T10:30:00"; assertEquals(LocalDateTime.parse("2021-10-01T10:30:00"), TypeUtil.cast(DataType.DATE_TIME, value)); value = 1; assertEquals(LocalDate.of(1960, 1, 2), TypeUtil.cast(DataType.DATE_DAYS_SINCE_1960, value)); value = 86401; assertEquals(LocalTime.of(0, 0, 1), TypeUtil.cast(DataType.TIME_SECONDS, value)); value = 315532800; assertEquals(LocalDate.of(1980, 1, 1), TypeUtil.cast(DataType.DATE_DAYS_SINCE_1980, value)); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testBinaryOr() { assertTrue(PredicateUtil.binaryOr(true, true)); assertTrue(PredicateUtil.binaryOr(true, false)); assertTrue(PredicateUtil.binaryOr(false, true)); assertFalse(PredicateUtil.binaryOr(false, false)); assertNull(PredicateUtil.binaryOr(null, true)); assertNull(PredicateUtil.binaryOr(true, null)); assertNull(PredicateUtil.binaryOr(null, null)); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil functionUtil = new FunctionUtil(); FieldValue result = functionUtil.evaluate(apply, values, context); assertNotNull(result); }
@Test public void testEvaluateNormDiscrete() { NormDiscrete normDiscrete = new NormDiscrete("field", "value", 1.0); EvaluationContext context = new EvaluationContext(); context.setFieldValue("field", FieldValueUtil.create("value")); FieldValue result = ExpressionUtil.evaluateNormDiscrete(normDiscrete, context); assertEquals(1.0, result.getValue()); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testGetValue() { SparseArray<Integer> sparseArray = new IntSparseArray(); sparseArray.put(0, 10); sparseArray.put(2, 20); sparseArray.put(4, 30); Integer value = SparseArrayUtil.getValue(sparseArray, 2); assertEquals(Integer.valueOf(20), value); }
@Test public void testMarshal() { FieldName fieldName = new FieldName("test"); String marshalledFieldName = FieldName.marshal(fieldName); assertNotNull(marshalledFieldName); assertEquals("test", marshalledFieldName); FieldName nullFieldName = null; String marshalledNullFieldName = FieldName.marshal(nullFieldName); assertNull(marshalledNullFieldName); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil functionUtil = new FunctionUtil(); FieldValue result = functionUtil.evaluate(apply, values, context); assertNotNull(result); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testPrepare() { DataField dataField = new DataField("testField", DataType.DOUBLE); MiningField miningField = new MiningField("testMiningField"); miningField.setOutlierTreatment(OutlierTreatmentMethodType.AS_EXTREME_VALUES); miningField.setLowValue(0.0); miningField.setHighValue(10.0); Object value = 15.0; FieldValue fieldValue = ArgumentUtil.prepare(dataField, miningField, value); assertEquals(10.0, fieldValue.getValue()); }
@Test public void testEvaluateDiscretize() { Discretize discretize = new Discretize("field", DataType.INTEGER, new HashMap<Double, String>(), "missing"); EvaluationContext context = new EvaluationContext(); context.setFieldValue("field", FieldValueUtil.create(DataType.INTEGER, 5)); FieldValue result = ExpressionUtil.evaluateDiscretize(discretize, context); assertEquals(FieldValueUtil.create(DataType.STRING, null, "missing"), result); }
@Test public void testGetDataType() { Object str = "Hello"; Object integer = 10; Object flt = 10.5f; Object dbl = 10.5; Object bool = true; Object date = LocalDate.now(); Object time = LocalTime.now(); Object dateTime = LocalDateTime.now(); Object daysSinceDate = new DaysSinceDate(LocalDate.of(1960, 1, 1), 10); Object secondsSinceMidnight = new SecondsSinceMidnight(LocalTime.now()); Object secondsSinceDate = new SecondsSinceDate(LocalDate.of(1970, 1, 1), 10000); assertEquals(DataType.STRING, TypeUtil.getDataType(str)); assertEquals(DataType.INTEGER, TypeUtil.getDataType(integer)); assertEquals(DataType.FLOAT, TypeUtil.getDataType(flt)); assertEquals(DataType.DOUBLE, TypeUtil.getDataType(dbl)); assertEquals(DataType.BOOLEAN, TypeUtil.getDataType(bool)); assertEquals(DataType.DATE, TypeUtil.getDataType(date)); assertEquals(DataType.TIME, TypeUtil.getDataType(time)); assertEquals(DataType.DATE_TIME, TypeUtil.getDataType(dateTime)); assertEquals(DataType.DATE_DAYS_SINCE_1960, TypeUtil.getDataType(daysSinceDate)); assertEquals(DataType.TIME_SECONDS, TypeUtil.getDataType(secondsSinceMidnight)); assertEquals(DataType.DATE_TIME_SECONDS_SINCE_1970, TypeUtil.getDataType(secondsSinceDate)); assertThrows(EvaluationException.class, () -> TypeUtil.getDataType(new Object())); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testAcceptable() { Object expected = 10; Object actual = 10.0; double precision = 0.1; double zeroThreshold = 0.0; boolean result = VerificationUtil.acceptable(expected, actual, precision, zeroThreshold); assertTrue(result); }
@Test public void testEvaluate() { List<FieldValue> values = new ArrayList<>(); values.add(new FieldValue("John")); values.add(new FieldValue("Doe")); Apply apply = new Apply("concat", values); EvaluationContext context = new EvaluationContext(); FieldValue result = FunctionUtil.evaluate(apply, values, context); assertEquals("JohnDoe", result.getValue()); }
@Test public void testEvaluateFieldRef() { FieldRef fieldRef = new FieldRef("fieldName"); EvaluationContext context = new EvaluationContext(); context.setFieldValue("fieldName", new FieldValue("fieldValue")); FieldValue result = ExpressionUtil.evaluateFieldRef(fieldRef, context); assertEquals(new FieldValue("fieldValue"), result); }
@Test public void testIsInvalid() { DataField dataField = new DataField("fieldName", DataType.STRING); Object value = "validValue"; assertFalse(ArgumentUtil.isInvalid(dataField, value)); value = null; assertFalse(ArgumentUtil.isInvalid(dataField, value)); dataField = new DataField("fieldName", DataType.INTEGER); value = "invalidValue"; assertTrue(ArgumentUtil.isInvalid(dataField, value)); }
@Test public void testGetConstantDataType() { assertEquals(DataType.INTEGER, TypeUtil.getConstantDataType("123")); assertEquals(DataType.FLOAT, TypeUtil.getConstantDataType("123.45")); assertEquals(DataType.STRING, TypeUtil.getConstantDataType("abc")); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testBinaryAnd() { assertTrue(PredicateUtil.binaryAnd(true, true)); assertFalse(PredicateUtil.binaryAnd(true, false)); assertFalse(PredicateUtil.binaryAnd(false, true)); assertFalse(PredicateUtil.binaryAnd(false, false)); assertNull(PredicateUtil.binaryAnd(null, true)); assertNull(PredicateUtil.binaryAnd(true, null)); assertFalse(PredicateUtil.binaryAnd(null, false)); assertNull(PredicateUtil.binaryAnd(null, null)); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testCreate() { String value = "testValue"; FieldName fieldName = FieldName.create(value); assertNotNull(fieldName); assertEquals(value, fieldName.value); }
@Test public void testContains() { Interval interval = new Interval(2.0, 5.0, Interval.Closure.OPEN_CLOSED); assertTrue(DiscretizationUtil.contains(interval, 3.0)); assertFalse(DiscretizationUtil.contains(interval, 1.0)); assertFalse(DiscretizationUtil.contains(interval, 6.0)); assertTrue(DiscretizationUtil.contains(interval, 5.0)); assertFalse(DiscretizationUtil.contains(interval, 2.0)); }
@Test public void testEvaluate() { Apply apply = new Apply("functionName"); List<FieldValue> values = new ArrayList<>(); EvaluationContext context = new EvaluationContext(); FieldValue fieldValue1 = new FieldValue("field1", "value1"); FieldValue fieldValue2 = new FieldValue("field2", "value2"); values.add(fieldValue1); values.add(fieldValue2); FunctionUtil.evaluate(apply, values, context); }
@Test public void testEvaluateAggregate() { Aggregate aggregate = new Aggregate(new Field("field"), Aggregate.Function.COUNT, null); EvaluationContext context = new EvaluationContext(); Collection<Integer> values = Arrays.asList(1, 2, 3, null, 4, 5, null); FieldValue fieldValue = FieldValueUtil.create(values); FieldName groupName = new FieldName("groupField"); ExpressionUtil.evaluate(groupName, context); FieldValue result = ExpressionUtil.evaluateAggregate(aggregate, context); assertEquals(5, FieldValueUtil.getValue(result)); }
@Test public void testGroupRows() { Map<String, Object> row1 = new HashMap<>(); row1.put("name", "John"); row1.put("age", 25); row1.put("city", "New York"); Map<String, Object> row2 = new HashMap<>(); row2.put("name", "Jane"); row2.put("age", 30); row2.put("city", "Los Angeles"); Map<String, Object> row3 = new HashMap<>(); row3.put("name", "Bob"); row3.put("age", 25); row3.put("city", "New York"); List<Map<String, Object>> table = new ArrayList<>(); table.add(row1); table.add(row2); table.add(row3); List<Map<String, Object>> resultTable = EvaluatorUtil.groupRows("age", table); assertEquals(2, resultTable.size()); Map<String, Object> resultRow1 = resultTable.get(0); assertEquals(25, resultRow1.get("age")); assertEquals(2, resultRow1.size()); Map<String, Object> resultRow2 = resultTable.get(1); assertEquals(30, resultRow2.get("age")); assertEquals(2, resultRow2.size()); }
@Test public void testCreate() { String value = "testValue"; FieldName fieldName = FieldName.create(value); assertNotNull(fieldName); assertEquals(value, fieldName.value); }
@Test public void testIsValid() { DataField dataField = new DataField(DataType.DOUBLE, OpType.CONTINUOUS); dataField.addInterval(new Interval(0.0, 10.0)); Object value = 5.0; boolean result = ArgumentUtil.isValid(dataField, value); assertTrue(result); dataField = new DataField(DataType.STRING, OpType.CATEGORICAL); dataField.addValue(new Value("red", Value.Property.VALID)); dataField.addValue(new Value("blue", Value.Property.VALID)); dataField.addValue(new Value("green", Value.Property.INVALID)); value = "red"; result = ArgumentUtil.isValid(dataField, value); assertTrue(result); value = "green"; result = ArgumentUtil.isValid(dataField, value); assertFalse(result); }
@Test public void testProcess() { Target target = new Target(); target.setMin(10.0); target.setMax(20.0); target.setRescaleFactor(2.0); target.setRescaleConstant(5.0); target.setCastInteger(Target.CastInteger.ROUND); Double value = 15.0; Number expected = 35; Number actual = TargetUtil.process(target, value); assertEquals(expected, actual); }
@Test public void testChangedLines() { ChangedLinesComputer clc = new ChangedLinesComputer(); Set<Integer> expected = new HashSet<>(); expected.add(1); expected.add(3); expected.add(5); Tracker tracker = new Tracker(expected); Set<Integer> actual = clc.changedLines(tracker); assertEquals(expected, actual); }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testChangedLines() { ChangedLinesComputer clc = new ChangedLinesComputer(); Set<Integer> expected = new HashSet<>(); expected.add(1); expected.add(3); expected.add(5); Tracker tracker = new Tracker(expected); Set<Integer> actual = clc.changedLines(tracker); assertEquals(expected, actual); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Map<Path, Set<Integer>> changedLines = gitScmProvider.branchChangedLines("testBranch", tempDir, changedFiles); assertEquals(1, changedLines.size()); assertTrue(changedLines.containsKey(filePath)); assertEquals(new HashSet<>(Arrays.asList(1)), changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Map<Path, Set<Integer>> changedLines = gitScmProvider.branchChangedLines("testBranch", tempDir, changedFiles); assertEquals(1, changedLines.size()); assertTrue(changedLines.containsKey(filePath)); assertEquals(new HashSet<>(Arrays.asList(1)), changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testChangedLines() { ChangedLinesComputer clc = new ChangedLinesComputer(); Set<Integer> expected = new HashSet<>(); expected.add(1); expected.add(3); expected.add(5); Tracker tracker = new Tracker(expected); Set<Integer> actual = clc.changedLines(tracker); assertEquals(expected, actual); }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBlameCommand() { JGitBlameCommand jgitBlameCommand = new JGitBlameCommand(); AnalysisWarnings analysisWarnings = new AnalysisWarnings(); GitIgnoreCommand gitIgnoreCommand = new GitIgnoreCommand(); System2 system2 = new System2(); GitScmProvider gitScmProvider = new GitScmProvider(jgitBlameCommand, analysisWarnings, gitIgnoreCommand, system2); BlameCommand blameCommand = gitScmProvider.blameCommand(); assertNotNull(blameCommand); }
@Test public void testRelativePathFromScmRoot() { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path path = Paths.get("C:/Users/username/Documents/project/src/main/java/com/example/MyClass.java"); Path expected = Paths.get("src/main/java/com/example/MyClass.java"); assertEquals(expected, gitScmProvider.relativePathFromScmRoot(path)); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); GitScmProvider provider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); Map<Path, Set<Integer>> changedLines = provider.branchChangedLines("testBranch", tempDir, changedFiles); Set<Integer> expectedLines = new HashSet<>(); expectedLines.add(1); assertEquals(expectedLines, changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testGitScmProviderKey() { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); String expectedKey = "git"; String actualKey = gitScmProvider.key(); assertEquals(expectedKey, actualKey); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Added new file to test branch").call(); GitScmProvider scmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = scmProvider.branchChangedFiles("testBranch", tempDir); Set<Path> expectedFiles = new HashSet<>(); expectedFiles.add(newFilePath); assertEquals(expectedFiles, changedFiles); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Map<Path, Set<Integer>> changedLines = gitScmProvider.branchChangedLines("testBranch", tempDir, changedFiles); assertEquals(1, changedLines.size()); assertTrue(changedLines.containsKey(filePath)); assertEquals(new HashSet<>(Arrays.asList(1)), changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testSupports() { File baseDir = new File("path/to/base/dir"); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); boolean result = gitScmProvider.supports(baseDir); assertTrue(result); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testNewThread() { ForkJoinPool pool = new ForkJoinPool(); GitThreadFactory factory = new GitThreadFactory(); ForkJoinWorkerThread thread = factory.newThread(pool); assertNotNull(thread); assertEquals("GitThreadFactory-0", thread.getName()); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); GitScmProvider provider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); Map<Path, Set<Integer>> changedLines = provider.branchChangedLines("testBranch", tempDir, changedFiles); Set<Integer> expectedLines = new HashSet<>(); expectedLines.add(1); assertEquals(expectedLines, changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Map<Path, Set<Integer>> changedLines = gitScmProvider.branchChangedLines("testBranch", tempDir, changedFiles); assertEquals(1, changedLines.size()); assertTrue(changedLines.containsKey(filePath)); assertEquals(new HashSet<>(Arrays.asList(1)), changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testDefine() { Context context = mock(Context.class); GitPlugin gitPlugin = new GitPlugin(); gitPlugin.define(context); verify(context).addExtensions(JGitBlameCommand.class, GitScmProvider.class, GitIgnoreCommand.class); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testRelativePathFromScmRoot() { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path path = Paths.get("C:/Users/username/git/project/src/main/java/com/example/MyClass.java"); Path expected = Paths.get("src/main/java/com/example/MyClass.java"); assertEquals(expected, gitScmProvider.relativePathFromScmRoot(path)); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); GitScmProvider provider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); Map<Path, Set<Integer>> changedLines = provider.branchChangedLines("testBranch", tempDir, changedFiles); Set<Integer> expectedLines = new HashSet<>(); expectedLines.add(1); assertEquals(expectedLines, changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testChangedLines() { ChangedLinesComputer clc = new ChangedLinesComputer(); Set<Integer> expected = new HashSet<>(); expected.add(1); expected.add(3); expected.add(5); Tracker tracker = new Tracker(expected); Set<Integer> actual = clc.changedLines(tracker); assertEquals(expected, actual); }
@Test public void testRelativePathFromScmRoot() { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path path = Paths.get("C:/Users/username/Documents/project/src/main/java/com/example/MyClass.java"); Path expected = Paths.get("src/main/java/com/example/MyClass.java"); assertEquals(expected, gitScmProvider.relativePathFromScmRoot(path)); }
@Test public void testRevisionId() throws IOException { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path path = Paths.get("path/to/repo"); String revisionId = gitScmProvider.revisionId(path); assertNotNull(revisionId); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBranchChangedLines() throws Exception { Path tempDir = Files.createTempDirectory("testRepo"); try { Git.init().setDirectory(tempDir.toFile()).call(); Path filePath = tempDir.resolve("test.txt"); Files.write(filePath, "test content".getBytes()); Git git = Git.open(tempDir.toFile()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.branchCreate().setName("testBranch").call(); Files.write(filePath, "modified content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Modified file in testBranch").call(); Set<Path> changedFiles = new HashSet<>(); changedFiles.add(filePath); GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Map<Path, Set<Integer>> changedLines = gitScmProvider.branchChangedLines("testBranch", tempDir, changedFiles); assertEquals(1, changedLines.size()); assertTrue(changedLines.containsKey(filePath)); assertEquals(new HashSet<>(Arrays.asList(1)), changedLines.get(filePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testChangedLines() { ChangedLinesComputer clc = new ChangedLinesComputer(); Set<Integer> expected = new HashSet<>(); expected.add(1); expected.add(3); expected.add(5); Tracker tracker = new Tracker(expected); Set<Integer> actual = clc.changedLines(tracker); assertEquals(expected, actual); }
@Test public void testBlame() throws Exception { BlameInput input = mock(BlameInput.class); BlameOutput output = mock(BlameOutput.class); FileSystem fileSystem = mock(FileSystem.class); PathResolver pathResolver = mock(PathResolver.class); AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class); when(input.fileSystem()).thenReturn(fileSystem); when(fileSystem.baseDir()).thenReturn(new File("test")); when(input.filesToBlame()).thenReturn(Arrays.asList(new InputFile("testFile"))); JGitBlameCommand jGitBlameCommand = new JGitBlameCommand(pathResolver, analysisWarnings); jGitBlameCommand.blame(input, output); verify(output, times(1)).blame(any(BlameLine.class)); }
@Test public void testBranchChangedFiles() throws IOException, GitAPIException { Path tempDir = Files.createTempDirectory("testRepo"); try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Path filePath = tempDir.resolve("testFile.txt"); Files.write(filePath, "test content".getBytes()); git.add().addFilepattern(".").call(); git.commit().setMessage("Initial commit").call(); git.checkout().setCreateBranch(true).setName("testBranch").call(); Path newFilePath = tempDir.resolve("newTestFile.txt"); Files.write(newFilePath, "new test content".getBytes()); GitScmProvider gitScmProvider = new GitScmProvider(null, null, null, null); Set<Path> changedFiles = gitScmProvider.branchChangedFiles("testBranch", tempDir); assertEquals(1, changedFiles.size()); assertTrue(changedFiles.contains(newFilePath)); } finally { FileUtils.deleteDirectory(tempDir.toFile()); } }
@Test public void testRevisionId() throws IOException { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path path = Paths.get("path/to/repo"); String revisionId = gitScmProvider.revisionId(path); assertNotNull(revisionId); }
@Test public void testForkDate() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path projectBaseDir = Paths.get("path/to/project"); Instant forkDate = gitScmProvider.forkDate("master", projectBaseDir); assertNotNull(forkDate); }
@Test public void testBranchChangedFiles() throws Exception { GitScmProvider gitScmProvider = new GitScmProvider(new JGitBlameCommand(), new AnalysisWarnings(), new GitIgnoreCommand(), new System2()); Path rootBaseDir = Paths.get("path/to/root/dir"); Set<Path> expected = new HashSet<>(); expected.add(rootBaseDir.resolve("file1.txt")); expected.add(rootBaseDir.resolve("file2.txt")); Set<Path> actual = gitScmProvider.branchChangedFiles("targetBranch", rootBaseDir); assertEquals(expected, actual); }
@Test public void testHashCode() { NodeId nodeId1 = new NodeId(123456789L); NodeId nodeId2 = new NodeId(123456789L); NodeId nodeId3 = new NodeId(987654321L); assertEquals(nodeId1.hashCode(), nodeId2.hashCode()); assertNotEquals(nodeId1.hashCode(), nodeId3.hashCode()); }
@Test public void testGetNodeAddresses() { NodeAddress node1 = new NodeAddress("127.0.0.1", 8080); NodeAddress node2 = new NodeAddress("127.0.0.1", 8081); NodeAddress node3 = new NodeAddress("127.0.0.1", 8082); List<NodeAddress> nodeList = Arrays.asList(node1, node2, node3); ConstNodeDiscovery constNodeDiscovery = new ConstNodeDiscovery(nodeList); assertEquals(nodeList, constNodeDiscovery.getNodeAddresses()); }
@Test public void testShutdown() throws Exception { NodeServer nodeServer = new NodeServer(); nodeServer.shutdown(); assertNull(nodeServer.acceptChannel); }
@Test public void testToString() { NodeId nodeId = new NodeId(123456789L); String expected = "NodeId{ id=0x75BCD15 }"; String actual = nodeId.toString(); assertEquals(expected, actual); }
@Test public void testRemoveUser() { MucService service = new MucService(); KixmppJid roomJid = new KixmppJid("room@example.com"); MucRoomSettings settings = new MucRoomSettings(); MucRoom room = new MucRoom(service, roomJid, settings); KixmppJid userJid = new KixmppJid("user@example.com/resource"); room.addUser(userJid, "nickname"); boolean result = room.removeUser(userJid); assertTrue(result); }
@Test public void testCompareTo() { NodeId nodeId1 = new NodeId(1L); NodeId nodeId2 = new NodeId(2L); NodeId nodeId3 = new NodeId(1L); assertTrue(nodeId1.compareTo(nodeId2) < 0); assertTrue(nodeId2.compareTo(nodeId1) > 0); assertTrue(nodeId1.compareTo(nodeId3) == 0); }
@Test public void testJoin() { MucService service = new MucService(); KixmppJid roomJid = new KixmppJid("roomJid"); MucRoomSettings settings = new MucRoomSettings(); MucRoom room = new MucRoom(service, roomJid, settings); Channel channel = new Channel(); String nickname = "testNickname"; room.join(channel, nickname); assertTrue(channel.getUsers().contains(nickname)); }
@Test public void testEquals() { NodeId nodeId1 = new NodeId(1); NodeId nodeId2 = new NodeId(2); NodeId nodeId3 = new NodeId(1); NodeId nodeId4 = new NodeId(nodeId1); assertTrue(nodeId1.equals(nodeId3)); assertTrue(nodeId1.equals(nodeId4)); assertFalse(nodeId1.equals(nodeId2)); assertFalse(nodeId1.equals(null)); assertFalse(nodeId1.equals("not a NodeId object")); }
@Test public void testEquals() { NodeId nodeId1 = new NodeId(1); NodeId nodeId2 = new NodeId(2); NodeId nodeId3 = new NodeId(1); NodeId nodeId4 = new NodeId(nodeId1); assertTrue(nodeId1.equals(nodeId3)); assertTrue(nodeId1.equals(nodeId4)); assertFalse(nodeId1.equals(nodeId2)); assertFalse(nodeId1.equals(null)); assertFalse(nodeId1.equals("not a NodeId object")); }
@Test public void testGetNodeAddresses() { NodeAddress node1 = new NodeAddress("127.0.0.1", 8080); NodeAddress node2 = new NodeAddress("127.0.0.1", 8081); NodeAddress node3 = new NodeAddress("127.0.0.1", 8082); List<NodeAddress> nodeList = Arrays.asList(node1, node2, node3); ConstNodeDiscovery constNodeDiscovery = new ConstNodeDiscovery(nodeList); assertEquals(nodeList, constNodeDiscovery.getNodeAddresses()); }
@Test public void testGetNodeAddresses() { NodeAddress node1 = new NodeAddress("127.0.0.1", 8080); NodeAddress node2 = new NodeAddress("127.0.0.1", 8081); NodeAddress node3 = new NodeAddress("127.0.0.1", 8082); List<NodeAddress> nodeList = Arrays.asList(node1, node2, node3); ConstNodeDiscovery constNodeDiscovery = new ConstNodeDiscovery(nodeList); assertEquals(nodeList, constNodeDiscovery.getNodeAddresses()); }
@Test public void testIsIdSet() { Address address = new Address(); assertFalse(address.isIdSet()); address.setId(1); assertTrue(address.isIdSet()); }
@Test public void testIsIdSet() { MoreTypesDemo moreTypesDemo = new MoreTypesDemo(); assertFalse(moreTypesDemo.isIdSet()); moreTypesDemo.setId(BigDecimal.ONE); assertTrue(moreTypesDemo.isIdSet()); }
@Test public void testIsIdSet() { Role role = new Role(); assertFalse(role.isIdSet()); role.setId(1); assertTrue(role.isIdSet()); }
@Test public void testToString() { LegacyPk pk1 = new LegacyPk("123", 456, "John Doe"); LegacyPk pk2 = new LegacyPk("456", null, "Jane Smith"); LegacyPk pk3 = new LegacyPk(null, null, null); assertEquals("123:456:John Doe", pk1.toString()); assertEquals("456:Jane Smith", pk2.toString()); assertEquals("", pk3.toString()); }
@Test public void testIsIdSet() { Account account = new Account(); assertFalse(account.isIdSet()); account.setId(""); assertFalse(account.isIdSet()); account.setId("123"); assertTrue(account.isIdSet()); }
@Test public void testIsIdSet() { Book book = new Book(); assertFalse(book.isIdSet()); book.setId(1); assertTrue(book.isIdSet()); }
@Test public void testIsIdSet() { AuditLog auditLog = new AuditLog(); assertFalse(auditLog.isIdSet()); auditLog.setId(1); assertTrue(auditLog.isIdSet()); }
@Test public void testIsIdSet() { SavedSearch savedSearch = new SavedSearch(); savedSearch.setId(1); assertTrue(savedSearch.isIdSet()); }
@Test public void testIsIdSet() { Document document = new Document(); document.setId("123"); assertTrue(document.isIdSet()); document.setId(""); assertFalse(document.isIdSet()); document.setId(null); assertFalse(document.isIdSet()); }
@Test public void testIsEmpty() { LegacyPk pk = new LegacyPk(); assertTrue(pk.isEmpty()); pk = new LegacyPk("code", 1, "name"); assertFalse(pk.isEmpty()); }
@Test public void testFailOverSink() { EventSink primary = mock(EventSink.class); EventSink backup = mock(EventSink.class); FailOverSink failOverSink = new FailOverSink(primary, backup); assertNotNull(failOverSink); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testNaiveFileWALDeco() { Context context = new Context(); EventSink sink = new MockEventSink(); WALManager walManager = new MockWALManager(); RollTrigger rollTrigger = new TimeTrigger(1000); AckListener ackListener = new MockAckListener(); long checkMs = 500; NaiveFileWALDeco naiveFileWALDeco = new NaiveFileWALDeco(context, sink, walManager, rollTrigger, ackListener, checkMs); assertNotNull(naiveFileWALDeco); }
@Test public void testGenEventSource() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SOURCE.name())); tree.addChild(new CommonTree("type")); CommonTree arg1 = new CommonTree(ASTNODE.ARG.name()); arg1.addChild(new CommonTree("arg1")); CommonTree arg2 = new CommonTree(ASTNODE.ARG.name()); arg2.addChild(new CommonTree("arg2")); tree.addChild(arg1); tree.addChild(arg2); String result = FlumeSpecGen.genEventSource(tree); assertEquals("type(arg1,arg2)", result); }
@Test public void testTextFileSink() { String fileName = "test.txt"; OutputFormat format = OutputFormat.JSON; TextFileSink textFileSink = new TextFileSink(fileName, format); assertEquals(format, textFileSink.getFormat()); }
@Test public void testGetMetrics() { FanOutSink<EventSink> fanOutSink = new FanOutSink<>(); ReportEvent reportEvent = fanOutSink.getMetrics(); assertNotNull(reportEvent); assertEquals(0, reportEvent.getLongMetric(R_SUBSINKS)); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testGetMetrics() { TailDirSource tailDirSource = new TailDirSource(new File("test.txt"), ".*"); ReportEvent reportEvent = tailDirSource.getMetrics(); assertNotNull(reportEvent); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESPRESENT)); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testShutdown() throws InterruptedException { ZooKeeperService svc = new ZooKeeperService(); String prefix = "testPrefix"; ZooKeeperCounter counter = new ZooKeeperCounter(svc, prefix); counter.shutdown(); }
@Test public void testExecNioSource() { ExecNioSource source = new ExecNioSource("ls -l", true, false, 1000); assertNotNull(source); }
@Test public void testGetCodec() { Configuration conf = new Configuration(); String codecName = "None"; CompressionCodec codec = CustomDfsSink.getCodec(conf, codecName); assertNull(codec); codecName = "GzipCodec"; codec = CustomDfsSink.getCodec(conf, codecName); assertNotNull(codec); assertTrue(codec instanceof GzipCodec); }
@Test public void testGetMetrics() { TailDirSource tailDirSource = new TailDirSource(new File("test.txt"), ".*"); ReportEvent reportEvent = tailDirSource.getMetrics(); assertNotNull(reportEvent); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESPRESENT)); }
@Test public void testOpen() throws IOException, InterruptedException { EventSink primary = mock(EventSink.class); EventSink backup = mock(EventSink.class); BackoffPolicy backoff = mock(BackoffPolicy.class); BackOffFailOverSink sink = new BackOffFailOverSink(primary, backup, backoff); IOException ex = new IOException("Primary open failed"); when(primary.open()).thenThrow(ex); when(backoff.sleepBeforeNextAttempt()).thenReturn(true); sink.open(); verify(primary, times(1)).open(); verify(backup, times(1)).open(); verify(backoff, times(1)).sleepBeforeNextAttempt(); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testGenArg() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.HEX.name())); tree.getChild(0).addChild(new CommonTree("0x123")); String result = FlumeSpecGen.genArg(tree); assertEquals("0x123", result); }
@Test public void testOpen() throws IOException { ExecNioSource execNioSource = new ExecNioSource("ls -l", true, true, 1000); execNioSource.open(); assertNotNull(execNioSource.proc); assertNotNull(execNioSource.stdinISP); assertNotNull(execNioSource.stderrISP); assertNotNull(execNioSource.stdout); assertNotNull(execNioSource.stderr); assertNotNull(execNioSource.readOut); assertNotNull(execNioSource.readErr); }
@Test public void testGetChildren() throws Exception { ZKClient zkClient = new ZKClient("localhost:2181"); String path = "/test"; boolean watch = true; List<String> children = zkClient.getChildren(path, watch); assertNotNull(children); }
@Test public void testReset() throws KeeperException, IOException, InterruptedException { ZooKeeperService svc = new ZooKeeperService(); String prefix = "test"; String name = "testCounter"; ZooKeeperCounter counter = new ZooKeeperCounter(svc, prefix); counter.reset(); long count = svc.getData(prefix + "/" + name); assertEquals(0L, count); }
@Test public void testRetryHarness() { Retryable retry = mock(Retryable.class); BackoffPolicy policy = mock(BackoffPolicy.class); RetryHarness harness = new RetryHarness(retry, policy); assertNotNull(harness); }
@Test public void testSetConfig() throws IOException { MemoryBackedConfigStore store = new MemoryBackedConfigStore(); String host = "localhost"; String flowid = "testFlow"; String source = "testSource"; String sink = "testSink"; store.setConfig(host, flowid, source, sink); FlumeConfigData configData = store.cfgs.get(host); assertNotNull(configData); assertEquals(flowid, configData.flowID); assertEquals(source, configData.sourceName); assertEquals(sink, configData.sinkName); }
@Test public void testClose() { FlumeLog4jAvroAppender appender = new FlumeLog4jAvroAppender(); appender.close(); assertNull(appender.client); }
@Test public void testAgentSink() throws FlumeSpecException { Context ctx = new Context(); String dsthost = "localhost"; int port = 9090; ReliabilityMode mode = ReliabilityMode.ENDTOEND; AgentSink agentSink = new AgentSink(ctx, dsthost, port, mode); assertNotNull(agentSink); }
@Test public void testSetConfig() throws IOException { MemoryBackedConfigStore store = new MemoryBackedConfigStore(); String host = "localhost"; String flowid = "testFlow"; String source = "testSource"; String sink = "testSink"; store.setConfig(host, flowid, source, sink); FlumeConfigData configData = store.cfgs.get(host); assertNotNull(configData); assertEquals(flowid, configData.flowID); assertEquals(source, configData.sourceName); assertEquals(sink, configData.sinkName); }
@Test public void testExtractEvent() throws Exception { byte[] data = "<14>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8".getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bais); Event event = SyslogWireExtractor.extractEvent(dis); assertNotNull(event); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testGetAllReports() throws TException { FlumeConfiguration cfg = new FlumeConfiguration(); ThriftReportServer server = new ThriftReportServer(cfg); Map<String, ThriftFlumeReport> expectedMap = new HashMap<String, ThriftFlumeReport>(); ReportManager reportManager = ReportManager.get(); Map<String, Reportable> reports = reportManager.getReportables(); for (Entry<String, Reportable> e : reports.entrySet()) { ThriftFlumeReport report = reportToThrift(e.getValue().getMetrics()); expectedMap.put(e.getKey(), report); } Map<String, ThriftFlumeReport> actualMap = server.getAllReports(); assertEquals(expectedMap, actualMap); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testCheckConfig() { FlumeConfigData data = new FlumeConfigData(); data.setSourceVersion(System.currentTimeMillis()); LogicalNode node = new LogicalNode(); assertTrue(node.checkConfig(data)); }
@Test public void testClose() throws IOException { ExecNioSource execNioSource = new ExecNioSource("ls -l", true, true, 1000); execNioSource.close(); assertNull(execNioSource.proc); }
@Test public void testExec() throws MasterExecException, IOException { CommandManager cm = new CommandManager(); Command cmd = new Command("command", new String[]{"arg1", "arg2"}); cm.exec(cmd); }
@Test public void testZKClient() { ZKClient zkClient = new ZKClient("localhost:2181"); assertNotNull(zkClient); }
@Test public void testGetMetrics() { LogicalNodeManager logicalNodeManager = new LogicalNodeManager(); logicalNodeManager.addNode(new LogicalNode("node1")); logicalNodeManager.addNode(new LogicalNode("node2")); MasterRPC rpc = new MasterRPC(); WALManager walMan = new WALManager(); DiskFailoverManager dfMan = new DiskFailoverManager(); CollectorAckListener colAck = new CollectorAckListener(); LivenessManager liveman = new LivenessManager(); FlumeNode flumeNode = new FlumeNode("testNode", rpc, logicalNodeManager, walMan, dfMan, colAck, liveman); ReportEvent reportEvent = flumeNode.getMetrics(); assertEquals("testNode", reportEvent.getHostName()); assertEquals(2, reportEvent.getLongMetric(R_NUM_LOGICAL_NODES)); }
@Test public void testGetMasterHeartbeatPort() { FlumeConfiguration config = new FlumeConfiguration(true); int defaultPort = config.getMasterHeartbeatPort(); assertEquals(35873, defaultPort); config.set(MASTER_HEARTBEAT_PORT, "12345"); int port = config.getMasterHeartbeatPort(); assertEquals(12345, port); config.set(MASTER_HEARTBEAT_SERVERS, "localhost:12345,localhost:23456"); config.set(MASTER_SERVER_ID, "1"); int serverPort = config.getMasterHeartbeatPort(); assertEquals(23456, serverPort); }
@Test public void testReorderDecorator() { Context context = new Context(); String[] argv = {"0.5", "0.5"}; ReorderDecorator<EventSink> reorderDecorator = ReorderDecorator.builder().build(context, argv); assertNotNull(reorderDecorator); assertEquals(0.5, reorderDecorator.getYank(), 0.0); assertEquals(0.5, reorderDecorator.getSpew(), 0.0); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String result = FlumeSpecGen.genEventSink(tree); assertEquals("type1(arg1,arg2)", result); }
@Test public void testVar() { PatternMatch p1 = new PatternMatch(PatternType.VAR, "name1", null); PatternMatch p2 = new PatternMatch(PatternType.VAR, "name2", p1); PatternMatch result = PatternMatch.var("name3", p2); assertEquals(PatternType.VAR, result.getType()); assertEquals("name3", result.getArgs()[0]); assertEquals(p2, result.getArgs()[1]); }
@Test public void testConsistentHash() { List<String> nodes = Arrays.asList("node1", "node2", "node3"); ConsistentHash<String> consistentHash = new ConsistentHash<>(2, nodes); assertEquals(6, consistentHash.size()); }
@Test public void testFindHostIndex() throws UnknownHostException, SocketException { String[] hosts = {"localhost", "google.com", "example.com"}; int expectedIndex = 0; int actualIndex = NetUtils.findHostIndex(hosts); assertEquals(expectedIndex, actualIndex); }
@Test public void testAddLogicalNode() { MemoryBackedConfigStore store = new MemoryBackedConfigStore(); store.addLogicalNode("node1", "logic1"); assertTrue(store.nodeMap.containsEntry("node1", "logic1")); }
@Test public void testExec() throws MasterExecException, IOException { CommandManager cm = new CommandManager(); Command cmd = new Command("test", new String[]{"arg1", "arg2"}); Execable ex = mock(Execable.class); when(ex.exec(cmd.getArgs())).thenReturn(true); Map<String, Execable> cmds = new HashMap<>(); cmds.put("test", ex); Whitebox.setInternalState(cm, "cmds", cmds); cm.exec(cmd); verify(ex, times(1)).exec(cmd.getArgs()); }
@Test public void testDiskFailoverDeco() { Context context = new Context(); context.put(LogicalNodeContext.C_LOGICAL, "testNode"); DiskFailoverManager dfoman = new DiskFailoverManager(); RollTrigger t = new TimeTrigger(new ProcessTagger(), 1000); long checkmillis = 500; EventSink sink = new StdoutEventSink(); DiskFailoverDeco deco = new DiskFailoverDeco(sink, context, dfoman, t, checkmillis); assertNotNull(deco); }
@Test public void testGetMetrics() { TailDirSource tailDirSource = new TailDirSource(new File("test.txt"), ".*"); ReportEvent reportEvent = tailDirSource.getMetrics(); assertNotNull(reportEvent); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESPRESENT)); }
@Test public void testToFlumeEvent() { ThriftFlumeEvent evt = new ThriftFlumeEvent(); Event result = ThriftEventConvertUtil.toFlumeEvent(evt); assertNotNull(result); }
@Test public void testParseSink() throws RecognitionException { String sink = "agent1.sink1.type = avro"; CommonTree ast = FlumeBuilder.parseSink(sink); assertNotNull(ast); assertEquals(FlumeDeployParser.SINK, ast.getType()); assertEquals("agent1.sink1", ast.getChild(0).getText()); assertEquals("avro", ast.getChild(1).getChild(0).getText()); }
@Test public void testReorderDecorator() { Context context = new Context(); String[] argv = {"0.5", "0.5"}; ReorderDecorator<EventSink> reorderDecorator = ReorderDecorator.builder().build(context, argv); assertNotNull(reorderDecorator); assertEquals(0.5, reorderDecorator.getYank(), 0.0); assertEquals(0.5, reorderDecorator.getSpew(), 0.0); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testCommandManager() { Object[][] cmdArray = {{"command1", "description1"}, {"command2", "description2"}}; CommandManager commandManager = new CommandManager(cmdArray); assertNotNull(commandManager); }
@Test public void testDiskFailoverDeco() { Context context = new Context(); context.put(LogicalNodeContext.C_LOGICAL, "testNode"); DiskFailoverManager dfoman = new DiskFailoverManager(); RollTrigger t = new TimeTrigger(new ProcessTagger(), 1000); long checkmillis = 500; EventSink sink = new StdoutEventSink(); DiskFailoverDeco deco = new DiskFailoverDeco(sink, context, dfoman, t, checkmillis); assertNotNull(deco); }
@Test public void testFindHostIndex() throws UnknownHostException, SocketException { String[] hosts = {"localhost", "google.com", "example.com"}; int expectedIndex = 0; int actualIndex = NetUtils.findHostIndex(hosts); assertEquals(expectedIndex, actualIndex); }
@Test public void testCollectorSource() { Context context = new Context(); String[] argv = {"1234"}; EventSource eventSource = CollectorSource.builder().build(context, argv); assertNotNull(eventSource); }
@Test public void testHandleCommand() { CommandManager manager = new CommandManager(); CommandStatus cmd = new CommandStatus("test", "echo hello world"); manager.handleCommand(cmd); assertEquals("hello world\n", cmd.getExecOut()); assertEquals("", cmd.getExecErr()); assertEquals(CommandStatus.Status.SUCCEEDED, cmd.getStatus()); }
@Test public void testGetMasterGossipPort() { FlumeConfiguration config = new FlumeConfiguration(true); int defaultPort = config.getMasterGossipPort(); assertEquals(4545, defaultPort); config.set(MASTER_GOSSIP_PORT, "1234"); int port = config.getMasterGossipPort(); assertEquals(1234, port); config.set(MASTER_GOSSIP_SERVERS, "server1:5678,server2:7890"); config.set(MASTER_SERVER_ID, "1"); int serverPort = config.getMasterGossipPort(); assertEquals(7890, serverPort); }
@Test public void testValueDecorator() { EventSink<String> sink = new SomeEventSink<>(); String attr = "attribute"; String value = "value"; boolean escape = true; ValueDecorator<String> decorator = new ValueDecorator<>(sink, attr, value, escape); decorator.put("test"); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testEscapeString() { Event event = new Event(); String input = "This is a <b>bold</b> statement."; String expectedOutput = "This is a bold statement."; assertEquals(expectedOutput, event.escapeString(input)); }
@Test public void testGetAllReports() throws AvroRemoteException { AvroReportServer avroReportServer = new AvroReportServer(new FlumeConfiguration()); Map<CharSequence, AvroFlumeReport> reports = avroReportServer.getAllReports(); assertNotNull(reports); assertFalse(reports.isEmpty()); }
@Test public void testClose() throws IOException { ExecNioSource execNioSource = new ExecNioSource("ls -l", true, true, 1000); execNioSource.close(); assertNull(execNioSource.proc); }
@Test public void testGenArg() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.HEX.name())); tree.getChild(0).addChild(new CommonTree("0x123")); String result = FlumeSpecGen.genArg(tree); assertEquals("0x123", result); }
@Test public void testCreateTempFile() throws IOException { String filePrefix = "test"; String fileSuffix = ".txt"; File tempFile = FileUtil.createTempFile(filePrefix, fileSuffix); assertNotNull(tempFile); assertTrue(tempFile.exists()); assertTrue(tempFile.getName().startsWith(filePrefix)); assertTrue(tempFile.getName().endsWith(fileSuffix)); }
@Test public void testKindPatternMatch() { PatternMatch patternMatch = PatternMatch.kind("test"); assertNotNull(patternMatch); assertEquals(PatternType.KIND, patternMatch.getType()); assertEquals("test", patternMatch.getArgs()[0]); }
@Test public void testClose() throws IOException { HBaseSink hBaseSink = new HBaseSink("tableName", "rowkey", new ArrayList<>()); hBaseSink.close(); assertNull(hBaseSink.table); }
@Test public void testStart() { FlumeNode node = new FlumeNode("testNode", new MasterRPC(), new LogicalNodeManager(), new WALManager(), new DiskFailoverManager(), new CollectorAckListener(), new LivenessManager()); node.start(); assertTrue(node.isStarted()); }
@Test public void testHierarchicalMerge() { Map<String, Long> longMetrics1 = new HashMap<>(); longMetrics1.put("metric1", 10L); Map<String, String> stringMetrics1 = new HashMap<>(); stringMetrics1.put("metric2", "value2"); Map<String, Double> doubleMetrics1 = new HashMap<>(); doubleMetrics1.put("metric3", 3.14); ReportEvent event1 = new ReportEvent(longMetrics1, stringMetrics1, doubleMetrics1); Map<String, Long> longMetrics2 = new HashMap<>(); longMetrics2.put("metric4", 20L); Map<String, String> stringMetrics2 = new HashMap<>(); stringMetrics2.put("metric5", "value5"); Map<String, Double> doubleMetrics2 = new HashMap<>(); doubleMetrics2.put("metric6", 6.28); ReportEvent event2 = new ReportEvent(longMetrics2, stringMetrics2, doubleMetrics2); event1.hierarchicalMerge("prefix", event2); assertEquals(10L, (long) event1.getLongMetrics().get("prefix.metric1")); assertEquals("value2", event1.getStringMetrics().get("prefix.metric2")); assertEquals(3.14, event1.getDoubleMetrics().get("prefix.metric3"), 0.001); assertEquals(20L, (long) event1.getLongMetrics().get("prefix.metric4")); assertEquals("value5", event1.getStringMetrics().get("prefix.metric5")); assertEquals(6.28, event1.getDoubleMetrics().get("prefix.metric6"), 0.001); }
@Test public void testGetMetrics() { TailDirSource tailDirSource = new TailDirSource(new File("test.txt"), ".*"); ReportEvent reportEvent = tailDirSource.getMetrics(); assertNotNull(reportEvent); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSADDED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_SUBDIRSDELETED)); assertEquals(0, reportEvent.getLongMetric(TailDirSource.A_FILESPRESENT)); }
@Test public void testParseSink() throws RecognitionException { String sink = "agent1.sink1.type = avro"; CommonTree ast = FlumeBuilder.parseSink(sink); assertNotNull(ast); assertEquals(FlumeDeployParser.SINK, ast.getType()); assertEquals("agent1.sink1", ast.getChild(0).getText()); assertEquals("avro", ast.getChild(1).getText()); }
@Test public void testTuplePatternMatch() { PatternMatch pm1 = new PatternMatch(PatternType.VARIABLE, "x"); PatternMatch pm2 = new PatternMatch(PatternType.VARIABLE, "y"); PatternMatch pm3 = new PatternMatch(PatternType.TUPLE, pm1, pm2); PatternMatch pm4 = PatternMatch.tuple(pm1, pm2); assertEquals(pm3, pm4); }
@Test public void testRefreshAll() throws IOException { ConfigurationManager parentMan = mock(ConfigurationManager.class); ConfigurationManager selfMan = mock(ConfigurationManager.class); TranslatingConfigurationManager tcm = new TranslatingConfigurationManager(parentMan, selfMan); Map<String, FlumeConfigData> translatedConfigs = new HashMap<>(); FlumeConfigData fcd = new FlumeConfigData(); fcd.setSourceConfig("sourceConfig"); fcd.setSinkConfig("sinkConfig"); translatedConfigs.put("node1", fcd); when(parentMan.getTranslatedConfigs()).thenReturn(translatedConfigs); when(tcm.translateSink(anyString(), anyString())).thenReturn("translatedSink"); when(tcm.translateSource(anyString(), anyString())).thenReturn("translatedSource"); tcm.refreshAll(); verify(parentMan, times(1)).refreshAll(); verify(parentMan, times(1)).getTranslatedConfigs(); verify(tcm, times(1)).translateSink(anyString(), anyString()); verify(tcm, times(1)).translateSource(anyString(), anyString()); verify(selfMan, times(1)).setBulkConfig(anyMap()); }
@Test public void testReorderDecorator() { Context context = new Context(); String[] argv = {"0.5", "0.5"}; ReorderDecorator<EventSink> reorderDecorator = ReorderDecorator.builder().build(context, argv); assertNotNull(reorderDecorator); assertEquals(0.5, reorderDecorator.getYank(), 0.0); assertEquals(0.5, reorderDecorator.getSpew(), 0.0); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testToFlumeEvent() { AvroFlumeEvent avroFlumeEvent = new AvroFlumeEvent(); Event event = AvroEventConvertUtil.toFlumeEvent(avroFlumeEvent); assertNotNull(event); }
@Test public void testTailSource() { File file = new File("test.txt"); long offset = 0L; long waitTime = 1000L; boolean startFromEnd = false; String regex = "\\d+"; DelimMode dm = DelimMode.RECORD; TailSource tailSource = new TailSource(file, offset, waitTime, startFromEnd, regex, dm); assertNotNull(tailSource); }
@Test public void testBuildStream() { Context ctx = mock(Context.class); String[] argv = {"command"}; EventSource source = ExecNioSource.buildStream().build(ctx, argv); assertNotNull(source); assertTrue(source instanceof ExecNioSource); assertEquals("command", ((ExecNioSource) source).command); assertFalse(((ExecNioSource) source).aggregate); assertFalse(((ExecNioSource) source).restart); assertEquals(0, ((ExecNioSource) source).period); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testClose() throws IOException, InterruptedException { TailSource tailSource = new TailSource(new File("test.txt"), 0L, 1000L); tailSource.close(); assertTrue(tailSource.done); }
@Test public void testStart() { InternalHttpServer server = new InternalHttpServer(); server.setWebappDir("path/to/webapp"); server.start(); assertTrue(server.isStarted()); }
@Test public void testRecursive() { PatternMatch child = new PatternMatch(PatternType.CHILD); PatternMatch patternMatch = PatternMatch.recursive(child); assertEquals(PatternType.PARENT_RECURSIVE, patternMatch.getType()); assertEquals(child, patternMatch.getArgs()[0]); }
@Test public void testToFlumeEvent() { AvroFlumeEvent avroFlumeEvent = new AvroFlumeEvent(); Event event = AvroEventConvertUtil.toFlumeEvent(avroFlumeEvent); assertNotNull(event); }
@Test public void testToJson() throws IOException { StringWriter writer = new StringWriter(); ReportEvent reportEvent = new ReportEvent("localhost"); reportEvent.setStringMetric("metric1", "value1"); reportEvent.setLongMetric("metric2", 10L); reportEvent.setDoubleMetric("metric3", 3.14); reportEvent.toJson(writer); String expected = "{\"host\" : \"localhost\", \"metric1\" : \"value1\", \"metric2\" : 10, \"metric3\" : 3.14}"; assertEquals(expected, writer.toString()); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testBackoff() { ExponentialBackoff backoff = new ExponentialBackoff(1000, 10000); backoff.backoff(); assertEquals(2000, backoff.retryTime - Clock.unixTime()); assertEquals(2000, backoff.sleepIncrement); assertEquals(1, backoff.backoffCount); }
@Test public void testAppend() throws IOException, InterruptedException { EventSinkDecorator<S> mockSink = mock(EventSinkDecorator.class); DigestDecorator<S> digestDecorator = new DigestDecorator<>(mockSink, "SHA-256", "digest", true); Event event = new Event(); event.setBody("test".getBytes()); digestDecorator.append(event); ArgumentCaptor<Event> argument = ArgumentCaptor.forClass(Event.class); verify(mockSink).append(argument.capture()); assertEquals("test", new String(argument.getValue().getBody())); assertNotNull(argument.getValue().get("digest")); }
@Test public void testDecommission() throws IOException, InterruptedException { LogicalNodeManager manager = new LogicalNodeManager("physicalNode"); LogicalNode node = new LogicalNode("node"); manager.threads.put("node", node); ReportManager reportManager = ReportManager.get(); reportManager.add(node); manager.decommission("node"); assertFalse(manager.threads.containsKey("node")); assertFalse(reportManager.contains(node)); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testCollectorSourceConstructor() { int port = 8080; CollectorSource collectorSource = new CollectorSource(port); assertNotNull(collectorSource); assertEquals(port, collectorSource.port); }
@Test public void testGetNUniqueBinsFor() { ConsistentHash<String> ch = new ConsistentHash<>(2, Arrays.asList("node1", "node2", "node3")); List<String> bins = ch.getNUniqueBinsFor("key", 2); assertEquals(2, bins.size()); assertNotEquals(bins.get(0), bins.get(1)); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testGetReportByName() throws TException { FlumeConfiguration cfg = new FlumeConfiguration(); ThriftReportServer thriftReportServer = new ThriftReportServer(cfg); String reportName = "testReport"; Map<String, Reportable> reports = new HashMap<>(); Reportable reportable = new Reportable() { @Override public Map<String, Map<String, String>> getMetrics() { Map<String, Map<String, String>> metrics = new HashMap<>(); metrics.put("metric1", new HashMap<>()); metrics.put("metric2", new HashMap<>()); return metrics; } }; reports.put(reportName, reportable); Whitebox.setInternalState(ReportManager.class, "reportables", reports); ThriftFlumeReport expectedReport = thriftReportServer.reportToThrift(reportable.getMetrics()); ThriftFlumeReport actualReport = thriftReportServer.getReportByName(reportName); assertEquals(expectedReport, actualReport); }
@Test public void testGangliaSink() { String gangliaSvrs = "localhost:8649"; String attr = "testAttr"; String units = "testUnits"; Type t = Type.INT; GangliaSink gangliaSink = new GangliaSink(gangliaSvrs, attr, units, t); assertNotNull(gangliaSink); }
@Test public void testToFlumeEvent() { ThriftFlumeEvent evt = new ThriftFlumeEvent(); Event result = ThriftEventConvertUtil.toFlumeEvent(evt); assertNotNull(result); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testSubmit() { CommandManager manager = new CommandManager(); Command cmd = new Command("test"); long cmdId = manager.submit(cmd); assertNotNull(cmdId); assertEquals(1, manager.queue.size()); assertEquals(cmdId, manager.queue.peek().getId()); }
@Test public void testStart() { InternalHttpServer server = new InternalHttpServer(); server.setWebappDir("path/to/webapp"); server.start(); assertTrue(server.isStarted()); }
@Test public void testOpen() throws IOException { ExecNioSource execNioSource = new ExecNioSource("ls -l", true, true, 1000); execNioSource.open(); assertNotNull(execNioSource.proc); assertNotNull(execNioSource.stdinISP); assertNotNull(execNioSource.stderrISP); assertNotNull(execNioSource.stdout); assertNotNull(execNioSource.stderr); assertNotNull(execNioSource.readOut); assertNotNull(execNioSource.readErr); }
@Test public void testExtractEvent() throws Exception { byte[] data = "<14>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - BOM'su root' failed for lonvick on /dev/pts/8".getBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bis); Event event = SyslogWireExtractor.extractEvent(dis); assertNotNull(event); assertEquals("<14>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - BOM'su root' failed for lonvick on /dev/pts/8", event.getBody()); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testGenDfoChain() { String[] chain = {"host1", "host2", "host3"}; String expected = "< host1:host2:host3 ? diskFailover insistentAppend stubbornAppend insistentOpen host1:host2:host3 >"; String result = AgentFailChainSink.genDfoChain(chain); assertEquals(expected, result); }
@Test public void testDropUntilNewLine() { ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.put("Hello\nWorld".getBytes()); buffer.flip(); assertFalse(ExecNioSource.dropUntilNewLine(buffer)); buffer.put("Hello World".getBytes()); buffer.flip(); assertTrue(ExecNioSource.dropUntilNewLine(buffer)); }
@Test public void testCreateClient() throws IOException { ZooKeeperService zooKeeperService = new ZooKeeperService(); ZKClient zkClient = zooKeeperService.createClient(); assertNotNull(zkClient); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testDiskFailoverDeco() { Context context = new Context(); context.put(LogicalNodeContext.C_LOGICAL, "testNode"); DiskFailoverManager dfoman = new DiskFailoverManager(); RollTrigger t = new TimeTrigger(new ProcessTagger(), 1000); long checkmillis = 500; EventSink sink = new StdoutEventSink(); DiskFailoverDeco deco = new DiskFailoverDeco(sink, context, dfoman, t, checkmillis); assertNotNull(deco); }
@Test public void testFixedRetryPolicy() { int numRetries = 3; FixedRetryPolicy policy = new FixedRetryPolicy(numRetries); assertEquals(numRetries, policy.getNumRetries()); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testOr() { PatternMatch p1 = new PatternMatch(PatternType.WILDCARD); PatternMatch p2 = new PatternMatch(PatternType.LITERAL, "hello"); PatternMatch p3 = new PatternMatch(PatternType.REGEX, "[0-9]+"); PatternMatch p4 = new PatternMatch(PatternType.LITERAL, "world"); PatternMatch p5 = new PatternMatch(PatternType.REGEX, "[a-z]+"); PatternMatch result = PatternMatch.or(p1, p2, p3, p4, p5); assertEquals(PatternType.OR, result.getType()); assertArrayEquals(new Object[]{p1, p2, p3, p4, p5}, result.getArgs()); }
@Test public void testReorderDecorator() { Context context = new Context(); String[] argv = {"0.5", "0.5"}; ReorderDecorator<EventSink> reorderDecorator = ReorderDecorator.builder().build(context, argv); assertNotNull(reorderDecorator); assertEquals(0.5, reorderDecorator.getYank(), 0.0); assertEquals(0.5, reorderDecorator.getSpew(), 0.0); }
@Test public void testChild() { PatternMatch parent = new PatternMatch(PatternType.PARENT); PatternMatch child = new PatternMatch(PatternType.CHILD); PatternMatch patternMatch = parent.child(child); assertNotNull(patternMatch); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testTailDirSource() { File file = new File("test.txt"); String regex = ".*"; boolean startFromEnd = true; int recurseDepth = 2; String delimRegex = "\\n"; DelimMode delimMode = DelimMode.DISABLED; TailDirSource tailDirSource = new TailDirSource(file, regex, startFromEnd, recurseDepth, delimRegex, delimMode); assertNotNull(tailDirSource); }
@Test public void testAppend() throws IOException, InterruptedException { EventSinkImpl sink = new EventSinkImpl(); FormatterDecorator decorator = new FormatterDecorator(sink, "Test format string: %s"); Event event = new EventImpl("Test event".getBytes(), System.currentTimeMillis(), 1, 0, "localhost"); decorator.append(event); assertEquals("Test format string: Test event", new String(sink.getEvents().get(0).getBody())); }
@Test public void testSetConfig() throws IOException { MemoryBackedConfigStore store = new MemoryBackedConfigStore(); String host = "localhost"; String flowid = "testFlow"; String source = "testSource"; String sink = "testSink"; store.setConfig(host, flowid, source, sink); FlumeConfigData configData = store.cfgs.get(host); assertNotNull(configData); assertEquals(flowid, configData.flowID); assertEquals(source, configData.sourceName); assertEquals(sink, configData.sinkName); }
@Test public void testTextFileSink() { String fileName = "test.txt"; OutputFormat format = OutputFormat.JSON; TextFileSink textFileSink = new TextFileSink(fileName, format); assertEquals(format, textFileSink.getFormat()); }
@Test public void testToText() throws IOException { StringWriter writer = new StringWriter(); Map<String, Long> longMetrics = new HashMap<>(); longMetrics.put("metric1", 10L); Map<String, String> stringMetrics = new HashMap<>(); stringMetrics.put("metric2", "value2"); Map<String, Double> doubleMetrics = new HashMap<>(); doubleMetrics.put("metric3", 3.14); ReportEvent event = new ReportEvent(longMetrics, stringMetrics, doubleMetrics); event.toText(writer); String expected = "ReportEvent{longMetrics={metric1=10}, stringMetrics={metric2=value2}, doubleMetrics={metric3=3.14}}"; assertEquals(expected, writer.toString()); }
@Test public void testEscapeString() { Event event = new Event(); String input = "This is a <b>bold</b> statement."; String expectedOutput = "This is a bold statement."; assertEquals(expectedOutput, event.escapeString(input)); }
@Test public void testGet() { FlumeConfiguration config1 = FlumeConfiguration.get(); FlumeConfiguration config2 = FlumeConfiguration.get(); assertNotNull(config1); assertNotNull(config2); assertSame(config1, config2); }
@Test public void testGenArg() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.HEX.name())); tree.getChild(0).addChild(new CommonTree("0x123")); String result = FlumeSpecGen.genArg(tree); assertEquals("0x123", result); }
@Test public void testReorderDecorator() { Context context = new Context(); String[] argv = {"0.5", "0.5"}; ReorderDecorator<EventSink> reorderDecorator = ReorderDecorator.builder().build(context, argv); assertNotNull(reorderDecorator); assertEquals(0.5, reorderDecorator.getYank(), 0.0); assertEquals(0.5, reorderDecorator.getSpew(), 0.0); }
@Test public void testAppend() throws IOException, InterruptedException { EventSinkDecorator<S> mockSink = mock(EventSinkDecorator.class); DigestDecorator<S> digestDecorator = new DigestDecorator<>(mockSink, "SHA-256", "digest", true); Event event = new Event(); event.setBody("test".getBytes()); digestDecorator.append(event); verify(mockSink).append(argThat(argument -> { return argument.getBody().equals("test".getBytes()) && argument.get("digest").equals(Base64.encodeBase64String(MessageDigest.getInstance("SHA-256").digest("test".getBytes()))); })); }
@Test public void testClose() throws IOException { HBaseSink hBaseSink = new HBaseSink("tableName", "rowkey", new ArrayList<>()); hBaseSink.close(); assertNull(hBaseSink.table); }
@Test public void testSetPort() { FlumeLog4jAvroAppender appender = new FlumeLog4jAvroAppender(); appender.setPort(1234); assertEquals(1234, appender.getPort()); }
@Test public void testContainsTag() { assertTrue(Event.containsTag("#tag")); assertFalse(Event.containsTag("not a tag")); assertTrue(Event.containsTag("multiple #tags in #string")); assertFalse(Event.containsTag("")); }
@Test public void testCollectorSinkBuilder() { Context context = new Context(); String snkSpec = "testSink"; long millis = 1000L; AckListener ackListener = new AckListener() { @Override public void acknowledge(AckEvent event) { } }; CollectorSink collectorSink = new CollectorSink(context, snkSpec, millis, ackListener); assertNotNull(collectorSink); }
@Test public void testNth() { PatternMatch parent = new PatternMatch(PatternType.PARENT); PatternMatch child = new PatternMatch(PatternType.CHILD); PatternMatch result = parent.nth(2, child); assertEquals(PatternType.PARENT_NTH, result.getType()); assertEquals(parent, result.getArgs()[0]); assertEquals(child, result.getArgs()[1]); assertEquals(2, result.getArgs()[2]); }
@Test public void testGenBestEffortChain() { String[] chain = {"host1", "host2", "host3"}; String expectedSpec = "{ lazyOpen => { stubbornAppend => [host1, host2, host3] } }"; String actualSpec = AgentFailChainSink.genBestEffortChain(chain); assertEquals(expectedSpec, actualSpec); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testBuildPeriodic() { Context ctx = mock(Context.class); String[] argv = {"ls -l", "5000"}; EventSource source = ExecNioSource.buildPeriodic().build(ctx, argv); assertNotNull(source); assertTrue(source instanceof ExecNioSource); assertEquals("ls -l", ((ExecNioSource) source).command); assertTrue(((ExecNioSource) source).aggregate); assertTrue(((ExecNioSource) source).restart); assertEquals(5000, ((ExecNioSource) source).period); }
@Test public void testSetConfig() throws IOException { MemoryBackedConfigStore store = new MemoryBackedConfigStore(); String host = "localhost"; String flowid = "testFlow"; String source = "testSource"; String sink = "testSink"; store.setConfig(host, flowid, source, sink); FlumeConfigData configData = store.cfgs.get(host); assertNotNull(configData); assertEquals(flowid, configData.flowID); assertEquals(source, configData.sourceName); assertEquals(sink, configData.sinkName); }
@Test public void testAppend() throws IOException, InterruptedException { EventSinkDecorator mockSink = mock(EventSinkDecorator.class); ValueDecorator decorator = new ValueDecorator(mockSink, "attribute", "value", true); Event mockEvent = mock(Event.class); decorator.append(mockEvent); verify(mockEvent).set("attribute", "value".getBytes()); verify(mockSink).append(mockEvent); }
@Test public void testEscapeString() { Event event = new Event(); String input = "This is a <b>bold</b> statement."; String expectedOutput = "This is a bold statement."; assertEquals(expectedOutput, event.escapeString(input)); }
@Test public void testGenArg() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.HEX.name())); tree.getChild(0).addChild(new CommonTree("0x123")); String result = FlumeSpecGen.genArg(tree); assertEquals("0x123", result); }
@Test public void testOpen() throws IOException { DiskFailoverManager dfMan = new DiskFailoverManager(); DiskFailoverSource diskFailoverSource = new DiskFailoverSource(dfMan); diskFailoverSource.open(); assertTrue(dfMan.isOpen()); }
@Test public void testReorderDecorator() { EventSink mockSink = Mockito.mock(EventSink.class); ReorderDecorator reorderDecorator = new ReorderDecorator(mockSink, 0.5, 0.3, 12345L); assertEquals(0.5, reorderDecorator.yank, 0.0); assertEquals(0.3, reorderDecorator.spew, 0.0); assertNotNull(reorderDecorator.rand); assertEquals(mockSink, reorderDecorator.parent); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testExec() throws MasterExecException, IOException { CommandManager cm = new CommandManager(); Command cmd = new Command("test", new String[]{"arg1", "arg2"}); Execable ex = mock(Execable.class); when(ex.exec(cmd.getArgs())).thenReturn(true); Map<String, Execable> cmds = new HashMap<>(); cmds.put("test", ex); Whitebox.setInternalState(cm, "cmds", cmds); cm.exec(cmd); verify(ex, times(1)).exec(cmd.getArgs()); }
@Test public void testGetReportByName() throws AvroRemoteException { AvroReportServer avroReportServer = new AvroReportServer(new FlumeConfiguration()); CharSequence reportName = "testReport"; AvroFlumeReport expectedReport = avroReportServer.reportToAvro(new HashMap<String, String>()); AvroFlumeReport actualReport = avroReportServer.getReportByName(reportName); assertEquals(expectedReport, actualReport); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testToFlumeEvent() { AvroFlumeEvent avroFlumeEvent = new AvroFlumeEvent(); Event event = AvroEventConvertUtil.toFlumeEvent(avroFlumeEvent); assertNotNull(event); }
@Test public void testMerge() { Map<String, Long> longMetrics1 = new HashMap<>(); longMetrics1.put("metric1", 10L); Map<String, String> stringMetrics1 = new HashMap<>(); stringMetrics1.put("metric2", "value2"); Map<String, Double> doubleMetrics1 = new HashMap<>(); doubleMetrics1.put("metric3", 3.14); ReportEvent event1 = new ReportEvent(longMetrics1, stringMetrics1, doubleMetrics1); Map<String, Long> longMetrics2 = new HashMap<>(); longMetrics2.put("metric4", 20L); Map<String, String> stringMetrics2 = new HashMap<>(); stringMetrics2.put("metric5", "value5"); Map<String, Double> doubleMetrics2 = new HashMap<>(); doubleMetrics2.put("metric6", 6.28); ReportEvent event2 = new ReportEvent(longMetrics2, stringMetrics2, doubleMetrics2); event1.merge(event2); assertEquals(2, event1.getLongMetrics().size()); assertEquals(2, event1.getStringMetrics().size()); assertEquals(2, event1.getDoubleMetrics().size()); assertEquals(20L, (long) event1.getLongMetrics().get("metric4")); assertEquals("value5", event1.getStringMetrics().get("metric5")); assertEquals(6.28, event1.getDoubleMetrics().get("metric6"), 0.0); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testToHtml() throws IOException { StringWriter writer = new StringWriter(); ReportEvent event = new ReportEvent("localhost"); event.setStringMetric("status", "OK"); event.setLongMetric("responseTime", 100L); event.setDoubleMetric("cpuUsage", 0.75); event.toHtml(writer); String expectedOutput = "<table><tr><th>host</th><td>localhost</td></tr><tr><th>cpuUsage</th><td><div class=\"cpuUsage\">0.75</div></td></tr><tr><th>responseTime</th><td><div class=\"responseTime\">100</div></td></tr><tr><th>status</th><td><div class=\"status\">OK</div></td></tr></table>"; assertEquals(expectedOutput, writer.toString()); }
@Test public void testCheckup() { FlumeConfiguration flumeConfig = mock(FlumeConfiguration.class); when(flumeConfig.getMasterMaxMissedheartbeats()).thenReturn(3); when(flumeConfig.getConfigHeartbeatPeriod()).thenReturn(1000L); FlumeMaster flumeMaster = mock(FlumeMaster.class); when(flumeMaster.getSpecMan()).thenReturn(mock(SpecificationMananger.class)); StatusManager statusManager = new StatusManager(flumeConfig, flumeMaster); HashMap<String, NodeStatus> statuses = new HashMap<>(); NodeStatus nodeStatus1 = new NodeStatus(); nodeStatus1.lastseen = Clock.unixTime() - 4000L; nodeStatus1.physicalNode = "node1"; nodeStatus1.state = NodeState.ACTIVE; statuses.put("node1", nodeStatus1); NodeStatus nodeStatus2 = new NodeStatus(); nodeStatus2.lastseen = Clock.unixTime() - 2000L; nodeStatus2.physicalNode = "node2"; nodeStatus2.state = NodeState.ACTIVE; statuses.put("node2", nodeStatus2); NodeStatus nodeStatus3 = new NodeStatus(); nodeStatus3.lastseen = Clock.unixTime() - 1000L; nodeStatus3.physicalNode = "node3"; nodeStatus3.state = NodeState.ACTIVE; statuses.put("node3", nodeStatus3); Field field = StatusManager.class.getDeclaredField("statuses"); field.setAccessible(true); field.set(statusManager, statuses); statusManager.checkup(); assertEquals(NodeState.LOST, nodeStatus1.state); assertEquals(NodeState.DECOMMISSIONED, nodeStatus2.state); assertEquals(NodeState.ACTIVE, nodeStatus3.state); }
@Test public void testFindHostIndex() throws UnknownHostException, SocketException { String[] hosts = {"localhost", "google.com", "example.com"}; int expectedIndex = 0; int actualIndex = NetUtils.findHostIndex(hosts); assertEquals(expectedIndex, actualIndex); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testParseSink() throws RecognitionException { String sink = "agent1.sink1.type = avro"; CommonTree ast = FlumeBuilder.parseSink(sink); assertNotNull(ast); assertEquals(FlumeDeployParser.SINK, ast.getType()); assertEquals("agent1.sink1", ast.getChild(0).getText()); assertEquals("avro", ast.getChild(1).getChild(0).getText()); }
@Test public void testTextFileSink() { String fileName = "test.txt"; OutputFormat format = OutputFormat.JSON; TextFileSink textFileSink = new TextFileSink(fileName, format); assertEquals(format, textFileSink.getFormat()); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testGetMasterZKServers() { FlumeConfiguration flumeConfig = new FlumeConfiguration(true); flumeConfig.set(MASTER_ZK_SERVERS, "localhost:2181"); String expected = "localhost:2181"; String result = flumeConfig.getMasterZKServers(); assertEquals(expected, result); }
@Test public void testGetMasterIsDistributed() { FlumeConfiguration flumeConfig = new FlumeConfiguration(true); flumeConfig.setMasterServers("localhost:1234,localhost:5678"); assertTrue(flumeConfig.getMasterIsDistributed()); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testClose() throws IOException { HBaseSink hBaseSink = new HBaseSink("tableName", "rowkey", new ArrayList<>()); hBaseSink.close(); assertNull(hBaseSink.table); }
@Test public void testGetDriver() { Context ctx = new Context(); String name = "testNode"; LogicalNode node = new LogicalNode(ctx, name); Driver driver = node.getDriver(); assertNotNull(driver); }
@Test public void testParseHost() throws RecognitionException { String s = "localhost:1234"; CommonTree expected = new CommonTree(); expected.addChild(new CommonTree(new CommonToken(0, "localhost"))); expected.addChild(new CommonTree(new CommonToken(0, "1234"))); CommonTree result = FlumeBuilder.parseHost(s); assertEquals(expected.toStringTree(), result.toStringTree()); }
@Test public void testToFlumeEvent() { ThriftFlumeEvent evt = new ThriftFlumeEvent(); Event result = ThriftEventConvertUtil.toFlumeEvent(evt); assertNotNull(result); }
@Test public void testBuildSink() throws FlumeSpecException { Context context = new Context(); String s = "someSink"; EventSink eventSink = FlumeBuilder.buildSink(context, s); assertNotNull(eventSink); }
@Test public void testExtractLines() throws InterruptedException { ByteBuffer buf = ByteBuffer.allocate(1024); String command = "test command"; String tag = "test tag"; BlockingQueue<Event> sync = new LinkedBlockingQueue<>(); buf.put("test line 1\n".getBytes()); buf.put("test line 2\n".getBytes()); buf.put("test line 3\n".getBytes()); buf.put("test line 4\n".getBytes()); buf.put("test line 5\n".getBytes()); buf.flip(); boolean result = ExecNioSource.extractLines(buf, command, tag, sync); assertTrue(result); assertEquals(5, sync.size()); }
@Test public void testUpdateAll() throws IOException { ConfigurationManager parent = mock(ConfigurationManager.class); ConfigurationManager self = mock(ConfigurationManager.class); TranslatingConfigurationManager tcm = new TranslatingConfigurationManager(parent, self); Map<String, FlumeConfigData> translatedConfigs = new HashMap<>(); FlumeConfigData fcd = new FlumeConfigData(); fcd.setSourceConfig("sourceConfig"); fcd.setSinkConfig("sinkConfig"); translatedConfigs.put("node1", fcd); when(parent.getTranslatedConfigs()).thenReturn(translatedConfigs); when(self.getConfig(anyString())).thenReturn(null); tcm.updateAll(); verify(parent, times(1)).updateAll(); verify(self, times(1)).setBulkConfig(anyMap()); }
@Test public void testGenE2EChain() { String[] chain = {"host1", "host2", "host3"}; String expectedSpec = "{ ackedWriteAhead => { stubbornAppend => { insistentOpen => " + FailoverChainManager.genAvailableSinkSpec(" %s ", Arrays.asList(chain)) + " } } }"; String actualSpec = AgentFailChainSink.genE2EChain(chain); assertEquals(expectedSpec, actualSpec); Context context = new Context(); RELIABILITY rel = RELIABILITY.AT_LEAST_ONCE; String[] hosts = {"host1", "host2", "host3"}; AgentFailChainSink agentFailChainSink = new AgentFailChainSink(context, rel, hosts); assertNotNull(agentFailChainSink); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testGenEventSink() throws FlumeSpecException { CommonTree tree = new CommonTree(); tree.addChild(new CommonTree(ASTNODE.SINK.name())); CommonTree child1 = new CommonTree("type1"); CommonTree child2 = new CommonTree("arg1"); CommonTree child3 = new CommonTree("arg2"); tree.addChild(child1); tree.addChild(child2); tree.addChild(child3); String expected = "type1(arg1,arg2)"; String result = FlumeSpecGen.genEventSink(tree); assertEquals(expected, result); }
@Test public void testPing() { StatusController statusController = new StatusController(new Ping()); Long result = statusController.ping(); assertNotNull(result); }
@Test public void testListStrategies() { TurbineService turbineService = new TurbineService(); String result = turbineService.listStrategies(); assertNotNull(result); }
@Test public void testGetName() { IndicatorInstance instance = new IndicatorInstance("ClassName", 1, 2, 3, true); ClientIndicator clientIndicator = new ClientIndicator(); clientIndicator.setName("TestName"); instance.setClientIndicator(clientIndicator); assertEquals("TestName", instance.getName()); }
@Test public void testFindIndicatorsByRic() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); List<IndicatorJson> indicators = service.findIndicatorsByRic("AAPL"); assertNotNull(indicators); assertFalse(indicators.isEmpty()); for (IndicatorJson indicator : indicators) { assertEquals("AAPL", indicator.getRic()); } }
@Test public void testFindTickersByExchange() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); ExchangeEnum exchange = ExchangeEnum.BITFINEX; List<Ticker> tickers = service.findTickersByExchange(exchange); assertNotNull(tickers); assertFalse(tickers.isEmpty()); for (Ticker ticker : tickers) { assertEquals(exchange.toString(), ticker.getExchange()); } }
@Test public void testGetIndicatorsAfter() throws Exception { IndicatorController controller = new IndicatorController(); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); String ric = "AAPL"; String name = "MACD"; Long date = 1622505600000L; mockMvc.perform(get("/{ric}/{name}/{date}", ric, name, date)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.indicators", hasSize(2))) .andExpect(jsonPath("$.indicators[0].name", is("MACD"))) .andExpect(jsonPath("$.indicators[0].value", is(12.34))) .andExpect(jsonPath("$.indicators[1].name", is("MACD"))) .andExpect(jsonPath("$.indicators[1].value", is(56.78))); }
@Test public void testFindIndicatorsByRicAndNameAndDateGreaterThan() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); String ric = "AAPL"; String name = "Apple Inc."; Long date = 1625097600000L; List<IndicatorJson> result = service.findIndicatorsByRicAndNameAndDateGreaterThan(ric, name, date); assertNotNull(result); assertFalse(result.isEmpty()); for (IndicatorJson indicator : result) { assertEquals(ric, indicator.getRic()); assertEquals(name, indicator.getName()); assertTrue(indicator.getDate() > date); } }
@Test public void testIsNumeric() { String numericString = "12345"; String nonNumericString = "abcde"; assertTrue(TurbineMatchers.isNumeric().matches(numericString)); assertFalse(TurbineMatchers.isNumeric().matches(nonNumericString)); }
@Test public void testCompareTo() { IndicatorInstance instance1 = new IndicatorInstance("com.example.Indicator1", 10, 20, 30, true); IndicatorInstance instance2 = new IndicatorInstance("com.example.Indicator2", 5, 10, 15, false); IndicatorInstance instance3 = new IndicatorInstance("com.example.Indicator3", 20, 40, 60, true); assertTrue(instance1.compareTo(instance2) > 0); assertTrue(instance2.compareTo(instance3) < 0); assertTrue(instance1.compareTo(instance3) < 0); }
@Test public void testFindTicks() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); String ticks = service.findTicks(); assertNotNull(ticks); assertTrue(ticks.startsWith("[")); assertTrue(ticks.endsWith("]")); }
@Test public void testFindTicksByRicAndDateGreaterThan() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); List<TickJson> ticks = service.findTicksByRicAndDateGreaterThan("AAPL", 1625097600000L); assertNotNull(ticks); assertFalse(ticks.isEmpty()); }
@Test public void testPing() throws Exception { TurbineController controller = new TurbineController(); PingResponse response = controller.ping(); assertNotNull(response); assertEquals("pong", response.getMessage()); }
@Test public void testListIndicators() { TurbineService turbineService = new TurbineService(); String result = turbineService.listIndicators(); assertNotNull(result); assertTrue(result.contains("indicators")); }
@Test public void testFindIndicatorsByRicAndDateGreaterThan() { ElasticsearchNativeServiceImpl service = new ElasticsearchNativeServiceImpl(); List<IndicatorJson> result = service.findIndicatorsByRicAndDateGreaterThan("AAPL", 1625097600000L); assertNotNull(result); assertFalse(result.isEmpty()); }
@Test public void testFindTicksByRic() { ElasticsearchService service = new ElasticsearchNativeServiceImpl(); List<TickJson> ticks = service.findTicksByRic("AAPL"); assertNotNull(ticks); assertFalse(ticks.isEmpty()); for (TickJson tick : ticks) { assertEquals("AAPL", tick.getRic()); } }
@Test public void testGetCount() { UnsafeCountingFactorizer factorizer = new UnsafeCountingFactorizer(); long count = factorizer.getCount(); assertEquals(0, count); }
@Test public void testThreeStoogesConstructor() { ThreeStooges threeStooges = new ThreeStooges(); List<String> expectedStooges = Arrays.asList("Moe", "Larry", "Curly"); assertEquals(expectedStooges, threeStooges.stooges); }
@Test public void testGetInstance() { LazyInitRace lazyInitRace = new LazyInitRace(); ExpensiveObject obj1 = lazyInitRace.getInstance(); ExpensiveObject obj2 = lazyInitRace.getInstance(); assertEquals(obj1, obj2); }
@Test public void testASecondOfPrimes() throws InterruptedException { List<BigInteger> expected = new ArrayList<>(); expected.add(new BigInteger("2")); expected.add(new BigInteger("3")); expected.add(new BigInteger("5")); expected.add(new BigInteger("7")); expected.add(new BigInteger("11")); expected.add(new BigInteger("13")); expected.add(new BigInteger("17")); expected.add(new BigInteger("19")); expected.add(new BigInteger("23")); expected.add(new BigInteger("29")); expected.add(new BigInteger("31")); expected.add(new BigInteger("37")); expected.add(new BigInteger("41")); expected.add(new BigInteger("43")); expected.add(new BigInteger("47")); expected.add(new BigInteger("53")); expected.add(new BigInteger("59")); expected.add(new BigInteger("61")); expected.add(new BigInteger("67")); expected.add(new BigInteger("71")); expected.add(new BigInteger("73")); expected.add(new BigInteger("79")); expected.add(new BigInteger("83")); expected.add(new BigInteger("89")); expected.add(new BigInteger("97")); List<BigInteger> actual = PrimeGenerator.aSecondOfPrimes(); assertEquals(expected, actual); }
@Test public void testNoVisibility() throws InterruptedException { Thread thread = new Thread(() -> { while (!ready) { Thread.yield(); } assertEquals(42, number); }); thread.start(); number = 42; ready = true; thread.join(); }
@Test public void testGetCount() { CountingFactorizer countingFactorizer = new CountingFactorizer(); long expectedCount = 0; long actualCount = countingFactorizer.getCount(); assertEquals(expectedCount, actualCount); }
@Test public void testStartIndexing() throws InterruptedException { File[] roots = new File[] { new File("path/to/root1"), new File("path/to/root2") }; ProducerConsumer.startIndexing(roots); Thread.sleep(5000); }
@Test public void testHolderConstructor() { Holder holder = new Holder(10); assertEquals(10, holder.n); }
@Test public void testGetNext() { Sequence sequence = new Sequence(); int firstValue = sequence.getNext(); int secondValue = sequence.getNext(); assertEquals(firstValue + 1, secondValue); }
@Test public void testOutOfTime() throws Exception { Timer timer = new Timer(); timer.schedule(new ThrowTask(), 1); TimeUnit.SECONDS.sleep(1); timer.schedule(new ThrowTask(), 1); TimeUnit.SECONDS.sleep(5); }
@Test public void testUnsafeSequence() { UnsafeSequence sequence = new UnsafeSequence(); assertEquals(0, sequence.getNext()); assertEquals(1, sequence.getNext()); assertEquals(2, sequence.getNext()); }
@Test public void testCreateReasoner() { AxiomLoader.Factory axiomLoaderFactory = mock(AxiomLoader.Factory.class); ReasonerFactory reasonerFactory = new ReasonerFactory(); Reasoner reasoner = reasonerFactory.createReasoner(axiomLoaderFactory); assertNotNull(reasoner); }
@Test public void testLoad() throws ElkLoadingException { Owl2Parser owlParser = mock(Owl2Parser.class); InterruptMonitor interrupter = mock(InterruptMonitor.class); ElkAxiomProcessor axiomInserter = mock(ElkAxiomProcessor.class); ElkAxiomProcessor axiomDeleter = mock(ElkAxiomProcessor.class); Owl2ParserLoader parserLoader = new Owl2ParserLoader(interrupter, owlParser); parserLoader.load(axiomInserter, axiomDeleter); verify(owlParser, times(1)).parse(); verify(axiomInserter, times(0)).visit(any(ElkAxiom.class)); verify(axiomDeleter, times(0)).visit(any(ElkAxiom.class)); }
@Test public void testGetGoal() { Reasoner reasoner = new Reasoner(); OWLAxiom goal = new OWLAxiom(); OwlInternalProof proof = new OwlInternalProof(reasoner, goal); assertEquals(goal, proof.getGoal()); }
@Test public void testGetGoal() { Reasoner reasoner = new Reasoner(); OWLAxiom goal = new OWLAxiom(); OwlInternalProof proof = new OwlInternalProof(reasoner, goal); assertEquals(goal, proof.getGoal()); }
@Test public void testLoad() throws ElkLoadingException { Owl2Parser owlParser = mock(Owl2Parser.class); InterruptMonitor interrupter = mock(InterruptMonitor.class); ElkAxiomProcessor axiomInserter = mock(ElkAxiomProcessor.class); ElkAxiomProcessor axiomDeleter = mock(ElkAxiomProcessor.class); Owl2ParserLoader parserLoader = new Owl2ParserLoader(interrupter, owlParser); parserLoader.load(axiomInserter, axiomDeleter); verify(owlParser, times(1)).parse(); verify(axiomInserter, times(0)).visit(any(ElkAxiom.class)); verify(axiomDeleter, times(0)).visit(any(ElkAxiom.class)); }
@Test public void testCreateReasoner() { AxiomLoader.Factory axiomLoaderFactory = mock(AxiomLoader.Factory.class); ReasonerFactory reasonerFactory = new ReasonerFactory(); Reasoner reasoner = reasonerFactory.createReasoner(axiomLoaderFactory); assertNotNull(reasoner); }
@Test public void testGetConfiguration() throws ConfigurationException { ConfigurationFactory factory = new ConfigurationFactory(); BaseConfiguration config = factory.getConfiguration("prefix", BaseConfiguration.class); assertNotNull(config); }
@Test public void testGetConfiguration() throws ConfigurationException { ConfigurationFactory factory = new ConfigurationFactory(); BaseConfiguration config = factory.getConfiguration("prefix", BaseConfiguration.class); assertNotNull(config); }
@Test public void testGetConfiguration() throws ConfigurationException { ConfigurationFactory factory = new ConfigurationFactory(); BaseConfiguration config = factory.getConfiguration("prefix", BaseConfiguration.class); assertNotNull(config); }
@Test public void testGetARModes() { AspectModeManager aspectModeManager = new AspectModeManager(); String[] expectedModes = {"mode1", "mode2", "mode3"}; String[] actualModes = aspectModeManager.getARModes(); assertArrayEquals(expectedModes, actualModes); }
@Test public void testTranslate() { RectangleF src = new RectangleF(0, 0, 10, 10); RectangleF dest = new RectangleF(20, 20, 10, 10); RectangleF rect = new RectangleF(5, 5, 5, 5); rect.translate(src, dest); assertEquals(25.0f, rect.getX(), 0.0f); assertEquals(25.0f, rect.getY(), 0.0f); assertEquals(2.5f, rect.getWidth(), 0.0f); assertEquals(2.5f, rect.getHeight(), 0.0f); }
@Test public void testFitInside() { RectangleF src = new RectangleF(0, 0, 10, 10); RectangleF dest = new RectangleF(0, 0, 20, 20); RectangleF result = AspectHelper.fitInside(src, dest); assertEquals(5.0f, result.width, 0.0f); assertEquals(5.0f, result.height, 0.0f); assertEquals(7.5f, result.x, 0.0f); assertEquals(7.5f, result.y, 0.0f); }
@Test public void testRead() throws IOException { SimplePullDataSource dataSource = new SimplePullDataSource(); byte[] buffer = new byte[10]; int offset = 0; int len = 5; int result = dataSource.read(0, buffer, offset, len); assertEquals(-1, result); }
@Test public void testRead() throws IOException { SimplePullDataSource dataSource = new SimplePullDataSource(); byte[] buffer = new byte[10]; int offset = 0; int len = 5; int result = dataSource.read(0, buffer, offset, len); assertEquals(-1, result); }
@Test public void testZoom() { RectangleF src = new RectangleF(0, 0, 100, 100); float ar = 1.5f; RectangleF expected = new RectangleF(12.5f, 0, 75, 100); RectangleF result = AspectHelper.zoom(src, ar); assertEquals(expected, result); }
@Test public void testFitHeight() { RectangleF src = new RectangleF(0, 0, 10, 20); RectangleF dest = new RectangleF(0, 0, 30, 60); RectangleF expected = new RectangleF(0, 0, 15, 30); RectangleF result = AspectHelper.fitHeight(src, dest); assertEquals(expected, result); }
@Test public void testReadBuffer() throws IOException { byte[] buffer = new byte[10]; int offset = 0; int len = 5; SimplePullDataSource dataSource = new SimplePullDataSource(); int result = dataSource.readBuffer(buffer, offset, len); assertEquals(-1, result); }
@Test public void testFitInside() { RectangleF src = new RectangleF(0, 0, 10, 10); RectangleF dest = new RectangleF(0, 0, 20, 20); RectangleF result = AspectHelper.fitInside(src, dest); assertEquals(5.0f, result.width, 0.0f); assertEquals(5.0f, result.height, 0.0f); assertEquals(7.5f, result.x, 0.0f); assertEquals(7.5f, result.y, 0.0f); }
@Test public void testScale() { RectangleF rectangle = new RectangleF(0, 0, 10, 20); rectangle.scale(2); assertEquals(20, rectangle.width, 0.001); assertEquals(40, rectangle.height, 0.001); }
@Test public void testFitWidth() { RectangleF src = new RectangleF(0, 0, 10, 20); RectangleF dest = new RectangleF(0, 0, 30, 40); RectangleF result = AspectHelper.fitWidth(src, dest); assertEquals(30.0f, result.width, 0.001f); assertEquals(60.0f, result.height, 0.001f); assertEquals(0.0f, result.x, 0.001f); assertEquals(10.0f, result.y, 0.001f); }
@Test public void testStretch() { RectangleF src = new RectangleF(0, 0, 4, 3); float ar = 16/9f; RectangleF expected = new RectangleF(-1, 0, 6, 3); RectangleF actual = AspectHelper.stretch(src, ar); assertEquals(expected, actual); }
@Test public void testDoMeasureSource() { VideoInfo videoInfo = new VideoInfo(new Size(1920, 1080), 1.777f); RectangleF screen = new RectangleF(0, 0, 1280, 720); AspectModeManager aspectModeManager = new AspectModeManager(); RectangleF result = aspectModeManager.doMeasureSource(videoInfo, screen); assertEquals(new RectangleF(0, 0, 1280, 720), result); }
@Test public void testZoom() { RectangleF src = new RectangleF(0, 0, 100, 100); float ar = 1.5f; RectangleF expected = new RectangleF(12.5f, 0, 75, 100); RectangleF result = AspectHelper.zoom(src, ar); assertEquals(expected, result); }
@Test public void testReadBuffer() throws IOException { byte[] buffer = new byte[10]; int offset = 0; int len = 5; SimplePullDataSource dataSource = new SimplePullDataSource(); int result = dataSource.readBuffer(buffer, offset, len); assertEquals(-1, result); }
@Test public void testRead() throws IOException { BufferedPullDataSource dataSource = new BufferedPullDataSource(); byte[] buffer = new byte[10]; int read = dataSource.read(0, buffer, 0, 10); assertEquals(-1, read); }
@Test public void testGetHost() { SimplePullDataSource dataSource = new SimplePullDataSource("localhost"); String uri = "stv: String expectedHost = "localhost"; String actualHost = dataSource.getHost(uri); assertEquals(expectedHost, actualHost); }
@Test public void testDoMeasure() { VideoInfo info = new VideoInfo(); info.size = new SizeF(1920, 1080); info.aspectMode = "Stretch"; RectangleF uiSize = new RectangleF(0, 0, 1280, 720); float uiAR = 16f/9f; AspectModeManager manager = new AspectModeManager(); RectangleF result = manager.doMeasure(info, uiSize, uiAR); assertEquals(1280f, result.width, 0.01); assertEquals(720f, result.height, 0.01); }
@Test public void testStretch() { RectangleF src = new RectangleF(0, 0, 4, 3); float ar = 16/9f; RectangleF expected = new RectangleF(-1, 0, 6, 3); RectangleF actual = AspectHelper.stretch(src, ar); assertEquals(expected, actual); }
@Test public void testGetPath() { SimplePullDataSource dataSource = new SimplePullDataSource(); String uri = "stv: String expectedPath = "shows/123"; String actualPath = dataSource.getPath(uri); assertEquals(expectedPath, actualPath); }
@Test public void testEquals() { RectangleF r1 = new RectangleF(1.0f, 2.0f, 3.0f, 4.0f); RectangleF r2 = new RectangleF(1.0f, 2.0f, 3.0f, 4.0f); RectangleF r3 = new RectangleF(1.0f, 2.0f, 3.0f, 4.0001f); RectangleF r4 = new RectangleF(); assertTrue(r1.equals(r2)); assertFalse(r1.equals(r3)); assertFalse(r1.equals(r4)); assertTrue(r4.equals(new RectangleF())); }
@Test public void testCenter() { RectangleF dest = new RectangleF(0, 0, 10, 10); RectangleF rect = new RectangleF(2, 2, 4, 4); RectangleF expected = new RectangleF(3, 3, 4, 4); RectangleF actual = rect.center(dest); assertEquals(expected.x, actual.x, 0.0); assertEquals(expected.y, actual.y, 0.0); assertEquals(expected.width, actual.width, 0.0); assertEquals(expected.height, actual.height, 0.0); }
@Test public void testDoMeasureSource() { VideoInfo videoInfo = new VideoInfo(new Size(1920, 1080), 1.777f); RectangleF screen = new RectangleF(0, 0, 1280, 720); AspectModeManager aspectModeManager = new AspectModeManager(); RectangleF result = aspectModeManager.doMeasureSource(videoInfo, screen); assertEquals(new RectangleF(0, 0, 1280, 720), result); }
@Test public void testSendAck() { Context context = mock(Context.class); Intent response = new Intent(); response.setAction("com.example.ACTION"); response.putExtra("key", "value"); Ack ack = new Ack(); ack.sendAck(context, response); verify(context).sendBroadcast(any(Intent.class)); }
@Test public void testStartRequest() { Context context = mock(Context.class); String rationale = "Need permission to access location"; PermissionRequest permissionRequest = new PermissionRequest(mock(RequestParams.class)); permissionRequest.startRequest(context, rationale); assertNotNull(permissionRequest.getPayload()); }
@Test public void testIsIntentFromPermissionNanny() throws NannyException { Intent intent = new Intent(); Bundle bundle = new Bundle(); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, new Intent(getContext(), MainActivity.class), 0); bundle.putParcelable(Nanny.SENDER_IDENTITY, pendingIntent); intent.putExtra(Nanny.ENTITY_BODY, bundle); assertTrue(Nanny.isIntentFromPermissionNanny(intent)); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); ContentResolver mockContentResolver = mock(ContentResolver.class); Cursor mockCursor = mock(Cursor.class); Bundle mockBundle = mock(Bundle.class); ContentRequest mockContentRequest = mock(ContentRequest.class); ContentListener mockContentListener = mock(ContentListener.class); Uri mockUri = mock(Uri.class); when(mockIntent.getIntExtra(eq(Nanny.STATUS_CODE), anyInt())).thenReturn(Nanny.SC_OK); when(mockIntent.getBundleExtra(eq(Nanny.ENTITY_BODY))).thenReturn(mockBundle); when(mockBundle.getLong(eq(ContentRequest.SELECT), anyLong())).thenReturn(123L); when(mockContentRequest.opCode).thenReturn(ContentRequest.SELECT); when(mockContext.getContentResolver()).thenReturn(mockContentResolver); when(mockContentResolver.query(eq(mockUri), eq(null), eq(null), eq(null), eq(null))).thenReturn(mockCursor); ContentEvent contentEvent = new ContentEvent(mockContentRequest, mockContentListener); contentEvent.process(mockContext, mockIntent); verify(mockContentResolver).query(eq(mockUri), eq(null), eq(null), eq(null), eq(null)); verify(mockContentListener).onResponse(eq(mockIntent.getExtras()), eq(mockCursor)); }
@Test public void testOnReceive() { PermissionReceiver permissionReceiver = new PermissionReceiver(); Context context = mock(Context.class); Intent intent = mock(Intent.class); Nanny nanny = mock(Nanny.class); Map<String, EventFilter> eventFilters = mock(Map.class); EventFilter eventFilter = mock(EventFilter.class); when(intent.getStringExtra(Nanny.CONNECTION)).thenReturn(Nanny.CLOSE); when(intent.getStringExtra(Nanny.SERVER)).thenReturn("server"); when(nanny.CLOSE).thenReturn(Nanny.CLOSE); when(nanny.SERVER).thenReturn(Nanny.SERVER); when(eventFilters.get("server")).thenReturn(eventFilter); permissionReceiver.mEventFilters = eventFilters; permissionReceiver.onReceive(context, intent); verify(context).unregisterReceiver(permissionReceiver); verify(eventFilter).process(context, intent); }
@Test public void testIsIntentFromPermissionNanny() throws NannyException { Intent intent = new Intent(); Bundle bundle = new Bundle(); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, new Intent(getContext(), MainActivity.class), 0); bundle.putParcelable(Nanny.SENDER_IDENTITY, pendingIntent); intent.putExtra(Nanny.ENTITY_BODY, bundle); assertTrue(Nanny.isIntentFromPermissionNanny(intent)); }
@Test public void testGetRequestRationale() { Bundle bundle = new Bundle(); bundle.putString(Nanny.REQUEST_RATIONALE, "Test rationale"); NannyBundle nannyBundle = new NannyBundle(bundle); String rationale = nannyBundle.getRequestRationale(); assertEquals("Test rationale", rationale); }
@Test public void testStop() { Context context = mock(Context.class); BroadcastReceiver receiver = mock(BroadcastReceiver.class); NannyRequest nannyRequest = new NannyRequest(); nannyRequest.mReceiver = receiver; nannyRequest.stop(context); verify(context, times(1)).unregisterReceiver(receiver); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); ContentResolver mockContentResolver = mock(ContentResolver.class); Cursor mockCursor = mock(Cursor.class); Bundle mockBundle = mock(Bundle.class); ContentRequest mockContentRequest = mock(ContentRequest.class); ContentListener mockContentListener = mock(ContentListener.class); Uri mockUri = mock(Uri.class); when(mockIntent.getIntExtra(eq(Nanny.STATUS_CODE), anyInt())).thenReturn(Nanny.SC_OK); when(mockIntent.getBundleExtra(eq(Nanny.ENTITY_BODY))).thenReturn(mockBundle); when(mockBundle.getLong(eq(ContentRequest.SELECT), anyLong())).thenReturn(123L); when(mockContentRequest.opCode).thenReturn(ContentRequest.SELECT); when(mockContext.getContentResolver()).thenReturn(mockContentResolver); when(mockContentResolver.query(eq(mockUri), eq(null), eq(null), eq(null), eq(null))).thenReturn(mockCursor); ContentEvent contentEvent = new ContentEvent(mockContentRequest, mockContentListener); contentEvent.process(mockContext, mockIntent); verify(mockContentResolver).query(eq(mockUri), eq(null), eq(null), eq(null), eq(null)); verify(mockContentListener).onResponse(eq(mockIntent.getExtras()), eq(mockCursor)); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); Bundle mockBundle = mock(Bundle.class); NannyBundle mockNannyBundle = mock(NannyBundle.class); Parcelable[] mockParcels = mock(Parcelable[].class); Account[] mockAccounts = mock(Account[].class); OnAccountsUpdateListener mockListener = mock(OnAccountsUpdateListener.class); Handler mockHandler = mock(Handler.class); Ack mockAck = mock(Ack.class); when(mockNannyBundle.getEntityBody()).thenReturn(mockBundle); when(mockBundle.getParcelableArray(ACCOUNTS)).thenReturn(mockParcels); when(mockParcels.length).thenReturn(1); when(mockAccounts[0]).thenReturn(mock(Account.class)); doAnswer(invocation -> { Account[] accounts = invocation.getArgument(0); assertEquals(1, accounts.length); return null; }).when(mockListener).onAccountsUpdated(mockAccounts); AccountsUpdateEvent event = new AccountsUpdateEvent(mockListener, mockHandler, mockAck); event.process(mockContext, mockIntent); verify(mockAck).sendAck(mockContext, mockIntent); verify(mockNannyBundle).getEntityBody(); verify(mockBundle).getParcelableArray(ACCOUNTS); verify(mockHandler).post(any(Runnable.class)); verify(mockListener).onAccountsUpdated(mockAccounts); }
@Test public void testStartRequest() { Context context = mock(Context.class); BroadcastReceiver receiver = mock(BroadcastReceiver.class); IntentFilter filter = mock(IntentFilter.class); Intent payload = mock(Intent.class); String clientAddr = "testClientAddr"; NannyRequest nannyRequest = new NannyRequest(); nannyRequest.mReceiver = receiver; nannyRequest.mClientAddr = clientAddr; nannyRequest.mPaylaod = payload; when(Nanny.isPermissionNannyInstalled(context)).thenReturn(true); nannyRequest.startRequest(context); verify(context).registerReceiver(receiver, filter); verify(context).sendBroadcast(payload); }
@Test public void testStartRequest() { Context context = mock(Context.class); String rationale = "Need permission to access location"; PermissionRequest permissionRequest = new PermissionRequest(mock(RequestParams.class)); permissionRequest.startRequest(context, rationale); assertNotNull(permissionRequest.getPayload()); }
@Test public void testIsIntentFromPermissionNanny() throws NannyException { Intent intent = new Intent(); Bundle bundle = new Bundle(); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, new Intent(getContext(), MainActivity.class), 0); bundle.putParcelable(Nanny.SENDER_IDENTITY, pendingIntent); intent.putExtra(Nanny.ENTITY_BODY, bundle); assertTrue(Nanny.isIntentFromPermissionNanny(intent)); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); ContentResolver mockContentResolver = mock(ContentResolver.class); Cursor mockCursor = mock(Cursor.class); Bundle mockBundle = mock(Bundle.class); ContentRequest mockContentRequest = mock(ContentRequest.class); ContentListener mockContentListener = mock(ContentListener.class); Uri mockUri = mock(Uri.class); when(mockIntent.getIntExtra(eq(Nanny.STATUS_CODE), anyInt())).thenReturn(Nanny.SC_OK); when(mockIntent.getBundleExtra(eq(Nanny.ENTITY_BODY))).thenReturn(mockBundle); when(mockBundle.getLong(eq(ContentRequest.SELECT), anyLong())).thenReturn(123L); when(mockContentRequest.opCode).thenReturn(ContentRequest.SELECT); when(mockContext.getContentResolver()).thenReturn(mockContentResolver); when(mockContentResolver.query(eq(mockUri), eq(null), eq(null), eq(null), eq(null))).thenReturn(mockCursor); ContentEvent contentEvent = new ContentEvent(mockContentRequest, mockContentListener); contentEvent.process(mockContext, mockIntent); verify(mockContentResolver).query(eq(mockUri), eq(null), eq(null), eq(null), eq(null)); verify(mockContentListener).onResponse(eq(mockIntent.getExtras()), eq(mockCursor)); }
@Test public void testProcess() { AccountManagerCallback<String> callback = new AccountManagerCallback<String>() { @Override public void run(AccountManagerFuture<String> future) { } }; Handler handler = new Handler(); Class<String> type = String.class; AccountManagerEvent<String> event = new AccountManagerEvent<>(callback, handler, type); Context context = mock(Context.class); Intent intent = mock(Intent.class); Bundle bundle = new Bundle(); bundle.putString("CALLBACK", "test"); when(intent.getExtras()).thenReturn(bundle); event.process(context, intent); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); NmeaListener mockListener = mock(NmeaListener.class); Ack mockAck = mock(Ack.class); Bundle mockBundle = mock(Bundle.class); NmeaEvent nmeaEvent = new NmeaEvent(mockListener, mockAck); when(mockIntent.getExtras()).thenReturn(mockBundle); when(mockBundle.getLong(eq("timestamp"), anyLong())).thenReturn(123456789L); when(mockBundle.getString(eq("nmea"))).thenReturn("$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"); nmeaEvent.process(mockContext, mockIntent); verify(mockAck).sendAck(mockContext, mockIntent); verify(mockListener).onNmeaReceived(123456789L, "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); ContentResolver mockContentResolver = mock(ContentResolver.class); Cursor mockCursor = mock(Cursor.class); Bundle mockBundle = mock(Bundle.class); ContentRequest mockContentRequest = mock(ContentRequest.class); ContentListener mockContentListener = mock(ContentListener.class); Uri mockUri = mock(Uri.class); when(mockIntent.getIntExtra(eq(Nanny.STATUS_CODE), anyInt())).thenReturn(Nanny.SC_OK); when(mockIntent.getBundleExtra(eq(Nanny.ENTITY_BODY))).thenReturn(mockBundle); when(mockBundle.getLong(eq(ContentRequest.SELECT), anyLong())).thenReturn(123L); when(mockContentRequest.opCode).thenReturn(ContentRequest.SELECT); when(mockContext.getContentResolver()).thenReturn(mockContentResolver); when(mockContentResolver.query(eq(mockUri), eq(null), eq(null), eq(null), eq(null))).thenReturn(mockCursor); ContentEvent contentEvent = new ContentEvent(mockContentRequest, mockContentListener); contentEvent.process(mockContext, mockIntent); verify(mockContentResolver).query(eq(mockUri), eq(null), eq(null), eq(null), eq(null)); verify(mockContentListener).onResponse(eq(mockIntent.getExtras()), eq(mockCursor)); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); ContentResolver mockContentResolver = mock(ContentResolver.class); Cursor mockCursor = mock(Cursor.class); Bundle mockBundle = mock(Bundle.class); ContentRequest mockContentRequest = mock(ContentRequest.class); ContentListener mockContentListener = mock(ContentListener.class); Uri mockUri = mock(Uri.class); when(mockIntent.getIntExtra(eq(Nanny.STATUS_CODE), anyInt())).thenReturn(Nanny.SC_OK); when(mockIntent.getBundleExtra(eq(Nanny.ENTITY_BODY))).thenReturn(mockBundle); when(mockBundle.getLong(eq(ContentRequest.SELECT), anyLong())).thenReturn(123L); when(mockContentRequest.opCode).thenReturn(ContentRequest.SELECT); when(mockContext.getContentResolver()).thenReturn(mockContentResolver); when(mockContentResolver.query(eq(mockUri), eq(null), eq(null), eq(null), eq(null))).thenReturn(mockCursor); ContentEvent contentEvent = new ContentEvent(mockContentRequest, mockContentListener); contentEvent.process(mockContext, mockIntent); verify(mockContentResolver).query(eq(mockUri), eq(null), eq(null), eq(null), eq(null)); verify(mockContentListener).onResponse(eq(mockIntent.getExtras()), eq(mockCursor)); }
@Test public void testProcess() { Context mockContext = mock(Context.class); Intent mockIntent = mock(Intent.class); Bundle mockBundle = mock(Bundle.class); when(mockIntent.getExtras()).thenReturn(mockBundle); SimpleListener mockListener = mock(SimpleListener.class); PermissionEvent permissionEvent = new PermissionEvent(mockListener); permissionEvent.process(mockContext, mockIntent); verify(mockListener).onResponse(mockBundle); }
@Test public void testIsIntentFromPermissionNanny() throws NannyException { Intent intent = new Intent(); Bundle bundle = new Bundle(); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, new Intent(getContext(), MainActivity.class), 0); bundle.putParcelable(Nanny.SENDER_IDENTITY, pendingIntent); intent.putExtra(Nanny.ENTITY_BODY, bundle); assertTrue(Nanny.isIntentFromPermissionNanny(intent)); }
@Test public void testProcess() { GpsStatus.Listener listener = mock(GpsStatus.Listener.class); Ack ack = mock(Ack.class); GpsStatusEvent gpsStatusEvent = new GpsStatusEvent(listener, ack); Context context = mock(Context.class); Intent intent = mock(Intent.class); Bundle bundle = mock(Bundle.class); when(intent.getExtras()).thenReturn(bundle); when(bundle.getInt(eq(EVENT), anyInt())).thenReturn(1); gpsStatusEvent.process(context, intent); verify(ack).sendAck(context, intent); verify(listener).onGpsStatusChanged(1); }
@Test public void testMakeMock() { PowerMockitoMockMaker mockMaker = new PowerMockitoMockMaker(); TypeToken<String> typeToken = TypeToken.get(String.class); String mockString = mockMaker.makeMock(typeToken); assertNotNull(mockString); }
@Test public void testProvideMockMaker() { MockMaker mockMaker = mock(MockMaker.class); EasyPowerMockMockerConfig mockerConfig = new EasyPowerMockMockerConfig(mockMaker); assertEquals(mockMaker, mockerConfig.provideMockMaker()); }
@Test public void testAssertNull() { Object obj = null; Preconditions.assertNull(obj, "Object is not null"); obj = new Object(); try { Preconditions.assertNull(obj, "Object is not null"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { assertEquals("Object is not null", e.getMessage()); } }
@Test public void testInject() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, new Wrapper<Mockspresso.Builder, Mockspresso.Builder>(builder)) {}; Object instance = new Object(); extension.inject(instance); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); JavaxInjectionConfig config = new JavaxInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testCreate() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, Wrapper.wrap(builder)) {}; assertNotNull(extension.create(Object.class)); }
@Test public void testCreate() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, new Wrapper<Mockspresso.Builder, Mockspresso.Builder>(builder)) {}; assertNotNull(extension.create(Object.class)); }
@Test public void testGetDependency() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, new Wrapper<Mockspresso.Builder, Mockspresso.Builder>(builder) {}); DependencyKey<String> key = new DependencyKey<String>() {}; String dependency = extension.getDependency(key); assertNotNull(dependency); }
@Test public void testApply() { MockspressoBuilderImpl builder = mock(MockspressoBuilderImpl.class); Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); RuleConfig ruleConfig = mock(RuleConfig.class); MockspressoRuleImpl rule = new MockspressoRuleImpl(builder, builderProvider, ruleConfig); Statement base = mock(Statement.class); FrameworkMethod method = mock(FrameworkMethod.class); Object target = new Object(); Statement result = rule.apply(base, method, target); assertNotNull(result); }
@Test public void testAssertNull() { Object obj = null; Preconditions.assertNull(obj, "Object is not null"); obj = new Object(); try { Preconditions.assertNull(obj, "Object is not null"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { assertEquals("Object is not null", e.getMessage()); } }
@Test public void testFromField() throws NoSuchFieldException { Field field = MyClass.class.getDeclaredField("myField"); DependencyKey<?> dependencyKey = DependencyKey.fromField(field); assertNotNull(dependencyKey); } class MyClass { @MyQualifier private String myField; } @Retention(RetentionPolicy.RUNTIME) @Qualifier @interface MyQualifier {}
@Test public void testPut() { DependencyKey<String> key = new DependencyKey<>("key", String.class); TypeToken<? extends String> implementationToken = new TypeToken<String>() {}; boolean shouldMapDependency = true; RealObjectMapping rom = new RealObjectMapping(); rom.put(key, implementationToken, shouldMapDependency); assertEquals(1, rom.mMap.size()); assertTrue(rom.mMap.containsKey(key)); }
@Test public void testBuild() { Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); DelayedMockspressoBuilder builder = new DelayedMockspressoBuilder(builderProvider); Mockspresso mockspresso = builder.build(); assertNotNull(mockspresso); assertTrue(mockspresso instanceof Mockspresso); }
@Test public void testProvideMockMaker() { MockMaker mockMaker = EasyMock.createMock(MockMaker.class); EasyMockMockerConfig mockerConfig = new EasyMockMockerConfig(mockMaker); assertSame(mockMaker, mockerConfig.provideMockMaker()); }
@Test public void testProvideMockAnnotations() { MockitoMockerConfig config = new MockitoMockerConfig(); List<Class<? extends Annotation>> annotations = config.provideMockAnnotations(); assertNotNull(annotations); assertEquals(2, annotations.size()); assertTrue(annotations.contains(Mock.class)); assertTrue(annotations.contains(Spy.class)); }
@Test public void testApply() { MockspressoBuilderImpl builder = mock(MockspressoBuilderImpl.class); Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); RuleConfig ruleConfig = mock(RuleConfig.class); MockspressoRuleImpl rule = new MockspressoRuleImpl(builder, builderProvider, ruleConfig); Statement base = mock(Statement.class); FrameworkMethod method = mock(FrameworkMethod.class); Object target = new Object(); Statement result = rule.apply(base, method, target); assertNotNull(result); }
@Test public void testAppend() { DependencyKey key1 = new DependencyKey("key1"); DependencyKey key2 = new DependencyKey("key2"); DependencyValidator validator1 = new DependencyValidator(key1); DependencyValidator validator2 = new DependencyValidator(key2); validator1.append(null); assertEquals(validator1.getChildren().size(), 0); validator1.append(validator2); assertEquals(validator1.getChildren().size(), 1); assertEquals(validator2.getParents().size(), 1); try { validator1.append(new DependencyValidator(new DependencyKey("key3"))); fail("Expected RuntimeException not thrown"); } catch (RuntimeException e) { assertEquals(e.getMessage(), "DependencyValidator append mismatch, tried to append key3 to key1"); } }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testMakeMock() { TypeToken<MyClass> typeToken = TypeToken.of(MyClass.class); EasyPowerMockMockMaker mockMaker = new EasyPowerMockMockMaker(); MyClass mockObj = mockMaker.makeMock(typeToken); assertNotNull(mockObj); assertTrue(mockObj instanceof MyClass); }
@Test public void testInjectObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); Object instance = new Object(); TypeToken<?> typeToken = TypeToken.of(Object.class); RealObjectMaker realObjectMaker = new RealObjectMaker(mock(InjectionConfig.ConstructorSelector.class), Arrays.asList(mock(Annotation.class).getClass()), Arrays.asList(mock(Annotation.class).getClass())); realObjectMaker.injectObject(dependencyProvider, instance, typeToken); verify(dependencyProvider, times(1)).assignInjectableFields(any(), any(), any()); verify(dependencyProvider, times(1)).callInjectableMethods(any(), any(), any()); }
@Test public void testApply() { Mockspresso.Builder builder = Mockito.mock(Mockspresso.Builder.class); PowerMockitoPlugin powerMockitoPlugin = new PowerMockitoPlugin(); Mockspresso.Builder result = powerMockitoPlugin.apply(builder); assertNotNull(result); }
@Test public void testInjectObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); Object instance = new Object(); TypeToken<?> typeToken = TypeToken.of(Object.class); RealObjectMaker realObjectMaker = new RealObjectMaker(mock(InjectionConfig.ConstructorSelector.class), Collections.singletonList(Inject.class), Collections.singletonList(Inject.class)); realObjectMaker.injectObject(dependencyProvider, instance, typeToken); verify(dependencyProvider, times(1)).assignInjectableFields(any(), any(), any()); verify(dependencyProvider, times(1)).callInjectableMethods(any(), any(), any()); }
@Test public void testGetAllDeclaredFields() { class A { private int a; public String b; } class B extends A { protected boolean c; } List<Field> fields = ReflectUtil.getAllDeclaredFields(B.class); assertEquals(3, fields.size()); assertTrue(fields.stream().anyMatch(f -> f.getName().equals("a"))); assertTrue(fields.stream().anyMatch(f -> f.getName().equals("b"))); assertTrue(fields.stream().anyMatch(f -> f.getName().equals("c"))); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testInjectObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); Object instance = new Object(); TypeToken<?> typeToken = TypeToken.of(Object.class); RealObjectMaker realObjectMaker = new RealObjectMaker(mock(InjectionConfig.ConstructorSelector.class), Arrays.asList(mock(Annotation.class)), Arrays.asList(mock(Annotation.class))); assertDoesNotThrow(() -> realObjectMaker.injectObject(dependencyProvider, instance, typeToken)); }
@Test public void testFindQualifierAnnotation() { class MyClass { @MyQualifier private String myField; } Field field = MyClass.class.getDeclaredField("myField"); Annotation annotation = ReflectUtil.findQualifierAnnotation(field); assertNotNull(annotation); assertTrue(annotation instanceof MyQualifier); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); JavaxInjectionConfig config = new JavaxInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testTeardown() { Collection<TestResource> testResources = new ArrayList<>(); DependencyMap dependencyMap = new DependencyMap(); RealObjectMapping realObjectMapping = new RealObjectMapping(); FieldImporter fieldImporter = new FieldImporter(); RealObjectFieldTracker realObjectFieldTracker = new RealObjectFieldTracker(); ResourceLifecycleFieldManager manager = new ResourceLifecycleFieldManager(testResources, dependencyMap, realObjectMapping, fieldImporter, realObjectFieldTracker); manager.teardown(); assertTrue(manager.mRealObjectFieldTracker.isEmpty()); assertTrue(manager.mDependencyMap.isEmpty()); assertTrue(manager.mRealObjectMapping.isEmpty()); }
@Test public void testGetDependency() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, new Wrapper<Mockspresso.Builder, Mockspresso.Builder>(builder) {}); DependencyKey<String> key = new DependencyKey<String>() {}; String dependency = extension.getDependency(key); assertNotNull(dependency); }
@Test public void testProvideFieldPreparer() { FieldPreparer mockFieldPreparer = Mockito.mock(FieldPreparer.class); PowerMockitoConfig powerMockitoConfig = new PowerMockitoConfig(); powerMockitoConfig.mFieldPreparer = mockFieldPreparer; assertEquals(mockFieldPreparer, powerMockitoConfig.provideFieldPreparer()); }
@Test public void testSetup() { Collection<TestResource> testResources = new ArrayList<>(); TestResource testResource1 = new TestResource(new ObjectWithResources()); TestResource testResource2 = new TestResource(new ObjectWithResources()); testResources.add(testResource1); testResources.add(testResource2); MockerConfig.FieldPreparer fieldPreparer = new MockerConfig.FieldPreparer(); ResourcesLifecycleMockManager manager = new ResourcesLifecycleMockManager(testResources, fieldPreparer); Mockspresso mockspresso = Mockito.mock(Mockspresso.class); manager.setup(mockspresso); Mockito.verify(fieldPreparer, Mockito.times(2)).prepareFields(Mockito.any(ObjectWithResources.class)); }
@Test public void testApply() { Mockspresso.Builder builder = Mockito.mock(Mockspresso.Builder.class); MockitoMockerConfig config = new MockitoMockerConfig(); MockitoPlugin plugin = new MockitoPlugin(); Mockspresso.Builder result = plugin.apply(builder); assertNotNull(result); Mockito.verify(builder).mocker(config); }
@Test public void testProvideMockAnnotations() { PowerMockitoConfig config = new PowerMockitoConfig(); List<Class<? extends Annotation>> annotations = config.provideMockAnnotations(); assertNotNull(annotations); assertEquals(2, annotations.size()); assertTrue(annotations.contains(Mock.class)); assertTrue(annotations.contains(Spy.class)); }
@Test public void testApply() { Mockspresso.Builder builder = mock(Mockspresso.Builder.class); EasyPowerMockPlugin easyPowerMockPlugin = mock(EasyPowerMockPlugin.class); PowerMockRule powerMockRule = mock(PowerMockRule.class); when(builder.plugin(easyPowerMockPlugin)).thenReturn(builder); when(builder.outerRule(powerMockRule)).thenReturn(builder); EasyPowerMockRulePlugin easyPowerMockRulePlugin = new EasyPowerMockRulePlugin(); Mockspresso.Builder result = easyPowerMockRulePlugin.apply(builder); verify(builder).plugin(easyPowerMockPlugin); verify(builder).outerRule(powerMockRule); assertEquals(builder, result); }
@Test public void testProvideFieldPreparer() { FieldPreparer expectedFieldPreparer = new FieldPreparer(); EasyPowerMockMockerConfig mockerConfig = new EasyPowerMockMockerConfig(); FieldPreparer actualFieldPreparer = mockerConfig.provideFieldPreparer(); assertEquals(expectedFieldPreparer, actualFieldPreparer); }
@Test public void testAssertNotNull() { String str = "test"; Preconditions.assertNotNull(str, "String is null"); }
@Test void testImportAnnotatedFields() { class MockObject { @ImportAnnotation private String field1 = "value1"; @ImportAnnotation private int field2 = 2; @Unmapped private boolean field3 = true; } MockObject mockObject = new MockObject(); DependencyMap dependencyMap = new DependencyMap(); KeyAdjuster keyAdjuster = new KeyAdjuster() { @Override public DependencyKey adjustKey(DependencyKey key, Field field) { return key; } }; FieldImporter fieldImporter = new FieldImporter(Collections.singletonList(ImportAnnotation.class), dependencyMap, keyAdjuster); fieldImporter.importAnnotatedFields(mockObject); assertEquals("value1", dependencyMap.get(String.class, null, null)); assertEquals(2, dependencyMap.get(int.class, null, null)); assertNull(dependencyMap.get(boolean.class, null, null)); }
@Test public void testProvideFieldPreparer() { FieldPreparer mockFieldPreparer = mock(FieldPreparer.class); MockitoMockerConfig mockerConfig = new MockitoMockerConfig(); mockerConfig.mFieldPreparer = mockFieldPreparer; assertEquals(mockFieldPreparer, mockerConfig.provideFieldPreparer()); }
@Test public void testPrepareFields() { EasyPowerMockFieldPreparer preparer = new EasyPowerMockFieldPreparer(); Object objectWithMockFields = new Object(); preparer.prepareFields(objectWithMockFields); }
@Test public void testSetup() { List<ResourcesLifecycleComponent> components = new ArrayList<>(); ResourcesLifecycleComponent component1 = mock(ResourcesLifecycleComponent.class); ResourcesLifecycleComponent component2 = mock(ResourcesLifecycleComponent.class); components.add(component1); components.add(component2); Mockspresso mockspresso = mock(Mockspresso.class); ResourcesLifecycleManager manager = new ResourcesLifecycleManager(components); manager.setup(mockspresso); verify(component1).setup(mockspresso); verify(component2).setup(mockspresso); }
@Test public void testAssertTrue() { Preconditions.assertTrue(true, "This should not throw an exception"); try { Preconditions.assertTrue(false, "This should throw an exception"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { assertEquals("This should throw an exception", e.getMessage()); } }
@Test void testImportAnnotatedFields() { class MockObject { @ImportAnnotation private String field1 = "value1"; @ImportAnnotation private int field2 = 2; @Unmapped private boolean field3 = true; } MockObject mockObject = new MockObject(); DependencyMap dependencyMap = new DependencyMap(); KeyAdjuster keyAdjuster = new KeyAdjuster() { @Override public DependencyKey adjustKey(DependencyKey key, Field field) { return key; } }; FieldImporter fieldImporter = new FieldImporter(Collections.singletonList(ImportAnnotation.class), dependencyMap, keyAdjuster); fieldImporter.importAnnotatedFields(mockObject); assertEquals("value1", dependencyMap.get(String.class, null, null)); assertEquals(2, dependencyMap.get(int.class, null, null)); assertNull(dependencyMap.get(boolean.class, null, null)); }
@Test public void testPrepareFields() { EasyMockFieldPreparer easyMockFieldPreparer = new EasyMockFieldPreparer(); Object objectWithMockFields = new Object(); easyMockFieldPreparer.prepareFields(objectWithMockFields); assertNotNull(objectWithMockFields); }
@Test public void testFindQualifierAnnotation() { class MyClass { @MyQualifier private String myField; } Field field = MyClass.class.getDeclaredField("myField"); Annotation annotation = ReflectUtil.findQualifierAnnotation(field); assertNotNull(annotation); assertTrue(annotation instanceof MyQualifier); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = new DependencyProvider(); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), new ArrayList<Class<? extends Annotation>>(), new ArrayList<Class<? extends Annotation>>()); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testInjectObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); Object instance = new Object(); TypeToken<?> typeToken = TypeToken.of(Object.class); RealObjectMaker realObjectMaker = new RealObjectMaker(mock(InjectionConfig.ConstructorSelector.class), Collections.singletonList(Inject.class), Collections.singletonList(Inject.class)); assertDoesNotThrow(() -> realObjectMaker.injectObject(dependencyProvider, instance, typeToken)); }
@Test public void testInjectObject() throws IllegalAccessException { DependencyProvider dependencyProvider = mock(DependencyProvider.class); Object instance = new Object(); TypeToken<?> typeToken = TypeToken.of(instance.getClass()); RealObjectMaker realObjectMaker = new RealObjectMaker(constructorSelector, injectFieldAnnotations, injectMethodAnnotations); realObjectMaker.injectObject(dependencyProvider, instance, typeToken); verify(dependencyProvider).getDependency(any(TypeToken.class)); }
@Test public void testClear() { RealObjectMapping realObjectMapping = new RealObjectMapping(); RealObjectMaker realObjectMaker = new RealObjectMaker(); DependencyProviderFactory dependencyProviderFacotry = new DependencyProviderFactory(); RealObjectFieldTracker realObjectFieldTracker = new RealObjectFieldTracker(realObjectMapping, realObjectMaker, dependencyProviderFacotry); FieldInfo fieldInfo1 = new FieldInfo(); FieldInfo fieldInfo2 = new FieldInfo(); FieldInfo fieldInfo3 = new FieldInfo(); FieldInfo fieldInfo4 = new FieldInfo(); realObjectFieldTracker.mMappedFields.add(fieldInfo1); realObjectFieldTracker.mMappedFields.add(fieldInfo2); realObjectFieldTracker.mUnmappedFields.add(fieldInfo3); realObjectFieldTracker.mUnmappedFields.add(fieldInfo4); fieldInfo1.setValue("value1"); fieldInfo2.setValue("value2"); fieldInfo3.setValue("value3"); fieldInfo4.setValue("value4"); realObjectFieldTracker.clear(); assertTrue(realObjectFieldTracker.mMappedFields.isEmpty()); assertTrue(realObjectFieldTracker.mUnmappedFields.isEmpty()); assertNull(fieldInfo1.getValue()); assertNull(fieldInfo2.getValue()); assertNull(fieldInfo3.getValue()); assertNull(fieldInfo4.getValue()); }
@Test public void testIsAnyAnnotationPresent() throws NoSuchFieldException { Collection<Class<? extends Annotation>> annotations = new ArrayList<>(); annotations.add(MyAnnotation.class); Field field = MyClass.class.getDeclaredField("myField"); boolean result = ReflectUtil.isAnyAnnotationPresent(field, annotations); assertTrue(result); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); SimpleInjectionConfig config = new SimpleInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testApply() { Mockspresso.Builder builder = Mockspresso.builder(); DaggerMockspressoPlugin plugin = new DaggerMockspressoPlugin(); Mockspresso.Builder result = plugin.apply(builder); assertNotNull(result); assertNotNull(result.getPlugins()); assertEquals(2, result.getPlugins().size()); assertTrue(result.getPlugins().get(0) instanceof JavaxInjectMockspressoPlugin); assertTrue(result.getPlugins().get(1) instanceof DaggerLazyMaker); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); JavaxInjectionConfig config = new JavaxInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testInject() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, new Wrapper<Mockspresso.Builder, Mockspresso.Builder>(builder) {}); Object instance = new Object(); extension.inject(instance); }
@Test public void testAssertTrue() { Preconditions.assertTrue(true, "This should not throw an exception"); try { Preconditions.assertTrue(false, "This should throw an exception"); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { assertEquals("This should throw an exception", e.getMessage()); } }
@Test public void testProvideMockMaker() { MockMaker mockMaker = Mockito.mock(MockMaker.class); PowerMockitoConfig powerMockitoConfig = new PowerMockitoConfig(mockMaker); assertEquals(mockMaker, powerMockitoConfig.provideMockMaker()); }
@Test public void testGetConfig() { Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); AbstractDelayedMockspresso mockspresso = new AbstractDelayedMockspresso(builderProvider) {}; MockspressoBuilderImpl builder = new MockspressoBuilderImpl(); when(builderProvider.get()).thenReturn(builder); MockspressoConfigContainer configContainer = mockspresso.getConfig(); assertNotNull(configContainer); }
@Test public void testScanNullRealObjectFields() { RealObjectMapping mapping = new RealObjectMapping(); RealObjectMaker maker = new RealObjectMaker(); DependencyProviderFactory factory = new DependencyProviderFactory(); RealObjectFieldTracker tracker = new RealObjectFieldTracker(mapping, maker, factory); Object object = new Object(); tracker.scanNullRealObjectFields(object); assertEquals(0, mapping.getTrackedFields().size()); }
@Test public void testApply() { Mockspresso.Builder builder = Mockspresso.Builder(); EasyPowerMockPlugin easyPowerMockPlugin = new EasyPowerMockPlugin(); Mockspresso.Builder result = easyPowerMockPlugin.apply(builder); assertNotNull(result); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testSetup() { Collection<TestResource> testResources = new ArrayList<>(); DependencyMap dependencyMap = new DependencyMap(); RealObjectMapping realObjectMapping = new RealObjectMapping(); FieldImporter fieldImporter = new FieldImporter(); RealObjectFieldTracker realObjectFieldTracker = new RealObjectFieldTracker(); ResourceLifecycleFieldManager manager = new ResourceLifecycleFieldManager(testResources, dependencyMap, realObjectMapping, fieldImporter, realObjectFieldTracker); Mockspresso mockspresso = new Mockspresso(); manager.setup(mockspresso); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); JavaxInjectionConfig config = new JavaxInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testAssertNotNull() { String str = "test"; Preconditions.assertNotNull(str, "String is null"); Integer num = null; try { Preconditions.assertNotNull(num, "Integer is null"); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException e) { assertEquals("Integer is null", e.getMessage()); } }
@Test public void testGetAllDeclaredMethods() { class TestClass { public void method1() {} private void method2() {} protected void method3() {} } List<Method> methods = ReflectUtil.getAllDeclaredMethods(TestClass.class); assertEquals(3, methods.size()); assertTrue(methods.stream().anyMatch(m -> m.getName().equals("method1"))); assertTrue(methods.stream().anyMatch(m -> m.getName().equals("method2"))); assertTrue(methods.stream().anyMatch(m -> m.getName().equals("method3"))); }
@Test public void testMakeMock() { MockitoMockMaker mockMaker = new MockitoMockMaker(); TypeToken<List<String>> typeToken = new TypeToken<List<String>>() {}; List<String> mockedList = mockMaker.makeMock(typeToken); assertNotNull(mockedList); assertTrue(mockedList instanceof List); }
@Test public void testApply() { MockspressoBuilderImpl builder = mock(MockspressoBuilderImpl.class); Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); RuleConfig ruleConfig = mock(RuleConfig.class); MockspressoRuleImpl rule = new MockspressoRuleImpl(builder, builderProvider, ruleConfig); Statement base = mock(Statement.class); FrameworkMethod method = mock(FrameworkMethod.class); Object target = new Object(); Statement result = rule.apply(base, method, target); assertNotNull(result); }
@Test public void testPut() { DependencyMap map = new DependencyMap(); DependencyKey<String> key = new DependencyKey<>("key", String.class); String value = "value"; map.put(key, value, null); assertEquals(value, map.get(key)); }
@Test void testImportAnnotatedFields() { class MockObject { @ImportAnnotation private String field1 = "value1"; @ImportAnnotation private int field2 = 2; @Unmapped private boolean field3 = true; } MockObject mockObject = new MockObject(); DependencyMap dependencyMap = new DependencyMap(); KeyAdjuster keyAdjuster = new KeyAdjuster() { @Override public DependencyKey adjustKey(DependencyKey key, Field field) { return key; } }; FieldImporter fieldImporter = new FieldImporter(Collections.singletonList(ImportAnnotation.class), dependencyMap, keyAdjuster); fieldImporter.importAnnotatedFields(mockObject); assertEquals("value1", dependencyMap.get(String.class, null, null)); assertEquals(2, dependencyMap.get(int.class, null, null)); assertNull(dependencyMap.get(boolean.class, null, null)); }
@Test public void testProvideFieldPreparer() { FieldPreparer mockFieldPreparer = EasyMock.createMock(FieldPreparer.class); EasyMock.expect(mockFieldPreparer.prepareFields(EasyMock.anyObject())).andReturn(null); EasyMock.replay(mockFieldPreparer); EasyMockMockerConfig mockerConfig = new EasyMockMockerConfig(); FieldPreparer fieldPreparer = mockerConfig.provideFieldPreparer(); assertNull(fieldPreparer.prepareFields(null)); EasyMock.verify(mockFieldPreparer); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); JavaxInjectionConfig config = new JavaxInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testMakeMock() { MockitoMockMaker mockMaker = new MockitoMockMaker(); TypeToken<List<String>> typeToken = new TypeToken<List<String>>() {}; List<String> mockedList = mockMaker.makeMock(typeToken); assertNotNull(mockedList); assertTrue(mockedList instanceof List); }
@Test public void testConcatList() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(7, 8, 9); List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> actual = CollectionUtil.concatList(list1, list2, list3); assertEquals(expected, actual); }
@Test public void testMakeMock() { TypeToken<String> typeToken = TypeToken.of(String.class); EasyMockMockMaker mockMaker = new EasyMockMockMaker(); String mockString = mockMaker.makeMock(typeToken); assertNotNull(mockString); }
@Test public void testApply() { Mockspresso.Builder builder = mock(Mockspresso.Builder.class); PowerMockitoPlugin powerMockitoPlugin = mock(PowerMockitoPlugin.class); PowerMockRule powerMockRule = mock(PowerMockRule.class); PowerMockitoRulePlugin powerMockitoRulePlugin = new PowerMockitoRulePlugin(); when(builder.plugin(powerMockitoPlugin)).thenReturn(builder); when(builder.outerRule(powerMockRule)).thenReturn(builder); Mockspresso.Builder result = powerMockitoRulePlugin.apply(builder); verify(builder).plugin(powerMockitoPlugin); verify(builder).outerRule(powerMockRule); assertEquals(builder, result); }
@Test public void testProvideConstructorSelector() { ConstructorSelector selector = new ConstructorSelectorImpl(); SimpleInjectionConfig config = new SimpleInjectionConfig(selector); assertEquals(selector, config.provideConstructorSelector()); }
@Test public void testApply() { Mockspresso.Builder builder = Mockspresso.builder(); GuavaMockspressoPlugin plugin = new GuavaMockspressoPlugin(); Mockspresso.Builder result = plugin.apply(builder); assertNotNull(result); assertTrue(result.getSpecialObjectMakers().contains(new ListenableFutureMaker())); assertTrue(result.getSpecialObjectMakers().contains(new SupplierMaker())); }
@Test public void testProvideInjectableFieldAnnotations() { JavaxInjectionConfig config = new JavaxInjectionConfig(); List<Class<? extends Annotation>> annotations = config.provideInjectableFieldAnnotations(); assertNotNull(annotations); assertEquals(1, annotations.size()); assertEquals(Inject.class, annotations.get(0)); }
@Test public void testBuild() { Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); DelayedMockspressoBuilder builder = new DelayedMockspressoBuilder(builderProvider); Mockspresso mockspresso = builder.build(); assertNotNull(mockspresso); assertTrue(mockspresso instanceof Mockspresso); }
@Test public void testCreateObject() { DependencyProvider dependencyProvider = mock(DependencyProvider.class); TypeToken<String> typeToken = new TypeToken<String>() {}; RealObjectMaker realObjectMaker = new RealObjectMaker(new InjectionConfig.ConstructorSelector(), Arrays.asList(InjectFieldAnnotation.class), Arrays.asList(InjectMethodAnnotation.class)); String result = realObjectMaker.createObject(dependencyProvider, typeToken); assertNotNull(result); }
@Test public void testBuildRule() { DelayedMockspressoBuilder builder = new DelayedMockspressoBuilder(() -> new MockspressoBuilderImpl()); try { builder.buildRule(); fail("Expected VerifyError was not thrown"); } catch (VerifyError e) { assertEquals("Can\'t build a new mockspresso @Rule on top of an existing one.", e.getMessage()); } }
@Test public void testMakeMock() { TypeToken<MyClass> typeToken = TypeToken.of(MyClass.class); EasyPowerMockMockMaker mockMaker = new EasyPowerMockMockMaker(); MyClass mockObj = mockMaker.makeMock(typeToken); assertNotNull(mockObj); assertTrue(mockObj instanceof MyClass); }
@Test public void testCreate() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, Wrapper.wrap(builder)) {}; assertNotNull(extension.create(Object.class)); }
@Test public void testSetup() { Collection<TestResource> testResources = new ArrayList<>(); DependencyMap dependencyMap = new DependencyMap(); RealObjectMapping realObjectMapping = new RealObjectMapping(); FieldImporter fieldImporter = new FieldImporter(); RealObjectFieldTracker realObjectFieldTracker = new RealObjectFieldTracker(); ResourceLifecycleFieldManager manager = new ResourceLifecycleFieldManager(testResources, dependencyMap, realObjectMapping, fieldImporter, realObjectFieldTracker); Mockspresso mockspresso = new Mockspresso(); manager.setup(mockspresso); }
@Test public void testConcatList() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(7, 8, 9); List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> actual = CollectionUtil.concatList(list1, list2, list3); assertEquals(expected, actual); }
@Test public void testConcatList() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(7, 8, 9); List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> actual = CollectionUtil.concatList(list1, list2, list3); assertEquals(expected, actual); }
@Test public void testMakeMock() { TypeToken<String> typeToken = TypeToken.of(String.class); EasyMockMockMaker mockMaker = new EasyMockMockMaker(); String mockString = mockMaker.makeMock(typeToken); assertNotNull(mockString); }
@Test public void testCreate() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); AbstractMockspressoExtension<Mockspresso.Builder> extension = new AbstractMockspressoExtension<Mockspresso.Builder>(mockspresso, Wrapper.wrap(builder)) {}; assertNotNull(extension.create(Object.class)); }
@Test public void testWrapTestRule() { TestRule testRule = new TestRule() { @Override public Statement apply(Statement base, Description description) { return null; } }; MethodRule methodRule = MethodRules.wrapTestRule(testRule); assertNotNull(methodRule); }
@Test public void testMakeMock() { PowerMockitoMockMaker mockMaker = new PowerMockitoMockMaker(); TypeToken<String> typeToken = TypeToken.get(String.class); String mockString = mockMaker.makeMock(typeToken); assertNotNull(mockString); }
@Test public void testTeardown() { TestResource testResource1 = new TestResource(); TestResource testResource2 = new TestResource(); Collection<TestResource> testResources = new ArrayList<>(); testResources.add(testResource1); testResources.add(testResource2); ResourcesLifecycleMethodManager manager = new ResourcesLifecycleMethodManager(testResources); manager.teardown(); assertTrue(testResource1.isAfterMethodCalled()); assertTrue(testResource2.isAfterMethodCalled()); } class TestResource implements ResourcesLifecycleComponent { private boolean afterMethodCalled = false; @Override public void teardown() { } @Override public void callAfterMethods() { afterMethodCalled = true; } public boolean isAfterMethodCalled() { return afterMethodCalled; } }
@Test public void testAppend() { DependencyKey key1 = new DependencyKey("key1"); DependencyKey key2 = new DependencyKey("key2"); DependencyValidator validator1 = new DependencyValidator(key1); DependencyValidator validator2 = new DependencyValidator(key2); validator1.append(null); assertEquals(validator1.getChildren().size(), 0); validator1.append(validator2); assertEquals(validator1.getChildren().size(), 1); assertEquals(validator2.getParents().size(), 1); try { validator1.append(new DependencyValidator(new DependencyKey("key3"))); fail("Expected RuntimeException not thrown"); } catch (RuntimeException e) { assertEquals(e.getMessage(), "DependencyValidator append mismatch, tried to append key3 to key1"); } }
@Test public void testPrepareFields() { Object objectWithMockFields = new Object(); MockitoFieldPreparer mockitoFieldPreparer = new MockitoFieldPreparer(); mockitoFieldPreparer.prepareFields(objectWithMockFields); assertNotNull(objectWithMockFields); }
@Test public void testProvideInjectableFieldAnnotations() { SimpleInjectionConfig config = new SimpleInjectionConfig(); List<Class<? extends Annotation>> annotations = config.provideInjectableFieldAnnotations(); assertNotNull(annotations); assertTrue(annotations.isEmpty()); }
@Test public void testCreate() { AbstractDelayedMockspresso abstractDelayedMockspresso = new AbstractDelayedMockspresso(new Provider<MockspressoBuilderImpl>() { @Override public MockspressoBuilderImpl get() { return new MockspressoBuilderImpl(); } }); assertNotNull(abstractDelayedMockspresso.create(Object.class)); }
@Test public void testConcatList() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(4, 5, 6); List<Integer> list3 = Arrays.asList(7, 8, 9); List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); List<Integer> actual = CollectionUtil.concatList(list1, list2, list3); assertEquals(expected, actual); }
@Test public void testSetParent() { MockspressoConfigContainer parentConfig = mock(MockspressoConfigContainer.class); MockspressoBuilderImpl builder = mock(MockspressoBuilderImpl.class); when(builder.deepCopy()).thenReturn(builder); when(builder.buildInternal()).thenReturn(mock(Mockspresso.class)); Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); when(builderProvider.get()).thenReturn(builder); DelayedMockspressoBuilder delayedBuilder = new DelayedMockspressoBuilder(builderProvider); delayedBuilder.setParent(parentConfig); verify(builder).setParent(parentConfig); }
@Test public void testFromField() throws NoSuchFieldException { Field field = MyClass.class.getDeclaredField("myField"); DependencyKey<?> dependencyKey = DependencyKey.fromField(field); assertNotNull(dependencyKey); } class MyClass { @MyQualifier private String myField; } @Retention(RetentionPolicy.RUNTIME) @Qualifier @interface MyQualifier {}
@Test public void testApply() { Mockspresso.Builder builder = Mockito.mock(Mockspresso.Builder.class); SimpleInjectMockspressoPlugin plugin = new SimpleInjectMockspressoPlugin(); Mockspresso.Builder result = plugin.apply(builder); assertNotNull(result); }
@Test public void testProvideMockAnnotations() { EasyMockMockerConfig config = new EasyMockMockerConfig(); List<Class<? extends Annotation>> annotations = config.provideMockAnnotations(); assertNotNull(annotations); assertEquals(1, annotations.size()); assertEquals(Mock.class, annotations.get(0)); }
@Test public void testProvideMockAnnotations() { EasyPowerMockMockerConfig config = new EasyPowerMockMockerConfig(); List<Class<? extends Annotation>> annotations = config.provideMockAnnotations(); assertNotNull(annotations); assertEquals(4, annotations.size()); assertTrue(annotations.contains(Mock.class)); assertTrue(annotations.contains(org.powermock.api.easymock.annotation.Mock.class)); assertTrue(annotations.contains(MockStrict.class)); assertTrue(annotations.contains(MockNice.class)); }
@Test public void testBuildUpon() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); Wrapper<Mockspresso.Builder, BLDR> wrapper = new Wrapper<Mockspresso.Builder, BLDR>() { @Override public BLDR wrap(Mockspresso.Builder builder) { return null; } }; AbstractMockspressoExtension<BLDR> extension = new AbstractMockspressoExtension<BLDR>(mockspresso, wrapper) {}; BLDR bldr = extension.buildUpon(); assertNotNull(bldr); }
@Test public void testBuildUpon() { Mockspresso.Builder builder = Mockspresso.builder(); Mockspresso mockspresso = builder.build(); Wrapper<Mockspresso.Builder, BLDR> wrapper = new Wrapper<Mockspresso.Builder, BLDR>() { @Override public BLDR wrap(Mockspresso.Builder builder) { return null; } }; AbstractMockspressoExtension<BLDR> extension = new AbstractMockspressoExtension<BLDR>(mockspresso, wrapper) {}; BLDR bldr = extension.buildUpon(); assertNotNull(bldr); }
@Test public void testIsAnyAnnotationPresent() throws NoSuchFieldException { Collection<Class<? extends Annotation>> annotations = new ArrayList<>(); annotations.add(MyAnnotation.class); Field field = MyClass.class.getDeclaredField("myField"); boolean result = ReflectUtil.isAnyAnnotationPresent(field, annotations); assertTrue(result); }
@Test void testImportAnnotatedFields() { class MockObject { @ImportAnnotation private String field1 = "value1"; @ImportAnnotation private int field2 = 2; @Unmapped private boolean field3 = true; } MockObject mockObject = new MockObject(); DependencyMap dependencyMap = new DependencyMap(); KeyAdjuster keyAdjuster = new KeyAdjuster() { @Override public DependencyKey adjustKey(DependencyKey key, Field field) { return key; } }; FieldImporter fieldImporter = new FieldImporter(Collections.singletonList(ImportAnnotation.class), dependencyMap, keyAdjuster); fieldImporter.importAnnotatedFields(mockObject); assertEquals("value1", dependencyMap.get(String.class, null, null)); assertEquals(2, dependencyMap.get(int.class, null, null)); assertNull(dependencyMap.get(boolean.class, null, null)); }
@Test public void testSetup() { Collection<TestResource> testResources = new ArrayList<>(); testResources.add(new TestResource()); ResourcesLifecycleMethodManager manager = new ResourcesLifecycleMethodManager(testResources); Mockspresso mockspresso = new Mockspresso(); manager.setup(mockspresso); }
@Test public void testPrepareFields() throws IllegalAccessException { PowerMockitoFieldPreparer preparer = new PowerMockitoFieldPreparer(); Object objectWithMockFields = new Object(); preparer.prepareFields(objectWithMockFields); }
@Test public void testTeardown() { List<ResourcesLifecycleComponent> components = new ArrayList<>(); ResourcesLifecycleComponent component1 = mock(ResourcesLifecycleComponent.class); ResourcesLifecycleComponent component2 = mock(ResourcesLifecycleComponent.class); ResourcesLifecycleComponent component3 = mock(ResourcesLifecycleComponent.class); components.add(component1); components.add(component2); components.add(component3); ResourcesLifecycleManager manager = new ResourcesLifecycleManager(components); manager.teardown(); verify(component3, times(1)).teardown(); verify(component2, times(1)).teardown(); verify(component1, times(1)).teardown(); }
@Test public void testApply() { Mockspresso.Builder builder = Mockito.mock(Mockspresso.Builder.class); JavaxInjectMockspressoPlugin plugin = new JavaxInjectMockspressoPlugin(); Mockspresso.Builder result = plugin.apply(builder); assertNotNull(result); verify(builder, times(1)).injector(any(JavaxInjectionConfig.class)); verify(builder, times(1)).specialObjectMaker(any(ProviderMaker.class)); }
@Test public void testProvideMockMaker() { MockMaker mockMaker = Mockito.mock(MockMaker.class); MockitoMockerConfig mockerConfig = new MockitoMockerConfig(mockMaker); assertEquals(mockMaker, mockerConfig.provideMockMaker()); }
@Test public void testApply() { MockspressoBuilderImpl builder = mock(MockspressoBuilderImpl.class); Provider<MockspressoBuilderImpl> builderProvider = mock(Provider.class); RuleConfig ruleConfig = mock(RuleConfig.class); MockspressoRuleImpl rule = new MockspressoRuleImpl(builder, builderProvider, ruleConfig); Statement base = mock(Statement.class); FrameworkMethod method = mock(FrameworkMethod.class); Object target = new Object(); Statement result = rule.apply(base, method, target); assertNotNull(result); }
@Test public void testCreate() { AbstractDelayedMockspresso abstractDelayedMockspresso = new AbstractDelayedMockspresso(new Provider<MockspressoBuilderImpl>() { @Override public MockspressoBuilderImpl get() { return new MockspressoBuilderImpl(); } }); assertNotNull(abstractDelayedMockspresso.create(Object.class)); }
@Test public void testApply() { Mockspresso.Builder builder = Mockspresso.Builder(); EasyMockPlugin easyMockPlugin = new EasyMockPlugin(); Mockspresso.Builder result = easyMockPlugin.apply(builder); assertNotNull(result); }
@Test public void testIsNumeric() { assertTrue(NumberHelper.isNumeric("123")); assertTrue(NumberHelper.isNumeric("-123")); assertTrue(NumberHelper.isNumeric("0")); assertFalse(NumberHelper.isNumeric("123.45")); assertFalse(NumberHelper.isNumeric("abc")); assertFalse(NumberHelper.isNumeric("")); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testEscapeJava() { String input = "Hello\tworld\n"; String expectedOutput = "Hello\\tworld\\n"; String actualOutput = StringHelper.escapeJava(input); assertEquals(expectedOutput, actualOutput); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testCompare() { AlphanumComparator comparator = new AlphanumComparator(Locale.US); CharSequence a = "file1.txt"; CharSequence b = "file10.txt"; int result = comparator.compare(a, b); assertEquals(-1, result); }
@Test public void testMakeAdhocBibliography() throws IOException { CSLItemData item1 = new CSLItemData(); item1.setId("item1"); item1.setType("book"); item1.setTitle("The Catcher in the Rye"); item1.setAuthor(Arrays.asList(new CSLName("Salinger", "J.D."))); item1.setPublisher("Little, Brown and Company"); item1.setIssued(new CSLDate(1951, null, null)); CSLItemData item2 = new CSLItemData(); item2.setId("item2"); item2.setType("article-journal"); item2.setTitle("The Role of the Teacher in the Language Classroom"); item2.setAuthor(Arrays.asList(new CSLName("Harmer", "Jeremy"))); item2.setContainerTitle("ELT Journal"); item2.setVolume("56"); item2.setIssue("3"); item2.setPage("240-249"); item2.setIssued(new CSLDate(2002, null, null)); Bibliography bibliography = CSL.makeAdhocBibliography("apa", item1, item2); assertNotNull(bibliography); }
@Test public void testSupportsStyle() { assertTrue(CSL.supportsStyle("apa.csl")); assertFalse(CSL.supportsStyle("invalidStyle")); assertTrue(CSL.supportsStyle("/customStyle.csl")); }
@Test public void testToDateSingle() { CSLDate expectedDate = new CSLDateBuilder().dateParts(2021, 5).circa(Boolean.TRUE).build(); CSLDate actualDate = DateParser.toDateSingle("2021circa", "May"); assertEquals(expectedDate, actualDate); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); Key key = new Key("key"); BibTeXEntry entry = new BibTeXEntry(new Key("entry"), new BibTeXObject() { @Override public void setValue(String value) {} @Override public String getValue() { return null; } @Override public void add(Object o) {} @Override public Object get(int index) { return null; } @Override public int size() { return 0; } @Override public void clear() {} @Override public void remove(Object o) {} @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return null; } }); db.addObject(entry); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("entry")); }
@Test public void testParseObject() throws IOException { String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; JsonLexer lexer = new JsonLexer(new StringReader(json)); JsonParser parser = new JsonParser(lexer); Map<String, Object> expected = new HashMap<>(); expected.put("name", "John"); expected.put("age", 30); expected.put("city", "New York"); Map<String, Object> result = parser.parseObject(); assertEquals(expected, result); }
@Test public void testCompare() { AlphanumComparator comparator = new AlphanumComparator(Locale.US); CharSequence a = "file1.txt"; CharSequence b = "file10.txt"; int result = comparator.compare(a, b); assertEquals(-1, result); }
@Test public void testMakeAdhocBibliography() throws IOException { CSLItemData item1 = new CSLItemData(); item1.setId("item1"); item1.setType("book"); item1.setTitle("The Catcher in the Rye"); item1.setAuthor(Arrays.asList(new CSLName("Salinger", "J.D."))); item1.setPublisher("Little, Brown and Company"); item1.setIssued(new CSLDate(1951, 7, 16)); CSLItemData item2 = new CSLItemData(); item2.setId("item2"); item2.setType("article-journal"); item2.setTitle("The Role of the Teacher in the Language Classroom"); item2.setAuthor(Arrays.asList(new CSLName("Harmer", "Jeremy"))); item2.setContainerTitle("English Teaching Professional"); item2.setVolume("1"); item2.setIssue("1"); item2.setPage("3-5"); item2.setIssued(new CSLDate(1996)); Bibliography bibliography = CSL.makeAdhocBibliography("apa", item1, item2); assertNotNull(bibliography); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testToDate() { String dateString = "2021-10-01"; CSLDate expected = new CSLDateBuilder().raw(dateString).build(); CSLDate actual = DateParser.toDate(dateString); assertEquals(expected, actual); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testFindMinimum() { List<String> list = new ArrayList<>(); list.add("kitten"); list.add("sitting"); list.add("cat"); list.add("dog"); String t = "cut"; String expected = "cat"; String actual = Levenshtein.findMinimum(list, t); assertEquals(expected, actual); }
@Test public void testParse() throws IntrospectionException, InvalidOptionException { Result result = ShellCommandParser.parse("command"); assertNotNull(result); assertEquals(0, result.getOptions().size()); assertEquals("command", result.getCommand()); }
@Test public void testToJson() { JsonBuilderFactory factory = new JsonBuilderFactory(); StringJsonBuilder builder = new StringJsonBuilder(factory); Object arr = new Object(); Object result = builder.toJson(arr); assertNotNull(result); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { CSLDateParser parser = new CSLDateParser(); String dateStr = "2021-05-20"; CSLDate expected = new CSLDateBuilder() .dateParts(new int[][]{{2021, 5, 20}}) .build(); CSLDate actual = parser.parse(dateStr); assertEquals(expected, actual); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); BibTeXEntry entry1 = new BibTeXEntry(new Key("key1"), new BibTeXEntryType("article")); entry1.addField(BibTeXEntry.KEY_AUTHOR, "John Doe"); entry1.addField(BibTeXEntry.KEY_TITLE, "A Title"); db.addObject(entry1); BibTeXEntry entry2 = new BibTeXEntry(new Key("key2"), new BibTeXEntryType("book")); entry2.addField(BibTeXEntry.KEY_AUTHOR, "Jane Smith"); entry2.addField(BibTeXEntry.KEY_TITLE, "Another Title"); db.addObject(entry2); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertEquals(2, result.size()); assertTrue(result.containsKey("key1")); assertTrue(result.containsKey("key2")); CSLItemData item1 = result.get("key1"); assertEquals("John Doe", item1.getAuthor().get(0).getName()); assertEquals("A Title", item1.getTitle()); CSLItemData item2 = result.get("key2"); assertEquals("Jane Smith", item2.getAuthor().get(0).getName()); assertEquals("Another Title", item2.getTitle()); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() { CSLDateParser parser = new CSLDateParser(); String dateStr = "2021-05-20"; CSLDate expected = new CSLDateBuilder() .dateParts(new int[][]{{2021, 5, 20}}) .build(); CSLDate actual = parser.parse(dateStr); assertEquals(expected, actual); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testToTitleCase() { String input = "the quick brown fox jumps over the lazy dog"; String expectedOutput = "The Quick Brown Fox Jumps over the Lazy Dog"; assertEquals(expectedOutput, StringHelper.toTitleCase(input)); }
@Test public void testReset() { ItemDataProvider itemDataProvider = mock(ItemDataProvider.class); AbbreviationProvider abbreviationProvider = mock(AbbreviationProvider.class); LocaleProvider localeProvider = mock(LocaleProvider.class); VariableWrapper variableWrapper = mock(VariableWrapper.class); CSL csl = new CSL(itemDataProvider, localeProvider, abbreviationProvider, variableWrapper, "style", "lang", true, true); csl.reset(); assertEquals("html", csl.outputFormatName); assertFalse(csl.convertLinks); assertTrue(csl.registeredItems.isEmpty()); assertTrue(csl.sortedItems.isEmpty()); assertTrue(csl.generatedCitations.isEmpty()); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() throws IntrospectionException, InvalidOptionException { Result result = ShellCommandParser.parse("command"); assertNotNull(result); assertEquals(0, result.getOptions().size()); assertEquals("command", result.getCommand()); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); Key key = new Key("key"); BibTeXEntry entry = new BibTeXEntry(new Key("entry"), new BibTeXObject() { @Override public void setValue(String value) {} @Override public String getValue() { return null; } @Override public void add(Object o) {} @Override public Object get(int index) { return null; } @Override public int size() { return 0; } @Override public void clear() {} @Override public void remove(Object o) {} @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return null; } }); db.addObject(entry); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("entry")); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testParse() throws IntrospectionException, InvalidOptionException { Result result = ShellCommandParser.parse("command"); assertNotNull(result); assertEquals(0, result.getOptions().size()); assertEquals("command", result.getCommand()); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); Key key = new Key("key"); BibTeXEntry entry = new BibTeXEntry(new Key("entry"), new BibTeXObject() { @Override public void setValue(String value) {} @Override public String getValue() { return null; } @Override public void add(Object o) {} @Override public Object get(int index) { return null; } @Override public int size() { return 0; } @Override public void clear() {} @Override public void remove(Object o) {} @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return null; } }); db.addObject(entry); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("entry")); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testTokenize() { List<NumberToken> expected = new ArrayList<>(); expected.add(new NumberToken("123", NumberTokenType.NUMBER)); expected.add(new NumberToken(",", NumberTokenType.SEPARATOR)); expected.add(new NumberToken("456", NumberTokenType.NUMBER)); expected.add(new NumberToken(".", NumberTokenType.SEPARATOR)); expected.add(new NumberToken("789", NumberTokenType.NUMBER)); List<NumberToken> actual = NumberHelper.tokenize("123,456.789"); assertEquals(expected, actual); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); Key key = new Key("key"); BibTeXEntry entry = new BibTeXEntry(new Key("entry"), new BibTeXObject() { @Override public void setValue(String value) {} @Override public String getValue() { return null; } @Override public void add(Object o) {} @Override public Object get(int index) { return null; } @Override public int size() { return 0; } @Override public void clear() {} @Override public void remove(Object o) {} @Override public boolean contains(Object o) { return false; } @Override public Iterator<Object> iterator() { return null; } }); db.addObject(entry); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertNotNull(result); assertEquals(1, result.size()); assertTrue(result.containsKey("entry")); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testMakeCitation() { ItemDataProvider itemDataProvider = mock(ItemDataProvider.class); AbbreviationProvider abbreviationProvider = mock(AbbreviationProvider.class); LocaleProvider localeProvider = mock(LocaleProvider.class); VariableWrapper variableWrapper = mock(VariableWrapper.class); String style = "apa"; String lang = "en-US"; boolean forceLang = true; boolean experimentalMode = true; CSL csl = new CSL(itemDataProvider, localeProvider, abbreviationProvider, variableWrapper, style, lang, forceLang, experimentalMode); List<Citation> citations = csl.makeCitation("id1", "id2", "id3"); assertNotNull(citations); assertEquals(3, citations.size()); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); BibTeXEntry entry1 = new BibTeXEntry(new Key("key1"), new BibTeXEntryType("article")); entry1.addField(BibTeXEntry.KEY_AUTHOR, "John Doe"); entry1.addField(BibTeXEntry.KEY_TITLE, "A Title"); db.addObject(entry1); BibTeXEntry entry2 = new BibTeXEntry(new Key("key2"), new BibTeXEntryType("book")); entry2.addField(BibTeXEntry.KEY_AUTHOR, "Jane Smith"); entry2.addField(BibTeXEntry.KEY_TITLE, "Another Title"); db.addObject(entry2); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertEquals(2, result.size()); assertTrue(result.containsKey("key1")); assertTrue(result.containsKey("key2")); CSLItemData item1 = result.get("key1"); assertEquals("John Doe", item1.getAuthor().get(0).getName()); assertEquals("A Title", item1.getTitle()); CSLItemData item2 = result.get("key2"); assertEquals("Jane Smith", item2.getAuthor().get(0).getName()); assertEquals("Another Title", item2.getTitle()); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testToJson() { JsonBuilderFactory factory = new JsonBuilderFactory(); MapJsonBuilder builder = new MapJsonBuilder(factory); Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); Object result = builder.toJson(map); assertNotNull(result); assertTrue(result instanceof JsonObject); JsonObject jsonObject = (JsonObject) result; assertEquals("value1", jsonObject.getString("key1")); assertEquals("value2", jsonObject.getString("key2")); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testSanitize() { String input = "H\u00e9ll\u00f2 W\u00f6rld! 123"; String expectedOutput = "Hello_World_123"; String actualOutput = StringHelper.sanitize(input); assertEquals(expectedOutput, actualOutput); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testFindMinimum() { List<String> list = new ArrayList<>(); list.add("kitten"); list.add("sitting"); list.add("cat"); list.add("dog"); String t = "cut"; String expected = "cat"; String actual = Levenshtein.findMinimum(list, t); assertEquals(expected, actual); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testToItemData() { BibTeXDatabase db = new BibTeXDatabase(); Key key = new Key("key"); BibTeXEntry entry = new BibTeXEntry(new Key("entry"), new BibTeXObject() {}); db.addObject(entry); BibTeXConverter converter = new BibTeXConverter(); Map<String, CSLItemData> result = converter.toItemData(db); assertEquals(1, result.size()); assertTrue(result.containsKey("entry")); }
@Test public void testComplete() { List<Class<? extends Command>> excludedCommands = new ArrayList<>(); ShellCommandCompleter completer = new ShellCommandCompleter(excludedCommands); LineReader reader = null; ParsedLine line = null; List<Candidate> candidates = new ArrayList<>(); completer.complete(reader, line, candidates); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testOverlap() { assertEquals(3, StringHelper.overlap("hello", "llo world")); assertEquals(0, StringHelper.overlap("hello", "world")); assertEquals(0, StringHelper.overlap("", "")); assertEquals(0, StringHelper.overlap(null, "world")); assertEquals(0, StringHelper.overlap("hello", null)); }
@Test public void testToDate() { String dateString = "2021-10-01"; CSLDate expected = new CSLDateBuilder().raw(dateString).build(); CSLDate actual = DateParser.toDate(dateString); assertEquals(expected, actual); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { CSLDateParser parser = new CSLDateParser(); String dateStr = "2021-05-20"; CSLDate expected = new CSLDateBuilder() .dateParts(new int[][]{{2021, 5, 20}}) .build(); CSLDate actual = parser.parse(dateStr); assertEquals(expected, actual); }
@Test public void testParse() { List<NumberElement> expected = Arrays.asList(new NumberElement("123"), new NumberElement("."), new NumberElement("45")); List<NumberElement> actual = NumberParser.parse("123.45"); assertEquals(expected, actual); }
@Test public void testGetSupportedStyles() throws IOException { Set<String> expectedStyles = new HashSet<>(); expectedStyles.add("ieee"); expectedStyles.add("csl"); CSL csl = new CSL(mock(ItemDataProvider.class), "ieee"); Set<String> actualStyles = csl.getSupportedStyles(); assertEquals(expectedStyles, actualStyles); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testFindMinimum() { List<String> list = new ArrayList<>(); list.add("kitten"); list.add("sitting"); list.add("cat"); list.add("dog"); String t = "cut"; String expected = "cat"; String actual = Levenshtein.findMinimum(list, t); assertEquals(expected, actual); }
@Test public void testSetOutputFormat() { ItemDataProvider itemDataProvider = mock(ItemDataProvider.class); String style = "apa"; boolean experimentalMode = true; CSL csl = new CSL(itemDataProvider, style, experimentalMode); String format = "text"; csl.setOutputFormat(format); assertEquals(TextFormat.class, csl.outputFormat.getClass()); }
@Test public void testGetSupportedOutputFormats() throws IOException { ItemDataProvider itemDataProvider = mock(ItemDataProvider.class); ScriptRunner runner = mock(ScriptRunner.class); when(CSL.getRunner()).thenReturn(runner); List<String> expectedOutputFormats = Arrays.asList("APA", "MLA", "Chicago"); when(CSL.getSupportedOutputFormats(runner)).thenReturn(expectedOutputFormats); List<String> actualOutputFormats = CSL.getSupportedOutputFormats(); assertEquals(expectedOutputFormats, actualOutputFormats); }
@Test public void testParse() { PageRange pageRange = PageParser.parse("1-5"); assertEquals("1-5", pageRange.getLiteral()); assertEquals(1, pageRange.getPageFrom()); assertEquals(5, pageRange.getNumberOfPages()); assertTrue(pageRange.isMultiplePages()); }
@Test public void testParse() throws IntrospectionException, InvalidOptionException { Result result = ShellCommandParser.parse("command"); assertNotNull(result); assertEquals(0, result.getOptions().size()); assertEquals("command", result.getCommand()); }
@Test public void testMakeCitation() { CSL.ItemDataProvider itemDataProvider = mock(CSL.ItemDataProvider.class); CSL.AbbreviationProvider abbreviationProvider = mock(CSL.AbbreviationProvider.class); CSL.LocaleProvider localeProvider = mock(CSL.LocaleProvider.class); CSL.VariableWrapper variableWrapper = mock(CSL.VariableWrapper.class); String style = "apa"; String lang = "en-US"; boolean forceLang = true; boolean experimentalMode = false; CSL csl = new CSL(itemDataProvider, localeProvider, abbreviationProvider, variableWrapper, style, lang, forceLang, experimentalMode); List<Citation> citations = csl.makeCitation("id1", "id2", "id3"); assertNotNull(citations); assertEquals(3, citations.size()); }
@Test public void testMakeAdhocBibliography() throws IOException { CSLItemData item1 = new CSLItemData(); item1.setId("item1"); item1.setType("book"); item1.setTitle("The Catcher in the Rye"); item1.setAuthor(Arrays.asList(new CSLName("Salinger", "J.D."))); item1.setPublisher("Little, Brown and Company"); item1.setIssued(new CSLDate(1951, 7, 16)); CSLItemData item2 = new CSLItemData(); item2.setId("item2"); item2.setType("article-journal"); item2.setTitle("The Role of the Teacher in the Language Classroom"); item2.setAuthor(Arrays.asList(new CSLName("Harmer", "Jeremy"))); item2.setContainerTitle("English Teaching Professional"); item2.setVolume("1"); item2.setIssue("1"); item2.setPage("3-5"); item2.setIssued(new CSLDate(1996)); Bibliography bibliography = CSL.makeAdhocBibliography("apa", item1, item2); assertNotNull(bibliography); assertEquals(2, bibliography.getEntries().size()); }
@Test public void testParseObject() throws IOException { String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"; JsonLexer lexer = new JsonLexer(new StringReader(json)); JsonParser parser = new JsonParser(lexer); Map<String, Object> expected = new HashMap<>(); expected.put("name", "John"); expected.put("age", 30); expected.put("city", "New York"); Map<String, Object> result = parser.parseObject(); assertEquals(expected, result); }
@Test public void testGetSupportedLocales() throws IOException { CSL csl = new CSL(mock(ItemDataProvider.class), "apa"); Set<String> locales = csl.getSupportedLocales(); assertNotNull(locales); assertFalse(locales.isEmpty()); }
@Test public void testParse() { String names = "John Doe, Jane Smith"; CSLName[] expected = { new CSLNameBuilder().given("John").family("Doe").build(), new CSLNameBuilder().given("Jane").family("Smith").build() }; assertArrayEquals(expected, NameParser.parse(names)); }
@Test public void testWriteFooter() throws IOException { String filePath = "testFilePath"; long currentPosition = 10L; FileFooter footer = new FileFooter(); CarbonFooterWriter writer = new CarbonFooterWriter(filePath); writer.writeFooter(footer, currentPosition); assertEquals(VERSION_NUMBER, footer.getVersion()); verify(thriftWriter, times(1)).close(); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ReverseDictionaryCache<String, String> cache = new ReverseDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testNext() { List<List<byte[]>> dictionaryChunks = new ArrayList<>(); List<byte[]> chunk1 = new ArrayList<>(); chunk1.add(new byte[]{1, 2, 3}); chunk1.add(new byte[]{4, 5, 6}); List<byte[]> chunk2 = new ArrayList<>(); chunk2.add(new byte[]{7, 8, 9}); chunk2.add(new byte[]{10, 11, 12}); dictionaryChunks.add(chunk1); dictionaryChunks.add(chunk2); DictionaryChunksWrapper wrapper = new DictionaryChunksWrapper(dictionaryChunks); byte[] expected1 = new byte[]{1, 2, 3}; byte[] expected2 = new byte[]{4, 5, 6}; byte[] expected3 = new byte[]{7, 8, 9}; byte[] expected4 = new byte[]{10, 11, 12}; Assert.assertArrayEquals(expected1, wrapper.next()); Assert.assertArrayEquals(expected2, wrapper.next()); Assert.assertArrayEquals(expected3, wrapper.next()); Assert.assertArrayEquals(expected4, wrapper.next()); }
@Test public void testGetEachDimColumnValueSize() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema("column1", "string")); columnsInTable.add(new ColumnSchema("column2", "int")); columnsInTable.add(new ColumnSchema("column3", "double")); int[] columnCardinality = {10, 20, 30}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); int[] expected = {10, 20, 30}; assertArrayEquals(expected, segmentProperties.getEachDimColumnValueSize()); }
@Test public void testGetMaskedByteRange() { List<QueryDimension> queryDimensions = new ArrayList<>(); queryDimensions.add(new QueryDimension(new Dimension(1), "value1")); queryDimensions.add(new QueryDimension(new Dimension(2), "value2")); queryDimensions.add(new QueryDimension(new Dimension(3), "value3")); KeyGenerator keyGenerator = new KeyGenerator(); int[] expected = {0, 1, 2, 3, 4, 5}; int[] result = QueryUtil.getMaskedByteRange(queryDimensions, keyGenerator); assertArrayEquals(expected, result); }
@Test public void testGetDimensionByName() { CarbonTable carbonTable = new CarbonTable(); CarbonDimension carbonDimension = new CarbonDimension("tableName", "columnName"); List<CarbonDimension> dimList = new ArrayList<>(); dimList.add(carbonDimension); carbonTable.tableDimensionsMap.put("tableName", dimList); assertEquals(carbonDimension, carbonTable.getDimensionByName("tableName", "columnName")); assertNull(carbonTable.getDimensionByName("tableName", "invalidColumnName")); }
@Test public void testGetInstance() { CarbonMetadata carbonMetadata = CarbonMetadata.getInstance(); assertNotNull(carbonMetadata); }
@Test public void testGetFactTableName() { CarbonTable carbonTable = new CarbonTable(); String factTableName = carbonTable.getFactTableName(); assertNotNull(factTableName); assertEquals("", factTableName); }
@Test public void testGetComplexDimColumnCardinality() { List<ColumnSchema> columnsInTable = new ArrayList<>(); ColumnSchema column1 = new ColumnSchema(); ColumnSchema column2 = new ColumnSchema(); columnsInTable.add(column1); columnsInTable.add(column2); int[] columnCardinality = {10, 20}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); int[] expected = {10, 20}; int[] actual = segmentProperties.getComplexDimColumnCardinality(); assertArrayEquals(expected, actual); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ForwardDictionaryCache<String, String> cache = new ForwardDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testGetDimensionOrdinalToBlockMapping() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema("column1", ColumnType.INT)); columnsInTable.add(new ColumnSchema("column2", ColumnType.STRING)); int[] columnCardinality = {100, 200}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); Map<Integer, Integer> dimensionOrdinalToBlockMapping = segmentProperties.getDimensionOrdinalToBlockMapping(); assertNotNull(dimensionOrdinalToBlockMapping); assertEquals(2, dimensionOrdinalToBlockMapping.size()); assertEquals(100, (int) dimensionOrdinalToBlockMapping.get(0)); assertEquals(200, (int) dimensionOrdinalToBlockMapping.get(1)); }
@Test public void testGetComplexDimensions() { List<ColumnSchema> columnsInTable = new ArrayList<>(); ColumnSchema column1 = new ColumnSchema(); ColumnSchema column2 = new ColumnSchema(); columnsInTable.add(column1); columnsInTable.add(column2); int[] columnCardinality = {10, 20}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); List<CarbonDimension> complexDimensions = segmentProperties.getComplexDimensions(); assertNotNull(complexDimensions); assertEquals(0, complexDimensions.size()); }
@Test public void testGetNumberOfMeasures() { CarbonTable carbonTable = new CarbonTable(); Map<String, List<String>> tableMeasuresMap = new HashMap<>(); List<String> measures = new ArrayList<>(); measures.add("measure1"); measures.add("measure2"); tableMeasuresMap.put("table1", measures); carbonTable.tableMeasuresMap = tableMeasuresMap; int numberOfMeasures = carbonTable.getNumberOfMeasures("table1"); assertEquals(2, numberOfMeasures); }
@Test public void testGetDatabaseName() { CarbonTable carbonTable = new CarbonTable(); String databaseName = carbonTable.getDatabaseName(); assertNotNull(databaseName); assertEquals("default", databaseName); }
@Test public void testGetDimensions() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema()); int[] columnCardinality = {1}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); List<CarbonDimension> dimensions = segmentProperties.getDimensions(); assertNotNull(dimensions); assertEquals(1, dimensions.size()); }
@Test public void testGetNumberOfTables() { CarbonMetadata carbonMetadata = new CarbonMetadata(); int numberOfTables = carbonMetadata.getNumberOfTables(); assertEquals(0, numberOfTables); }
@Test public void testWriteDictionaryFile() throws IOException { List<DictionaryChunk> oneDictionaryChunkList = new ArrayList<>(); DictionaryChunk dictionaryChunk = new DictionaryChunk(); dictionaryChunk.setDictionaryValues(new ArrayList<>()); oneDictionaryChunkList.add(dictionaryChunk); CarbonDictionaryWriterImpl writer = new CarbonDictionaryWriterImpl("hdfsStorePath", new CarbonTableIdentifier("table", "database"), new ColumnIdentifier("column", "table", "database")); writer.writeDictionaryFile(); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ReverseDictionaryCache<String, String> cache = new ReverseDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testGetAll() throws CarbonUtilException { ReverseDictionaryCache<String, String> cache = new ReverseDictionaryCache<>("path", new CarbonLRUCache(100)); List<DictionaryColumnUniqueIdentifier> identifiers = new ArrayList<>(); identifiers.add(new DictionaryColumnUniqueIdentifier("table1", "column1", "dict1")); identifiers.add(new DictionaryColumnUniqueIdentifier("table2", "column2", "dict2")); List<Dictionary> dictionaries = cache.getAll(identifiers); assertNotNull(dictionaries); assertEquals(2, dictionaries.size()); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ReverseDictionaryCache<String, String> cache = new ReverseDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testGetIfPresent() { String carbonStorePath = "/path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(); ReverseDictionaryCache cache = new ReverseDictionaryCache(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("columnId", "tableId", "databaseName", "tableName", "columnName", "columnUniqueId"); Dictionary dictionary = cache.getIfPresent(identifier); assertNull(dictionary); ColumnReverseDictionaryInfo columnReverseDictionaryInfo = new ColumnReverseDictionaryInfo(); carbonLRUCache.put(cache.getLruCacheKey(identifier.getColumnIdentifier().getColumnId(), CacheType.REVERSE_DICTIONARY), columnReverseDictionaryInfo); dictionary = cache.getIfPresent(identifier); assertNotNull(dictionary); assertTrue(dictionary instanceof ReverseDictionary); }
@Test public void testGetTableUniqueName() { CarbonTable carbonTable = new CarbonTable(); String tableUniqueName = "testTable"; carbonTable.tableUniqueName = tableUniqueName; assertEquals(tableUniqueName, carbonTable.getTableUniqueName()); }
@Test public void testWriteDictionaryFile() throws IOException { List<DictionaryChunk> oneDictionaryChunkList = new ArrayList<>(); DictionaryChunk dictionaryChunk = new DictionaryChunk(); dictionaryChunk.setDictionaryData(new byte[]{1, 2, 3}); dictionaryChunk.setDictionaryValues(new String[]{"value1", "value2", "value3"}); oneDictionaryChunkList.add(dictionaryChunk); CarbonDictionaryWriterImpl writer = new CarbonDictionaryWriterImpl("hdfsStorePath", new CarbonTableIdentifier("dbName", "tableName", "tableId"), new ColumnIdentifier("columnName", "columnId", "dataType")); Field field = CarbonDictionaryWriterImpl.class.getDeclaredField("oneDictionaryChunkList"); field.setAccessible(true); field.set(writer, oneDictionaryChunkList); writer.writeDictionaryFile(); }
@Test public void testGetDimensionBitLength() { int[] dimCardinality = {10, 20, 30}; int[] dimPartitioner = {1, 2}; int[] expectedBitLength = {4, 5, 5}; int[] actualBitLength = CarbonUtil.getDimensionBitLength(dimCardinality, dimPartitioner); assertArrayEquals(expectedBitLength, actualBitLength); }
@Test public void testGetNumberOfDimensions() { CarbonTable carbonTable = new CarbonTable(); Map<String, List<String>> tableDimensionsMap = new HashMap<>(); List<String> dimensions = new ArrayList<>(); dimensions.add("Dimension1"); dimensions.add("Dimension2"); tableDimensionsMap.put("Table1", dimensions); carbonTable.tableDimensionsMap = tableDimensionsMap; int numberOfDimensions = carbonTable.getNumberOfDimensions("Table1"); assertEquals(2, numberOfDimensions); }
@Test public void testGetAll() throws CarbonUtilException { List<DictionaryColumnUniqueIdentifier> identifiers = new ArrayList<>(); DictionaryColumnUniqueIdentifier identifier1 = new DictionaryColumnUniqueIdentifier("table1", "column1", "column_id1"); DictionaryColumnUniqueIdentifier identifier2 = new DictionaryColumnUniqueIdentifier("table2", "column2", "column_id2"); identifiers.add(identifier1); identifiers.add(identifier2); ForwardDictionaryCache cache = new ForwardDictionaryCache("path/to/store", new CarbonLRUCache()); List<Dictionary> dictionaries = cache.getAll(identifiers); assertNotNull(dictionaries); assertEquals(2, dictionaries.size()); }
@Test public void testGetDimColumnsCardinality() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema("column1", "type1")); columnsInTable.add(new ColumnSchema("column2", "type2")); int[] columnCardinality = {10, 20}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); int[] expected = {10, 20}; assertArrayEquals(expected, segmentProperties.getDimColumnsCardinality()); }
@Test public void testWriteDictionaryFile() throws IOException { List<DictionaryChunk> oneDictionaryChunkList = new ArrayList<>(); DictionaryChunk dictionaryChunk = new DictionaryChunk(); dictionaryChunk.setDictionaryValues(new ArrayList<>()); oneDictionaryChunkList.add(dictionaryChunk); CarbonDictionaryWriterImpl writer = new CarbonDictionaryWriterImpl("hdfsStorePath", new CarbonTableIdentifier("table", "database"), new ColumnIdentifier("column", "table", "database")); writer.writeDictionaryFile(); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testGetMaskedByteRangeBasedOrdinal() { List<Integer> ordinals = new ArrayList<>(); ordinals.add(1); ordinals.add(2); ordinals.add(3); KeyGenerator keyGenerator = new KeyGenerator(); int[] result = QueryUtil.getMaskedByteRangeBasedOrdinal(ordinals, keyGenerator); int[] expected = {0, 1, 2, 3, 4, 5, 6, 7}; assertArrayEquals(expected, result); }
@Test public void testGetEachComplexDimColumnValueSize() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema("column1", "string")); columnsInTable.add(new ColumnSchema("column2", "int")); int[] columnCardinality = {10, 20}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); int[] expected = {10, 20}; assertArrayEquals(expected, segmentProperties.getEachComplexDimColumnValueSize()); }
@Test public void testDictionaryChunksWrapper() { List<List<byte[]>> dictionaryChunks = new ArrayList<>(); List<byte[]> chunk1 = new ArrayList<>(); chunk1.add("hello".getBytes()); chunk1.add("world".getBytes()); List<byte[]> chunk2 = new ArrayList<>(); chunk2.add("foo".getBytes()); chunk2.add("bar".getBytes()); dictionaryChunks.add(chunk1); dictionaryChunks.add(chunk2); DictionaryChunksWrapper wrapper = new DictionaryChunksWrapper(dictionaryChunks); int expectedSize = 4; int actualSize = wrapper.getSize(); assertEquals(expectedSize, actualSize); byte[] expectedFirst = "hello".getBytes(); byte[] actualFirst = wrapper.next(); assertArrayEquals(expectedFirst, actualFirst); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testEquals() { TableSchema table1 = new TableSchema(); table1.tableId = 1; table1.tableName = "Table1"; TableSchema table2 = new TableSchema(); table2.tableId = 1; table2.tableName = "Table1"; TableSchema table3 = new TableSchema(); table3.tableId = 2; table3.tableName = "Table2"; assertTrue(table1.equals(table2)); assertFalse(table1.equals(table3)); assertFalse(table1.equals(null)); assertFalse(table1.equals("Table1")); }
@Test public void testGetMeasuresOrdinalToBlockMapping() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema("column1", "int")); columnsInTable.add(new ColumnSchema("column2", "string")); int[] columnCardinality = {100, 200}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); Map<Integer, Integer> measuresOrdinalToBlockMapping = segmentProperties.getMeasuresOrdinalToBlockMapping(); assertNotNull(measuresOrdinalToBlockMapping); assertEquals(0, measuresOrdinalToBlockMapping.size()); }
@Test public void testEquals() { TableInfo table1 = new TableInfo(); TableInfo table2 = new TableInfo(); TableInfo table3 = new TableInfo(); table3.setDatabaseName("database1"); table3.setTableUniqueName("table1"); assertTrue(table1.equals(table1)); assertTrue(table1.equals(table2)); assertTrue(table2.equals(table1)); assertTrue(table1.equals(table2)); assertTrue(table2.equals(table3)); assertTrue(table1.equals(table3)); assertFalse(table1.equals(null)); assertFalse(table1.equals("table1")); table2.setDatabaseName("database2"); assertFalse(table1.equals(table2)); table2.setDatabaseName("database1"); table2.setTableUniqueName("table2"); assertFalse(table1.equals(table2)); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testGetInstance() { CacheProvider instance1 = CacheProvider.getInstance(); CacheProvider instance2 = CacheProvider.getInstance(); assertNotNull(instance1); assertNotNull(instance2); assertSame(instance1, instance2); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ReverseDictionaryCache<String, String> cache = new ReverseDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testGetMeasures() { List<ColumnSchema> columnsInTable = new ArrayList<>(); columnsInTable.add(new ColumnSchema()); int[] columnCardinality = {1}; SegmentProperties segmentProperties = new SegmentProperties(columnsInTable, columnCardinality); List<CarbonMeasure> measures = segmentProperties.getMeasures(); assertNotNull(measures); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ForwardDictionaryCache<String, String> cache = new ForwardDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testCreateCache() { CacheProvider cacheProvider = new CacheProvider(); Cache<String, Integer> cache = cacheProvider.createCache(CacheType.LRU, "/path/to/store"); assertNotNull(cache); assertEquals(CacheType.LRU, cache.getCacheType()); assertEquals("/path/to/store", cache.getCarbonStorePath()); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testGetMaskedByteRange() { List<QueryDimension> queryDimensions = new ArrayList<>(); queryDimensions.add(new QueryDimension(new Dimension(1), "value1")); queryDimensions.add(new QueryDimension(new Dimension(2), "value2")); queryDimensions.add(new QueryDimension(new Dimension(3), "value3")); KeyGenerator keyGenerator = new KeyGenerator(); int[] expected = {0, 1, 2, 3, 4, 5}; int[] result = QueryUtil.getMaskedByteRange(queryDimensions, keyGenerator); assertArrayEquals(expected, result); }
@Test public void testWriteFooter() throws IOException { String filePath = "testFilePath"; long currentPosition = 10L; FileFooter footer = new FileFooter(); CarbonFooterWriter writer = new CarbonFooterWriter(filePath); writer.writeFooter(footer, currentPosition); assertEquals(VERSION_NUMBER, footer.getVersion()); verify(thriftWriter, times(1)).close(); }
@Test public void testGetMaxKeyBasedOnDimensions() throws KeyGenException { QueryDimension queryDimension1 = new QueryDimension(new Dimension("dimension1", 0), "value1"); QueryDimension queryDimension2 = new QueryDimension(new Dimension("dimension2", 1), "value2"); List<QueryDimension> queryDimensions = new ArrayList<>(); queryDimensions.add(queryDimension1); queryDimensions.add(queryDimension2); KeyGenerator generator = new KeyGenerator(2); byte[] expected = generator.generateKey(new long[]{Long.MAX_VALUE, Long.MAX_VALUE}); byte[] result = QueryUtil.getMaxKeyBasedOnDimensions(queryDimensions, generator); assertArrayEquals(expected, result); }
@Test public void testGetCarbonTable() { CarbonMetadata carbonMetadata = new CarbonMetadata(); String tableUniqueName = "myTable"; CarbonTable carbonTable = new CarbonTable(); carbonMetadata.tableInfoMap.put(tableUniqueName.toLowerCase(), carbonTable); assertEquals(carbonTable, carbonMetadata.getCarbonTable(tableUniqueName)); }
@Test public void testGet() throws CarbonUtilException { String carbonStorePath = "path/to/store"; CarbonLRUCache carbonLRUCache = new CarbonLRUCache(100); ForwardDictionaryCache<String, String> cache = new ForwardDictionaryCache<>(carbonStorePath, carbonLRUCache); DictionaryColumnUniqueIdentifier identifier = new DictionaryColumnUniqueIdentifier("column", "table", "database"); Dictionary dictionary = cache.get(identifier); assertNull(dictionary); }
@Test public void testWriteDictionaryFile() throws IOException { List<DictionaryChunk> oneDictionaryChunkList = new ArrayList<>(); DictionaryChunk dictionaryChunk = new DictionaryChunk(); dictionaryChunk.setDictionaryValues(new ArrayList<>()); oneDictionaryChunkList.add(dictionaryChunk); CarbonDictionaryWriterImpl writer = new CarbonDictionaryWriterImpl("hdfsStorePath", new CarbonTableIdentifier("table", "database"), new ColumnIdentifier("column", "table", "database")); writer.writeDictionaryFile(); }
@Test public void testGetFromNodeId() { Edge edge = new Edge(1, 2, 3.0); assertEquals(1, edge.getFromNodeId()); }
@Test public void testHashCode() { Node node1 = new Node(1L); Node node2 = new Node(2L); Node node3 = new Node(1L); assertNotEquals(node1.hashCode(), node2.hashCode()); assertEquals(node1.hashCode(), node3.hashCode()); }
@Test public void testGetWeight() { Edge edge = new Edge(1, 2, 3.5); double expectedWeight = 3.5; double actualWeight = edge.getWeight(); assertEquals(expectedWeight, actualWeight, 0.0); }
@Test public void testGetAdjacent() { Edge edge = new Edge(1, 2); assertEquals(2, edge.getAdjacent(1)); assertEquals(1, edge.getAdjacent(2)); Edge edgeWithCost = new Edge(3, 4, 2.5); assertEquals(4, edgeWithCost.getAdjacent(3)); assertEquals(3, edgeWithCost.getAdjacent(4)); }
@Test public void testGetDistance() { DistanceVector distanceVector = new DistanceVector(1L); distanceVector.vector.put(2L, new Vector(2L, 5.0)); distanceVector.vector.put(3L, new Vector(3L, 10.0)); assertEquals(5.0, distanceVector.getDistance(2L), 0.0); assertEquals(10.0, distanceVector.getDistance(3L), 0.0); }
@Test public void testEquals() { Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(1); assertTrue(node1.equals(node3)); assertFalse(node1.equals(node2)); }
@Test public void testEquals() { Edge edge1 = new Edge(1, 2, 3.0); Edge edge2 = new Edge(1, 2, 3.0); Edge edge3 = new Edge(2, 1, 3.0); Edge edge4 = new Edge(1, 2, 4.0); Object obj = new Object(); assertTrue(edge1.equals(edge2)); assertTrue(edge2.equals(edge1)); assertFalse(edge1.equals(edge3)); assertFalse(edge1.equals(edge4)); assertFalse(edge1.equals(obj)); }
@Test public void testToString() { Edge edge = new Edge(1, 2, 3.5); String expected = "1|2|3.5"; String actual = edge.toString(); assertEquals(expected, actual); }
@Test public void testGetElement() { DistanceVector distanceVector = new DistanceVector(1); DistanceElement element = distanceVector.getElement(2); assertNotNull(element); assertEquals(2, element.getId()); }
@Test public void testGetId() { Node node = new Node(12345L); assertEquals(12345L, node.getId()); }
@Test public void testIsBidirectional() { Edge edge = new Edge(1, 2, 3.0); assertFalse(edge.isBidirectional()); }
@Test public void testHashCode() { Edge edge1 = new Edge(); Edge edge2 = new Edge(1, 2); Edge edge3 = new Edge(1, 2, 3.0); assertNotEquals(edge1.hashCode(), edge2.hashCode()); assertNotEquals(edge1.hashCode(), edge3.hashCode()); assertNotEquals(edge2.hashCode(), edge3.hashCode()); Edge edge4 = new Edge(1, 2); Edge edge5 = new Edge(1, 2, 4.0); assertEquals(edge2.hashCode(), edge4.hashCode()); assertNotEquals(edge2.hashCode(), edge5.hashCode()); }
@Test public void testGetToNodeId() { Edge edge = new Edge(1, 2, 3.0); assertEquals(2, edge.getToNodeId()); }
@Test public void testReadGeneralProductInformation() { SafeReader safeReader = new SafeReader("path/to/safe"); safeReader.readGeneralProductInformation(); }
@Test public void testGetMeasurementFiles() { SafeReader safeReader = new SafeReader("path/to/safe"); Collection<String> measurementFiles = safeReader.getMesasurementFiles(); assertNotNull(measurementFiles); assertFalse(measurementFiles.isEmpty()); for (String file : measurementFiles) { assertNotNull(file); assertTrue(file.endsWith(".txt")); } }
@Test public void testReadorbitInformation() throws JAXBException, SAXException { SumoSafeReader reader = new SumoSafeReader("path/to/safe/file.xml"); reader.readorbitInformation(); OrbitInformation orbitWrapper = reader.getOrbitWrapper(); assertEquals("123", orbitWrapper.getOrbitNumberStart()); assertEquals("456", orbitWrapper.getOrbitNumberStop()); assertEquals("789", orbitWrapper.getCycleNumber()); assertEquals("ABC", orbitWrapper.getPhaseIdentifier()); }
@Test public void testReadGeneralProductInformation() throws JAXBException, SAXException { SumoSafeReader reader = new SumoSafeReader("path/to/safe"); reader.readGeneralProductInformation(); ProductInformation info = reader.getProductInformation(); assertNotNull(info); assertEquals("value1", info.getValueInfo("name1")); assertEquals("value2", info.getValueInfo("name2")); }
@Test public void testSafeReaderConstructor() throws IllegalArgumentException, IOException { String safePath = "path/to/safe"; SafeReader safeReader = new SafeReader(safePath); assertNotNull(safeReader); }
@Test public void testGetDataObjects() { SafeReader safeReader = new SafeReader("path/to/safe"); Collection<DataObject> dataObjects = safeReader.getDataObjects(); assertNotNull(dataObjects); assertEquals(0, dataObjects.size()); }
@Test public void testSumoSafeReader() throws JDOMException, IOException, JAXBException { SumoSafeReader reader = new SumoSafeReader("path/to/safe.xml"); assertNotNull(reader.safe); assertNotNull(reader.xFactory); assertEquals("path/to/safe.xml", reader.safePath); }
@Test public void testGetMetadataObjects() { SafeReader safeReader = new SafeReader("path/to/safe"); Collection<MetadataObject> metadataObjects = safeReader.getMetadataObjects(); assertNotNull(metadataObjects); assertFalse(metadataObjects.isEmpty()); }
@Test public void testReadGeneralProductInformation() throws JAXBException, SAXException { SumoSafeReader reader = new SumoSafeReader("path/to/safe"); reader.readGeneralProductInformation(); ProductInformation info = reader.getProductInformation(); assertNotNull(info); assertEquals("value1", info.getValueInfo("name1")); assertEquals("value2", info.getValueInfo("name2")); }
@Test public void testGetAnnotationsByProperty() { Property property = new Property("name", "John"); AnnotationDAO annotationDAO = mock(AnnotationDAO.class); Collection<Annotation> expectedAnnotations = new ArrayList<>(); expectedAnnotations.add(new Annotation("id1", "description1")); expectedAnnotations.add(new Annotation("id2", "description2")); when(annotationDAO.readByProperty(property)).thenReturn(expectedAnnotations); DAOBasedAnnotationService daoBasedAnnotationService = new DAOBasedAnnotationService(annotationDAO); Collection<Annotation> actualAnnotations = daoBasedAnnotationService.getAnnotationsByProperty(property); assertEquals(expectedAnnotations, actualAnnotations); }
@Test public void testCompareCollectionContents() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 2, 1); List<Integer> list3 = Arrays.asList(1, 2, 3, 4); Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("c", "b", "a")); Set<String> set3 = new HashSet<>(Arrays.asList("a", "b", "c", "d")); assertTrue(CollectionUtils.compareCollectionContents(list1, list2)); assertTrue(CollectionUtils.compareCollectionContents(set1, set2)); assertFalse(CollectionUtils.compareCollectionContents(list1, list3)); assertFalse(CollectionUtils.compareCollectionContents(set1, set3)); }
@Test public void testCompareCollectionContents() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 2, 1); List<Integer> list3 = Arrays.asList(1, 2, 3, 4); Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("c", "b", "a")); Set<String> set3 = new HashSet<>(Arrays.asList("a", "b", "c", "d")); assertTrue(CollectionUtils.compareCollectionContents(list1, list2)); assertTrue(CollectionUtils.compareCollectionContents(set1, set2)); assertFalse(CollectionUtils.compareCollectionContents(list1, list3)); assertFalse(CollectionUtils.compareCollectionContents(set1, set3)); }
@Test public void testGetPropertyTypes() { DAOBasedPropertyTypeService service = new DAOBasedPropertyTypeService(mock(PropertyDAO.class)); Collection<String> propertyTypes = service.getPropertyTypes(); assertNotNull(propertyTypes); }
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testCanProcess() { ParenthesesProcessor processor = new ParenthesesProcessor(); assertTrue(processor.canProcess("This is a (test) string.")); assertTrue(processor.canProcess("(test)")); assertFalse(processor.canProcess("This is a test string.")); assertFalse(processor.canProcess("(test")); assertFalse(processor.canProcess("test)")); }
@Test public void testGetNamespace() throws URISyntaxException { URI uri = URIUtils.getNamespace("rdf"); assertEquals(new URI("http: }
@Test public void testCompareCollectionContents() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 2, 1); List<Integer> list3 = Arrays.asList(1, 2, 3, 4); Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("c", "b", "a")); Set<String> set3 = new HashSet<>(Arrays.asList("a", "b", "c", "d")); assertTrue(CollectionUtils.compareCollectionContents(list1, list2)); assertTrue(CollectionUtils.compareCollectionContents(set1, set2)); assertFalse(CollectionUtils.compareCollectionContents(list1, list3)); assertFalse(CollectionUtils.compareCollectionContents(set1, set3)); }
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testDoQuery() { Query query = new Query(); LuceneDocumentMapper<MyObject> mapper = new LuceneDocumentMapper<MyObject>() { @Override public MyObject map(Document doc) { } }; ZoomaLuceneSearchService service = new ZoomaLuceneSearchService(); List<MyObject> result = service.doQuery(query, mapper); assertNotNull(result); }
@Test public void testCompareCollectionContents() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 2, 1); List<Integer> list3 = Arrays.asList(1, 2, 3, 4); Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("c", "b", "a")); Set<String> set3 = new HashSet<>(Arrays.asList("a", "b", "c", "d")); assertTrue(CollectionUtils.compareCollectionContents(list1, list2)); assertTrue(CollectionUtils.compareCollectionContents(set1, set2)); assertFalse(CollectionUtils.compareCollectionContents(list1, list3)); assertFalse(CollectionUtils.compareCollectionContents(set1, set3)); }
@Test public void testGetPrimaryLabel() { URI concept = URI.create("http: OntologyDAO ontologyDAO = mock(OntologyDAO.class); when(ontologyDAO.getSemanticTagLabel(concept)).thenReturn("Example Label"); LabelUtils.ontologyDAO = ontologyDAO; String label = LabelUtils.getPrimaryLabel(concept); assertEquals("Example Label", label); }
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testCanProcess() { ParenthesesProcessor processor = new ParenthesesProcessor(); assertTrue(processor.canProcess("This is a (test) string.")); assertTrue(processor.canProcess("(test)")); assertFalse(processor.canProcess("This is a test string.")); assertFalse(processor.canProcess("(test")); assertFalse(processor.canProcess("test)")); }
@Test public void testProcessSearchString() throws IllegalArgumentException, InterruptedException { TimeProcessor timeProcessor = new TimeProcessor(); List<String> result = timeProcessor.processSearchString("I have 2.5 hours free time today"); assertEquals(Collections.singletonList("I have free time today"), result); }
@Test public void testGetSupplementaryRDFStream() throws Exception { AnnotationFactory annotationFactory = mock(AnnotationFactory.class); OntologyLoader owlLoader = mock(OntologyLoader.class); String datasourceName = "testDatasource"; OWLOntology ontology = mock(OWLOntology.class); OWLOntologyManager manager = mock(OWLOntologyManager.class); RDFXMLOntologyFormat format = mock(RDFXMLOntologyFormat.class); PipedOutputStream out = mock(PipedOutputStream.class); PipedInputStream in = mock(PipedInputStream.class); when(owlLoader.getOntology()).thenReturn(ontology); when(ontology.getOWLOntologyManager()).thenReturn(manager); whenNew(PipedOutputStream.class).withNoArguments().thenReturn(out); whenNew(PipedInputStream.class).withArguments(out).thenReturn(in); doAnswer(invocation -> { ((Runnable) invocation.getArgument(0)).run(); return null; }).whenNew(Thread.class).withAnyArguments().thenReturn(mock(Thread.class)); doNothing().when(manager).saveOntology(ontology, format, out); OWLAnnotationDAO dao = new OWLAnnotationDAO(annotationFactory, owlLoader, datasourceName); InputStream result = dao.getSupplementaryRDFStream(); assertNotNull(result); verify(owlLoader).getOntology(); verify(ontology).getOWLOntologyManager(); verifyNew(PipedOutputStream.class).withNoArguments(); verifyNew(PipedInputStream.class).withArguments(out); verifyNew(Thread.class).withAnyArguments(); verify(manager).saveOntology(ontology, format, out); }
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testGetAnnotationsByStudy() { Study study = new Study(); AnnotationDAO annotationDAO = mock(AnnotationDAO.class); Collection<Annotation> expectedAnnotations = new ArrayList<>(); expectedAnnotations.add(new Annotation()); when(annotationDAO.readByStudy(study)).thenReturn(expectedAnnotations); DAOBasedAnnotationService daoBasedAnnotationService = new DAOBasedAnnotationService(annotationDAO); Collection<Annotation> actualAnnotations = daoBasedAnnotationService.getAnnotationsByStudy(study); assertEquals(expectedAnnotations, actualAnnotations); }
@Test public void testGetProperties() { DAOBasedPropertyService daoBasedPropertyService = new DAOBasedPropertyService(mock(PropertyDAO.class)); Collection<Property> properties = daoBasedPropertyService.getProperties(); assertNotNull(properties); }
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testGetProperty() { DAOBasedPropertyService daoBasedPropertyService = new DAOBasedPropertyService(mockedDAO); Property property = daoBasedPropertyService.getProperty("testShortname"); assertNotNull(property); assertEquals("testURI", property.getURI()); }
@Test public void testGetURI() throws URISyntaxException { String shortform = "example:resource"; URI expectedURI = new URI("http: URI actualURI = URIUtils.getURI(shortform); assertEquals(expectedURI, actualURI); }
@Test public void testGetPropertyTypes() { DAOBasedPropertyTypeService service = new DAOBasedPropertyTypeService(mock(PropertyDAO.class)); Collection<String> propertyTypes = service.getPropertyTypes(); assertNotNull(propertyTypes); }
@Test public void testGetAnnotation() { DAOBasedAnnotationService service = new DAOBasedAnnotationService(mockedDAO); Annotation expectedAnnotation = new Annotation(); expectedAnnotation.setUri("http: when(mockedDAO.getURIFromShortname("shortname")).thenReturn("http: when(mockedDAO.getAnnotation("http: Annotation actualAnnotation = service.getAnnotation("shortname"); assertEquals(expectedAnnotation, actualAnnotation); } Note: mockedDAO is a mock object of the DAO class used in the constructor of DAOBasedAnnotationService.
@Test public void testGetShortform() throws URISyntaxException { URI uri = new URI("http: String expectedShortform = "ex:resource"; String actualShortform = URIUtils.getShortform(uri); assertEquals(expectedShortform, actualShortform); }
@Test public void testDoQuery() { Query query = new Query(); LuceneDocumentMapper<MyObject> mapper = new LuceneDocumentMapper<>(MyObject.class); ZoomaLuceneSearchService service = new ZoomaLuceneSearchService(); List<MyObject> result = service.doQuery(query, mapper); assertNotNull(result); }
@Test public void testDoQuery() { Query query = new Query(); LuceneDocumentMapper<MyObject> mapper = new LuceneDocumentMapper<MyObject>() { @Override public MyObject map(Document doc) { } }; ZoomaLuceneSearchService service = new ZoomaLuceneSearchService(); List<MyObject> result = service.doQuery(query, mapper); assertNotNull(result); }
@Test public void testGetAnnotations() { AnnotationDAO dao = mock(AnnotationDAO.class); Collection<Annotation> annotations = new ArrayList<>(); annotations.add(new Annotation("annotation1")); annotations.add(new Annotation("annotation2")); when(dao.read()).thenReturn(annotations); DAOBasedAnnotationService service = new DAOBasedAnnotationService(dao); Collection<Annotation> result = service.getAnnotations(); assertEquals(2, result.size()); assertTrue(result.contains(new Annotation("annotation1"))); assertTrue(result.contains(new Annotation("annotation2"))); }
@Test public void testGetAnnotations() { AnnotationDAO dao = mock(AnnotationDAO.class); Collection<Annotation> annotations = new ArrayList<>(); annotations.add(new Annotation("annotation1")); annotations.add(new Annotation("annotation2")); when(dao.read()).thenReturn(annotations); DAOBasedAnnotationService service = new DAOBasedAnnotationService(dao); Collection<Annotation> result = service.getAnnotations(); assertEquals(2, result.size()); assertTrue(result.contains(new Annotation("annotation1"))); assertTrue(result.contains(new Annotation("annotation2"))); }
@Test public void testCompareCollectionContents() { List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(3, 2, 1); List<Integer> list3 = Arrays.asList(1, 2, 3, 4); Set<String> set1 = new HashSet<>(Arrays.asList("a", "b", "c")); Set<String> set2 = new HashSet<>(Arrays.asList("c", "b", "a")); Set<String> set3 = new HashSet<>(Arrays.asList("a", "b", "c", "d")); assertTrue(CollectionUtils.compareCollectionContents(list1, list2)); assertTrue(CollectionUtils.compareCollectionContents(set1, set2)); assertFalse(CollectionUtils.compareCollectionContents(list1, list3)); assertFalse(CollectionUtils.compareCollectionContents(set1, set3)); }
@Test public void testGetAnnotationsByBiologicalEntity() { BiologicalEntity biologicalEntity = new BiologicalEntity(); AnnotationDAO annotationDAO = mock(AnnotationDAO.class); Collection<Annotation> expectedAnnotations = new ArrayList<>(); expectedAnnotations.add(new Annotation()); when(annotationDAO.readByBiologicalEntity(biologicalEntity)).thenReturn(expectedAnnotations); DAOBasedAnnotationService daoBasedAnnotationService = new DAOBasedAnnotationService(annotationDAO); Collection<Annotation> actualAnnotations = daoBasedAnnotationService.getAnnotationsByBiologicalEntity(biologicalEntity); assertEquals(expectedAnnotations, actualAnnotations); }
@Test public void testGetAnnotationsBySemanticTag() { DAOBasedAnnotationService service = new DAOBasedAnnotationService(mockedDAO); String shortname = "test"; URI uri = URI.create("http: when(service.getURIFromShortname(shortname)).thenReturn(uri); Annotation annotation = new Annotation(uri); Collection<Annotation> expectedAnnotations = new ArrayList<>(); expectedAnnotations.add(annotation); when(service.getAnnotationsBySemanticTag(uri)).thenReturn(expectedAnnotations); Collection<Annotation> actualAnnotations = service.getAnnotationsBySemanticTag(shortname); assertEquals(expectedAnnotations, actualAnnotations); }
@Test public void testGetPrefixMappings() { Map<String, String> expectedPrefixMappings = new HashMap<>(); expectedPrefixMappings.put("key1", "value1"); expectedPrefixMappings.put("key2", "value2"); expectedPrefixMappings.put("key3", "value3"); URIUtils.prefixMappings = expectedPrefixMappings; Map<String, String> actualPrefixMappings = URIUtils.getPrefixMappings(); assertEquals(expectedPrefixMappings, actualPrefixMappings); }
@Test public void testGetProperties() { DAOBasedPropertyService daoBasedPropertyService = new DAOBasedPropertyService(mock(PropertyDAO.class)); Collection<Property> properties = daoBasedPropertyService.getProperties(); assertNotNull(properties); }
@Test public void testCanProcess() { TimeProcessor timeProcessor = new TimeProcessor(); assertTrue(timeProcessor.canProcess("12:30 PM")); assertTrue(timeProcessor.canProcess("3:45 AM")); assertTrue(timeProcessor.canProcess("9:00")); assertFalse(timeProcessor.canProcess("Hello World")); assertFalse(timeProcessor.canProcess("12:")); assertFalse(timeProcessor.canProcess(":30")); }
@Test public void testReadDataSet() throws IOException { byte[] bytes = {0x00, 0x01, 0x02, 0x03}; ByteArrayInputStream in = new ByteArrayInputStream(bytes); DicomInputStream dicomIn = new DicomInputStream(in); DicomObject dicomObj = dicomIn.readDataSet(); assertNotNull(dicomObj); }
@Test public void testWriteFileMetaInformation() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); DicomOutputStream dicomOut = new DicomOutputStream(out); DicomObject fmi = new BasicDicomObject(); fmi.putString(Tag.TransferSyntaxUID, VR.UI, "1.2.840.10008.1.2.1"); dicomOut.writeFileMetaInformation(fmi); byte[] bytes = out.toByteArray(); assertEquals(142, bytes.length); assertEquals('D', bytes[128]); assertEquals('I', bytes[129]); assertEquals('C', bytes[130]); assertEquals('M', bytes[131]); }
@Test public void testReadDataSet() throws IOException { byte[] bytes = {0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; ByteArrayInputStream in = new ByteArrayInputStream(bytes); DicomInputStream dicomInputStream = new DicomInputStream(in); DicomObject dicomObject = dicomInputStream.readDataSet(); assertNotNull(dicomObject); }
@Test public void testWriteDataSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeDataSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testReadDataSet() throws IOException { byte[] bytes = {0x00, 0x01, 0x02, 0x03}; ByteArrayInputStream in = new ByteArrayInputStream(bytes); DicomInputStream dicomIn = new DicomInputStream(in); DicomObject dicomObj = dicomIn.readDataSet(); assertNotNull(dicomObj); }
@Test public void testSpoolBulkData() throws IOException { InputStream inputStream = new ByteArrayInputStream("test data".getBytes()); DicomInputStream dicomInputStream = new DicomInputStream(inputStream); Supplier<Path> bulkDataSpoolPathSupplier = () -> Paths.get("test/path"); dicomInputStream.spoolBulkData(bulkDataSpoolPathSupplier); assertEquals(bulkDataSpoolPathSupplier, dicomInputStream.parser.getBulkDataSpoolPathSupplier()); assertEquals(DicomInputStream::bulkDataSpoolPathURI, dicomInputStream.parser.getBulkDataURIProducer()); }
@Test public void testReadDataSet() throws IOException { byte[] bytes = {0x00, 0x01, 0x02, 0x03}; ByteArrayInputStream in = new ByteArrayInputStream(bytes); DicomInputStream dicomIn = new DicomInputStream(in); DicomObject dicomObj = dicomIn.readDataSet(); assertNotNull(dicomObj); }
@Test public void testSplit() { String s = "one,two,three"; char delim = ','; String[] expected = {"one", "two", "three"}; String[] result = StringUtils.split(s, delim); assertArrayEquals(expected, result); }
@Test public void testWriteDataSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeDataSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testWriteCommandSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeCommandSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testJoin() { String[] arr = {"apple", "banana", "cherry", "date"}; char delim = '-'; int off = 1; int len = 3; String expected = "banana-cherry-date"; String result = StringUtils.join(arr, off, len, delim); assertEquals(expected, result); }
@Test public void testFormatTM() { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 31, 12, 30, 0); String formattedDateTime = DateTimeUtils.formatTM(dateTime); assertEquals("12:30:00", formattedDateTime); }
@Test public void testParseDA() { LocalDate expected = LocalDate.of(2021, 10, 31); LocalDate result = DateTimeUtils.parseDA("2021-10-31"); assertEquals(expected, result); }
@Test public void testWithBulkDataURI() throws IOException { InputStream inputStream = new ByteArrayInputStream("test data".getBytes()); Path path = Paths.get("test.txt"); DicomInputStream dicomInputStream = new DicomInputStream(inputStream); DicomInputStream result = dicomInputStream.withBulkDataURI(path); assertNotNull(result); }
@Test public void testCut() { String s = "Hello, world!"; int length = 5; char delim = ','; int index = 0; String expected = "Hello"; String result = StringUtils.cut(s, length, delim, index); assertEquals(expected, result); }
@Test public void testFormatDT() { LocalDateTime dateTime = LocalDateTime.of(2021, 10, 31, 12, 0, 0); String formattedDateTime = DateTimeUtils.formatDT(dateTime); assertEquals("31-10-2021 12:00:00", formattedDateTime); }
@Test public void testWriteDataSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeDataSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testTrim() { String s = " hello world "; Trim trim = new Trim(3, 3); String result = StringUtils.trim(s, trim); assertEquals("lo world", result); }
@Test public void testFormatDA() { LocalDate date = LocalDate.of(2021, 10, 31); String formattedDate = DateTimeUtils.formatDA(date); assertEquals("31/10/2021", formattedDate); }
@Test public void testWriteDataSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeDataSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testReadCommandSet() throws IOException { byte[] bytes = {0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00}; ByteArrayInputStream in = new ByteArrayInputStream(bytes); DicomInputStream dicomInputStream = new DicomInputStream(in); DicomObject dicomObject = dicomInputStream.readCommandSet(); assertNotNull(dicomObject); }
@Test public void testWriteDataSet() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DicomOutputStream dos = new DicomOutputStream(baos); DicomObject dcmobj = new BasicDicomObject(); dcmobj.putString(Tag.PatientName, VR.PN, "John Doe"); dos.writeDataSet(dcmobj); dos.close(); byte[] bytes = baos.toByteArray(); assertNotNull(bytes); assertTrue(bytes.length > 0); }
@Test public void testCmetaaAttribute() { AttributeDescriptor attributeDescriptor = new AttributeDescriptor(); Function<Tre, Serializable> accessorFunction = tre -> "test"; CmetaaAttribute cmetaaAttribute = new CmetaaAttribute("longName", "shortName", accessorFunction, attributeDescriptor, "extNitfName"); assertNotNull(cmetaaAttribute); }
@Test public void testAddWkt() { GeometryCollectionBuilder builder = new GeometryCollectionBuilder(); builder.addWkt("POINT(1 1)"); builder.addWkt("LINESTRING(0 0, 1 1)"); String expected = "POINT(1 1), LINESTRING(0 0, 1 1)"; assertEquals(expected, builder.toString()); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.write(new byte[1024 * 1024]); MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(2); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); packetBuffer.write(new byte[1024 * 1024]); result = condition.isRolloverReady(packetBuffer); assertTrue(result); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1010, bitReader.readBits(4)); assertEquals(0b10101010, bitReader.readBits(8)); }
@Test public void testApply() throws IOException, CatalogTransformerException { MetacardTransformer transformer = mock(MetacardTransformer.class); OverviewSupplier supplier = new OverviewSupplier(transformer); Metacard metacard = mock(Metacard.class); Map<String, Serializable> arguments = new HashMap<>(); BinaryContent content = mock(BinaryContent.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{}); BufferedImage image = mock(BufferedImage.class); when(transformer.transform(metacard, arguments)).thenReturn(content); when(content.getInputStream()).thenReturn(inputStream); when(ImageIO.read(inputStream)).thenReturn(image); Optional<BufferedImage> result = supplier.apply(metacard, arguments); assertTrue(result.isPresent()); assertEquals(image, result.get()); }
@Test public void testTransform() throws IOException, CatalogTransformerException { InputTransformer inputTransformer = mock(InputTransformer.class); List<MetacardType> metacardTypes = new ArrayList<>(); Stanag4609Processor stanag4609Processor = mock(Stanag4609Processor.class); KlvHandlerFactory klvHandlerFactory = mock(KlvHandlerFactory.class); KlvHandler defaultKlvHandler = mock(KlvHandler.class); StanagParserFactory stanagParserFactory = mock(StanagParserFactory.class); KlvProcessor klvProcessor = mock(KlvProcessor.class); Double distanceTolerance = 0.5; MpegTsInputTransformer mpegTsInputTransformer = new MpegTsInputTransformer(inputTransformer, metacardTypes, stanag4609Processor, klvHandlerFactory, defaultKlvHandler, stanagParserFactory, klvProcessor, distanceTolerance); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); Metacard metacard = mock(Metacard.class); when(inputTransformer.transform(inputStream)).thenReturn(metacard); Metacard result = mpegTsInputTransformer.transform(inputStream); assertEquals(metacard, result); }
@Test public void testDoAction() throws RolloverActionException { MetacardImpl metacard = new MetacardImpl(); File tempFile = new File("temp.txt"); List<RolloverAction> actionList = new ArrayList<>(); actionList.add(new MockRolloverAction1()); actionList.add(new MockRolloverAction2()); ListRolloverAction listRolloverAction = new ListRolloverAction(actionList); MetacardImpl result = listRolloverAction.doAction(metacard, tempFile); assertNotNull(result); } class MockRolloverAction1 implements RolloverAction { @Override public MetacardImpl doAction(MetacardImpl metacard, File tempFile) throws RolloverActionException { return metacard; } } class MockRolloverAction2 implements RolloverAction { @Override public MetacardImpl doAction(MetacardImpl metacard, File tempFile) throws RolloverActionException { return metacard; } }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testSetMegabyteCountThreshold() { MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(10); condition.setMegabyteCountThreshold(20); assertEquals(20, condition.megabyteCountThreshold); }
@Test public void testGetLatitude3() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("lat3", geoBoxHandler.getLatitude3()); }
@Test public void testGetNitfBinaryContent() throws IOException, MimeTypeParseException, NitfFormatException { BufferedImage chip = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); NitfSegmentsFlow nitfSegmentsFlow = new NitfSegmentsFlow(); int sourceX = 0; int sourceY = 0; Semaphore lock = new Semaphore(1); CatalogOutputAdapter catalogOutputAdapter = new CatalogOutputAdapter(lock); BinaryContent binaryContent = catalogOutputAdapter.getNitfBinaryContent(chip, nitfSegmentsFlow, sourceX, sourceY); assertNotNull(binaryContent); }
@Test public void testPolygon() { GeometryCollectionBuilder builder = new GeometryCollectionBuilder(); builder.polygon(0, 0, 0, 1, 1, 1, 1, 0); String expected = "POLYGON ((0.0 0.0, 0.0 1.0, 1.0 1.0, 1.0 0.0))"; assertEquals(expected, builder.toString()); }
@Test public void testProcess() { SecurityAttributes securityAttributes = new SecurityAttributes(); SystemHighAttributes systemHighAttributes = new SystemHighAttributes(); Map<String, String> initialValues = new HashMap<>(); DefaultSecurityAttributeValuesPlugin plugin = new DefaultSecurityAttributeValuesPlugin(securityAttributes, systemHighAttributes, initialValues); Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl("attribute1", "value1")); List<Metacard> metacards = new ArrayList<>(); metacards.add(metacard); CreateRequest createRequest = new CreateRequestImpl(metacards, null, null); CreateRequest processedRequest = plugin.process(createRequest); List<Metacard> updatedMetacards = processedRequest.getMetacards(); assertEquals(1, updatedMetacards.size()); Metacard updatedMetacard = updatedMetacards.get(0); assertNotNull(updatedMetacard.getAttribute("attribute1")); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getAccessControl())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getClassification())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getOwnerProducer())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getCodeWords())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getDisseminationControls())); }
@Test public void testGenerate() throws IOException { TempFileGeneratorImpl tempFileGenerator = new TempFileGeneratorImpl(); File file = tempFileGenerator.generate(); assertNotNull(file); assertTrue(file.exists()); assertTrue(file.getName().startsWith(TempFileGenerator.TEMP_FILE_PREFIX)); assertTrue(file.getName().endsWith(TempFileGenerator.TEMP_FILE_SUFFIX)); assertTrue(file.delete()); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testSupports() { VideographerRealm videographerRealm = new VideographerRealm(); VideographerAuthenticationToken token = new VideographerAuthenticationToken("username", "password"); boolean result = videographerRealm.supports(token); assertTrue(result); }
@Test public void testGetAttributeName() { LoggingKlvHandler handler = new LoggingKlvHandler(); assertNull(handler.getAttributeName()); }
@Test public void testSetOutputStreamFactory() { PacketBuffer packetBuffer = new PacketBuffer(); OutputStreamFactory outputStreamFactory = new OutputStreamFactory(); packetBuffer.setOutputStreamFactory(outputStreamFactory); assertNotNull(packetBuffer.outputStreamFactory); }
@Test public void testGetImage() throws IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); when(resource.getInputStream()).thenReturn(inputStream); when(resourceResponse.getResource()).thenReturn(resource); BufferedImage expectedImage = ImageIO.read(inputStream); BufferedImage actualImage = adapter.getImage(resourceResponse); assertEquals(expectedImage, actualImage); }
@Test public void asAttribute_returnsOptionalEmpty_whenMinimumListSizeIsZero() { LatitudeLongitudeHandler handler = new LatitudeLongitudeHandler("attributeName", "latitudeFieldName", "longitudeFieldName"); handler.setMap(new HashMap<>()); Optional<Attribute> attribute = handler.asAttribute(); assertTrue(attribute.isEmpty()); }
@Test public void testApply() throws IOException, CatalogTransformerException { MetacardTransformer transformer = mock(MetacardTransformer.class); OverviewSupplier supplier = new OverviewSupplier(transformer); Metacard metacard = mock(Metacard.class); Map<String, Serializable> arguments = new HashMap<>(); BinaryContent content = mock(BinaryContent.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{}); BufferedImage image = mock(BufferedImage.class); when(transformer.transform(metacard, arguments)).thenReturn(content); when(content.getInputStream()).thenReturn(inputStream); when(ImageIO.read(inputStream)).thenReturn(image); Optional<BufferedImage> result = supplier.apply(metacard, arguments); assertTrue(result.isPresent()); assertEquals(image, result.get()); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testGetBinaryContent() throws IOException, MimeTypeParseException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BinaryContent binaryContent = adapter.getBinaryContent(image); assertNotNull(binaryContent); }
@Test public void testAsAttribute() { ListOfDatesHandler handler = new ListOfDatesHandler("testAttribute"); handler.accept(new byte[]{0x01, 0x02, 0x03, 0x04}); Optional<Attribute> attribute = handler.asAttribute(); assertTrue(attribute.isPresent()); assertEquals("testAttribute", attribute.get().getName()); assertEquals(DateListAttribute.class, attribute.get().getClass()); }
@Test public void testApply() { GeometryReducer geometryReducer = new GeometryReducer(); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(1.0, 2.0)); Context context = new Context(); Geometry result = geometryReducer.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] coordinates = new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2) }; Geometry geometry = factory.createLineString(coordinates); Context context = new Context(); SimplifyGeometryFunction simplifyGeometryFunction = new SimplifyGeometryFunction(); Geometry result = simplifyGeometryFunction.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testSupports() { VideographerRealm videographerRealm = new VideographerRealm(); VideographerAuthenticationToken token = new VideographerAuthenticationToken("username", "password"); boolean result = videographerRealm.supports(token); assertTrue(result); }
@Test public void testGetNitfSegmentsFlow() throws NitfFormatException, IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); when(resourceResponse.getResource()).thenReturn(resource); when(resource.getInputStream()).thenReturn(inputStream); NitfSegmentsFlow nitfSegmentsFlow = adapter.getNitfSegmentsFlow(resourceResponse); assertNotNull(nitfSegmentsFlow); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 0)); }
@Test public void testGetLongitudeFieldName() { String attributeName = "attributeName"; String latitudeFieldName = "latitudeFieldName"; String longitudeFieldName = "longitudeFieldName"; LatitudeLongitudeHandler handler = new LatitudeLongitudeHandler(attributeName, latitudeFieldName, longitudeFieldName); String result = handler.getLongitudeFieldName(); assertEquals(longitudeFieldName, result); }
@Test public void testToLonLat() { List<Vector> pixels = new ArrayList<>(); pixels.add(new Vector(10, 20)); pixels.add(new Vector(30, 40)); pixels.add(new Vector(50, 60)); List<Vector> expected = new ArrayList<>(); expected.add(new Vector(0.5, 1.0)); expected.add(new Vector(1.5, 2.0)); expected.add(new Vector(2.5, 3.0)); CoordinateConverter converter = new CoordinateConverter(new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB), Arrays.asList(new Vector(0, 0), new Vector(1, 1))); List<Vector> result = converter.toLonLat(pixels); assertEquals(expected, result); }
@Test public void testSetMonitoredAddress() throws Exception { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); String monitoredAddress = "udp: udpStreamMonitor.setMonitoredAddress(monitoredAddress); assertEquals(new URI(monitoredAddress), udpStreamMonitor.getStreamUri()); }
@Test public void testSendEmail() throws IOException { String fromEmail = "test@example.com"; String toEmail = "recipient@example.com"; String subject = "Test Email"; String body = "This is a test email."; List<Pair<String, InputStream>> attachments = new ArrayList<>(); Pair<String, InputStream> attachment = new Pair<>("test.txt", new ByteArrayInputStream("test".getBytes())); attachments.add(attachment); EmailSenderImpl emailSender = new EmailSenderImpl(); emailSender.setMailHost("smtp.example.com"); emailSender.sendEmail(fromEmail, toEmail, subject, body, attachments); }
@Test public void testToString() { MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(10); String expected = "MegabyteCountRolloverCondition{megabyteCountThreshold=10}"; assertEquals(expected, condition.toString()); }
@Test public void testPostProcess() { Map<String, KlvDataElement> dataElements = new HashMap<>(); Map<String, KlvHandler> handlers = new HashMap<>(); handlers.put("cornerLatitude", new KlvHandler()); handlers.put("cornerLongitude", new KlvHandler()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LATITUDE_1, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LONGITUDE_1, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_1, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_1, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LATITUDE_2, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LONGITUDE_2, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_2, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_2, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LATITUDE_3, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LONGITUDE_3, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_3, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_3, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LATITUDE_4, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.CORNER_LONGITUDE_4, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_4, new KlvDataElement()); dataElements.put(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_4, new KlvDataElement()); OffsetCenterPostProcessor offsetCenterPostProcessor = new OffsetCenterPostProcessor(); offsetCenterPostProcessor.postProcess(dataElements, handlers); }
@Test public void testApply() { List<GeometryOperator> operatorList = new ArrayList<>(); operatorList.add((g, c) -> g.buffer(10)); operatorList.add((g, c) -> g.convexHull()); GeometryOperatorList operator = new GeometryOperatorList(operatorList); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(0, 0)); Context context = new Context(); Geometry result = operator.apply(geometry, context); assertNotNull(result); }
@Test public void testAttributeToLineString() { Attribute attribute = new Attribute(); attribute.setValue("POINT(1 1),POINT(2 2),POINT(3 3)"); GeometryOperator geometryOperator = new GeometryOperator() { @Override public Geometry apply(Geometry geometry, Context context) { return geometry; } }; GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); String result = GeometryUtility.attributeToLineString(attribute, geometryOperator, geometryOperatorContext); assertEquals("LINESTRING (1 1, 2 2, 3 3)", result); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> metacards = new HashSet<>(); Metacard metacard = mock(Metacard.class); metacards.add(metacard); Dictionary<String, Object> properties = new Hashtable<>(); Semaphore lock = mock(Semaphore.class); when(createResponse.getCreatedMetacards()).thenReturn(metacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(properties); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(lock); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testStreamEnded() { Context context = mock(Context.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Factory factory = mock(Factory.class); Metacard parentMetacard = mock(Metacard.class); AtomicBoolean isParentDirty = new AtomicBoolean(true); when(context.modifyParentOrChild(any(Function.class))).thenReturn(null); when(context.getParentMetacard()).thenReturn(Optional.of(parentMetacard)); FindChildrenStreamEndPlugin plugin = new FindChildrenStreamEndPlugin(filterBuilder, factory); plugin.streamEnded(context); verify(context, times(1)).modifyParentOrChild(any(Function.class)); verify(context, times(1)).getParentMetacard(); verify(parentMetacard, times(1)).handleParentMetacard(context, parentMetacard); assertFalse(isParentDirty.get()); }
@Test public void testFipsToStandardCountryCode() throws NitfAttributeTransformException { NitfAttributeConverters converters = new NitfAttributeConverters(new CountryCodeConverter()); String fipsCode = "US"; String expected = "USA"; String result = converters.fipsToStandardCountryCode(fipsCode); assertEquals(expected, result); }
@Test public void testSupports() { VideographerRealm videographerRealm = new VideographerRealm(); VideographerAuthenticationToken token = new VideographerAuthenticationToken("username", "password"); boolean result = videographerRealm.supports(token); assertTrue(result); }
@Test public void testSetSecurityClassificationDefault() { String classification = "SECRET"; List<MetacardType> metacardTypes = new ArrayList<>(); Stanag4609Processor stanag4609Processor = mock(Stanag4609Processor.class); KlvHandlerFactory klvHandlerFactory = mock(KlvHandlerFactory.class); KlvHandler defaultKlvHandler = mock(KlvHandler.class); StanagParserFactory stanagParserFactory = mock(StanagParserFactory.class); KlvProcessor klvProcessor = mock(KlvProcessor.class); Double distanceTolerance = 0.5; InputTransformer inputTransformer = mock(InputTransformer.class); MpegTsInputTransformer mpegTsInputTransformer = new MpegTsInputTransformer(inputTransformer, metacardTypes, stanag4609Processor, klvHandlerFactory, defaultKlvHandler, stanagParserFactory, klvProcessor, distanceTolerance); mpegTsInputTransformer.setSecurityClassificationDefault(classification); verify(klvProcessor, times(1)).accept(any(BaseKlvProcessorVisitor.class)); }
@Test public void testToString() { RolloverCondition firstCondition = mock(RolloverCondition.class); RolloverCondition secondCondition = mock(RolloverCondition.class); BooleanOrRolloverCondition condition = new BooleanOrRolloverCondition(firstCondition, secondCondition); String expected = "BooleanOrRolloverCondition{firstCondition=" + firstCondition.toString() + ", secondCondition=" + secondCondition.toString() + "}"; assertEquals(expected, condition.toString()); }
@Test public void testApply() { GeometryReducer geometryReducer = new GeometryReducer(); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(1.0, 2.0)); Context context = new Context(); Geometry result = geometryReducer.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testGetIpAddress() { VideographerPrincipal videographerPrincipal = new VideographerPrincipal("192.168.0.1"); VideographerAuthenticationToken token = new VideographerAuthenticationToken(videographerPrincipal, new SecurityLogger()); assertEquals("192.168.0.1", token.getIpAddress()); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testSetElapsedTimeRolloverCondition() { Long milliseconds = 1000L; UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setElapsedTimeRolloverCondition(milliseconds); assertEquals(milliseconds, udpStreamMonitor.elapsedTimeRolloverCondition); }
@Test public void testAccept() { SetDatesKlvProcessor processor = new SetDatesKlvProcessor(); Visitor visitor = mock(Visitor.class); processor.accept(visitor); verify(visitor, times(1)).visit(processor); }
@Test public void testGetLatitude1() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("lat1", geoBoxHandler.getLatitude1()); }
@Test public void testGetImage() throws IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); when(resource.getInputStream()).thenReturn(inputStream); when(resourceResponse.getResource()).thenReturn(resource); BufferedImage expectedImage = ImageIO.read(inputStream); BufferedImage actualImage = adapter.getImage(resourceResponse); assertEquals(expectedImage, actualImage); }
@Test public void testPostProcess() { Map<String, KlvDataElement> dataElements = new HashMap<>(); Map<String, KlvHandler> handlers = new HashMap<>(); handlers.put("handler1", new TrimmableHandler()); handlers.put("handler2", new NonTrimmableHandler()); handlers.put("handler3", new TrimmableHandler()); TrimmingPostProcessor trimmingPostProcessor = new TrimmingPostProcessor(); trimmingPostProcessor.postProcess(dataElements, handlers); TrimmableHandler handler1 = (TrimmableHandler) handlers.get("handler1"); TrimmableHandler handler3 = (TrimmableHandler) handlers.get("handler3"); assertTrue(handler1.trimCalled); assertFalse(handler3.trimCalled); } class TrimmableHandler implements KlvHandler, Trimmable { boolean trimCalled = false; @Override public void handle(KlvDataElement klvDataElement) {} @Override public void trim() { trimCalled = true; } } class NonTrimmableHandler implements KlvHandler { @Override public void handle(KlvDataElement klvDataElement) {} }
@Test public void testDoAction() throws Exception { FilenameGenerator filenameGenerator = mock(FilenameGenerator.class); String filenameTemplate = "template"; CatalogFramework catalogFramework = mock(CatalogFramework.class); Context context = mock(Context.class); MetacardUpdater parentMetacardUpdater = mock(MetacardUpdater.class); UuidGenerator uuidGenerator = mock(UuidGenerator.class); SubjectOperations subjectOperations = mock(SubjectOperations.class); CatalogRolloverAction catalogRolloverAction = new CatalogRolloverAction(filenameGenerator, filenameTemplate, catalogFramework, context, parentMetacardUpdater, uuidGenerator, subjectOperations); MetacardImpl metacard = new MetacardImpl(); File tempFile = new File("tempFile"); when(context.modifyParentOrChild(any())).thenReturn(metacard); when(context.getUdpStreamProcessor().getSubject()).thenReturn(mock(Subject.class)); when(filenameGenerator.generateFilename()).thenReturn("filename"); when(catalogFramework.create(any(CreateRequest.class))).thenReturn(mock(CreateResponse.class)); catalogRolloverAction.doAction(metacard, tempFile); verify(context, times(1)).modifyParentOrChild(any()); verify(context.getUdpStreamProcessor(), times(1)).getSubject(); verify(filenameGenerator, times(1)).generateFilename(); verify(catalogFramework, times(1)).create(any(CreateRequest.class)); }
@Test public void testProcess() { CopyPresentKlvProcessor processor = new CopyPresentKlvProcessor(); Map<String, KlvHandler> handlers = new HashMap<>(); handlers.put("handler1", new KlvHandler()); handlers.put("handler2", new KlvHandler()); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); processor.process(handlers, metacard, configuration); for (KlvHandler handler : handlers.values()) { handler.asAttribute().ifPresent(attribute -> { assertThat(metacard.getAttribute(attribute.getName())).isEqualTo(attribute); }); } }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", result.get()); }
@Test public void testTransform() throws IOException, CatalogTransformerException { InputTransformer inputTransformer = mock(InputTransformer.class); List<MetacardType> metacardTypes = new ArrayList<>(); Stanag4609Processor stanag4609Processor = mock(Stanag4609Processor.class); KlvHandlerFactory klvHandlerFactory = mock(KlvHandlerFactory.class); KlvHandler defaultKlvHandler = mock(KlvHandler.class); StanagParserFactory stanagParserFactory = mock(StanagParserFactory.class); KlvProcessor klvProcessor = mock(KlvProcessor.class); Double distanceTolerance = 0.5; MpegTsInputTransformer mpegTsInputTransformer = new MpegTsInputTransformer(inputTransformer, metacardTypes, stanag4609Processor, klvHandlerFactory, defaultKlvHandler, stanagParserFactory, klvProcessor, distanceTolerance); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); Metacard metacard = mock(Metacard.class); when(inputTransformer.transform(inputStream)).thenReturn(metacard); Metacard result = mpegTsInputTransformer.transform(inputStream); assertEquals(metacard, result); }
@Test public void testIndexedPiaprdAttribute() { TreGroup treGroup = new TreGroup(); treGroup.add(new Tre("tre1", "value1")); treGroup.add(new Tre("tre2", "value2")); IndexedPiaprdAttribute indexedPiaprdAttribute = new IndexedPiaprdAttribute("longName", "shortName", treGroup -> treGroup.getTres().get(0).getValue(), AttributeType.STRING); assertEquals("value1", indexedPiaprdAttribute.getAccessorFunction().apply(treGroup)); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testTrim() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "10.0", "20.0", "30.0", "40.0", "50.0", "60.0", "70.0", "80.0"); geoBoxHandler.addValue("fieldName1", "value1"); geoBoxHandler.addValue("fieldName2", "value2"); geoBoxHandler.addValue("fieldName3", "value3"); geoBoxHandler.addValue("fieldName4", "value4"); geoBoxHandler.addValue("fieldName5", "value5"); geoBoxHandler.trim(); assertEquals(3, geoBoxHandler.getValues().size()); }
@Test public void testBuild() { Factory mockFactory = mock(Factory.class); UpdateParentFactory updateParentFactory = new UpdateParentFactory(mockFactory); FindChildrenStreamEndPlugin.Handler handler = updateParentFactory.build(); assertNotNull(handler); assertTrue(handler instanceof UpdateParent); }
@Test public void testSetStartImmediately() { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); udpStreamMonitor.setStartImmediately(true); assertTrue(udpStreamMonitor.startImmediately); }
@Test public void testGetLatitude4() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("lat4", geoBoxHandler.getLatitude4()); }
@Test public void testInit() { AllianceBrandingPlugin plugin = new AllianceBrandingPlugin("test.properties"); plugin.init(); assertEquals("Alliance", plugin.productName); assertEquals("http: assertEquals("alliance_logo.png", plugin.productImage); assertEquals("Codice Foundation", plugin.vendorName); assertEquals("http: assertEquals("alliance_logo.png", plugin.vendorImage); assertEquals("/alliance/favicon.ico", plugin.favIcon); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); List<KlvProcessor> klvProcessorList = new ArrayList<>(); KlvProcessor klvProcessor1 = mock(KlvProcessor.class); KlvProcessor klvProcessor2 = mock(KlvProcessor.class); klvProcessorList.add(klvProcessor1); klvProcessorList.add(klvProcessor2); ListKlvProcessor listKlvProcessor = new ListKlvProcessor(klvProcessorList); listKlvProcessor.process(handlers, metacard, configuration); verify(klvProcessor1).process(handlers, metacard, configuration); verify(klvProcessor2).process(handlers, metacard, configuration); }
@Test public void testOverviewPredicate() { Metacard metacard = new MetacardImpl(); Attribute derivedResourceUris = new AttributeImpl(Core.DERIVED_RESOURCE_URI, Arrays.asList("http: metacard.setAttribute(derivedResourceUris); OverviewPredicate overviewPredicate = new OverviewPredicate(); assertTrue(overviewPredicate.test(metacard)); }
@Test public void testHandle() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new KlvHandler(); Map<Integer, List<DecodedKLVMetadataPacket>> stanagMetadata = new HashMap<>(); List<DecodedKLVMetadataPacket> metadataList = new ArrayList<>(); DecodedKLVMetadataPacket metadataPacket = new DecodedKLVMetadataPacket(); metadataPacket.setDecodedKLV(new byte[]{0x01, 0x02, 0x03}); metadataList.add(metadataPacket); stanagMetadata.put(1, metadataList); PostProcessor postProcessor = new PostProcessor(); Stanag4609ProcessorImpl processor = new Stanag4609ProcessorImpl(postProcessor); processor.handle(handlers, defaultHandler, stanagMetadata); }
@Test public void testAccept() { FrameCenterKlvProcessor processor = new FrameCenterKlvProcessor(); Visitor visitor = mock(Visitor.class); processor.accept(visitor); verify(visitor, times(1)).visit(processor); }
@Test public void testStreamEnded() { Context context = mock(Context.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Factory factory = mock(Factory.class); Metacard parentMetacard = mock(Metacard.class); AtomicBoolean isParentDirty = new AtomicBoolean(true); when(context.modifyParentOrChild(any(Function.class))).thenReturn(null); when(context.getParentMetacard()).thenReturn(Optional.of(parentMetacard)); FindChildrenStreamEndPlugin plugin = new FindChildrenStreamEndPlugin(filterBuilder, factory); plugin.streamEnded(context); verify(context, times(1)).modifyParentOrChild(any(Function.class)); verify(context, times(1)).getParentMetacard(); verify(parentMetacard, times(1)).handleParentMetacard(context, parentMetacard); assertFalse(isParentDirty.get()); }
@Test public void testOverviewPredicate() { Metacard metacard = new MetacardImpl(); Attribute derivedResourceUris = new AttributeImpl(Core.DERIVED_RESOURCE_URI, Arrays.asList("http: metacard.setAttribute(derivedResourceUris); OverviewPredicate overviewPredicate = new OverviewPredicate(); assertTrue(overviewPredicate.test(metacard)); }
@Test public void testApply() { GeometryReducer geometryReducer = new GeometryReducer(); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(1.0, 2.0)); Context context = new Context(); Geometry result = geometryReducer.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testFrameComplete() { PacketBuffer packetBuffer = new PacketBuffer(); DecodedStreamDataHandler handler = new DecodedStreamDataHandler(packetBuffer); handler.frameComplete(true); assertEquals(PacketBuffer.FrameType.IDR, packetBuffer.getCurrentFrameType()); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> createdMetacards = new HashSet<>(); createdMetacards.add(mock(Metacard.class)); when(createResponse.getCreatedMetacards()).thenReturn(createdMetacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(new HashMap<>()); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testGetRawGeoData() { LatitudeLongitudeHandler handler = new LatitudeLongitudeHandler("attributeName", "latitudeFieldName", "longitudeFieldName"); Map<String, List<Double>> expected = new HashMap<>(); List<Double> latLongList = new ArrayList<>(); latLongList.add(37.7749); latLongList.add(-122.4194); expected.put("San Francisco", latLongList); handler.process("San Francisco", latLongList); Map<String, List<Double>> actual = handler.getRawGeoData(); assertEquals(expected, actual); }
@Test public void testGetImage() throws IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); when(resource.getInputStream()).thenReturn(inputStream); when(resourceResponse.getResource()).thenReturn(resource); BufferedImage expectedImage = ImageIO.read(inputStream); BufferedImage actualImage = adapter.getImage(resourceResponse); assertEquals(expectedImage, actualImage); }
@Test public void testGetNitfSegmentsFlow() throws NitfFormatException, IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); when(resourceResponse.getResource()).thenReturn(resource); when(resource.getInputStream()).thenReturn(inputStream); NitfSegmentsFlow nitfSegmentsFlow = adapter.getNitfSegmentsFlow(resourceResponse); assertNotNull(nitfSegmentsFlow); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.write(new byte[1024 * 1024]); MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(2); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); packetBuffer.write(new byte[1024 * 1024]); result = condition.isRolloverReady(packetBuffer); assertTrue(result); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 0); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 10); processor.process(handlers, metacard, configuration); assertNotNull(metacard.getLocation()); PointImpl location = new PointImpl(1.0, 2.0); metacard.setLocation(location); processor.process(handlers, metacard, configuration); assertEquals(location, metacard.getLocation()); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testPolygon() { GeometryCollectionBuilder builder = new GeometryCollectionBuilder(); builder.polygon(0, 0, 0, 1, 1, 1, 1, 0); String expected = "POLYGON ((0.0 0.0, 0.0 1.0, 1.0 1.0, 1.0 0.0))"; assertEquals(expected, builder.toString()); }
@Test public void testChannel() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); when(nitfSegmentsFlow.fileHeader(any())).thenReturn(true); when(nitfSegmentsFlow.forEachImageSegment(any())).thenReturn(true); RoutingSlip routingSlip = new RoutingSlip(); String result = routingSlip.channel(nitfSegmentsFlow); assertEquals("GMTI_ROUTE", result); }
@Test public void testToString() { List<FilenameGenerator> filenameGeneratorList = new ArrayList<>(); filenameGeneratorList.add(new FilenameGenerator("file1")); filenameGeneratorList.add(new FilenameGenerator("file2")); ListFilenameGenerator listFilenameGenerator = new ListFilenameGenerator(filenameGeneratorList); String expected = "ListFilenameGenerator{filenameGeneratorList=" + filenameGeneratorList + "}"; assertEquals(expected, listFilenameGenerator.toString()); }
@Test public void testAccept() { Visitor visitor = mock(Visitor.class); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.accept(visitor); verify(visitor).visit(processor); }
@Test public void testDoAction() throws RolloverActionException { MetacardImpl metacard = new MetacardImpl(); File tempFile = new File("tempFile"); CreateMetacardRolloverAction action = new CreateMetacardRolloverAction(Collections.singletonList(new MetacardTypeImpl())); MetacardImpl newMetacard = action.doAction(metacard, tempFile); assertEquals(Constants.MPEGTS_MIME_TYPE, newMetacard.getContentTypeName()); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", result.get()); }
@Test public void testCreateMetacard() { String id = "123"; MetacardFactory factory = new MetacardFactory(); Metacard metacard = factory.createMetacard(id); assertNotNull(metacard); assertEquals(id, metacard.getAttribute(Core.ID).getValue()); assertEquals(Media.TYPE, metacard.getAttribute(Media.TYPE).getName()); assertEquals(MIME_TYPE.toString(), metacard.getAttribute(Media.TYPE).getValue()); assertEquals(Metacard.CONTENT_TYPE, metacard.getAttribute(Metacard.CONTENT_TYPE).getName()); assertEquals(MIME_TYPE.toString(), metacard.getAttribute(Metacard.CONTENT_TYPE).getValue()); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 0)); assertEquals(Color.WHITE.getRGB(), croppedImage.getRGB(30, 30)); assertThrows(ChipOutOfBoundsException.class, () -> chipService.crop(inputImage, -1, 0, 50, 50)); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testToString() { IllegalCharactersFilenameGenerator generator = new IllegalCharactersFilenameGenerator(); String expected = "IllegalCharactersFilenameGenerator{}"; String actual = generator.toString(); assertEquals(expected, actual); }
@Test public void testParse() throws Exception { ByteSource byteSource = new ByteSource(); Stanag4609TransportStreamParser parser = new Stanag4609TransportStreamParser(byteSource); parser.parse((klvStreamPid, decodedKLVMetadataPacket) -> { assertNotNull(klvStreamPid); assertNotNull(decodedKLVMetadataPacket); }); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 0)); }
@Test public void testSendEmail() throws IOException { String fromEmail = "test@example.com"; String toEmail = "recipient@example.com"; String subject = "Test Email"; String body = "This is a test email."; List<Pair<String, InputStream>> attachments = new ArrayList<>(); Pair<String, InputStream> attachment = new Pair<>("test.txt", new ByteArrayInputStream("test".getBytes())); attachments.add(attachment); EmailSenderImpl emailSender = new EmailSenderImpl(); emailSender.setMailHost("smtp.example.com"); emailSender.sendEmail(fromEmail, toEmail, subject, body, attachments); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testConvertSubpolygonsToEnvelopes() { GeometryFactory geometryFactory = new GeometryFactory(); Geometry polygon1 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(1, 0), new Coordinate(0, 0)}); Geometry polygon2 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(2, 2), new Coordinate(2, 3), new Coordinate(3, 3), new Coordinate(3, 2), new Coordinate(2, 2)}); Geometry[] polygons = new Geometry[] {polygon1, polygon2}; GeometryCollection geometryCollection = geometryFactory.createGeometryCollection(polygons); ConvertSubpolygonsToEnvelopes operator = new ConvertSubpolygonsToEnvelopes(); Geometry result = operator.apply(geometryCollection, null); assertTrue(result instanceof Polygon); }
@Test public void testSetMegabyteCountRolloverCondition() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); Integer count = 10; udpStreamMonitor.setMegabyteCountRolloverCondition(count); assertEquals(count, udpStreamMonitor.byteCountRolloverCondition); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testSetMonitoredAddress() throws Exception { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); String monitoredAddress = "udp: udpStreamMonitor.setMonitoredAddress(monitoredAddress); assertEquals(new URI(monitoredAddress), udpStreamMonitor.getStreamUri()); }
@Test public void testFrameComplete() { PacketBuffer packetBuffer = new PacketBuffer(); DecodedStreamDataHandler handler = new DecodedStreamDataHandler(packetBuffer); handler.frameComplete(true); assertEquals(PacketBuffer.FrameType.IDR, packetBuffer.getCurrentFrameType()); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 0); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 10); processor.process(handlers, metacard, configuration); assertNotNull(metacard.getLocation()); PointImpl location = new PointImpl(1.0, 2.0); metacard.setLocation(location); processor.process(handlers, metacard, configuration); assertEquals(location, metacard.getLocation()); }
@Test public void testDoGetAuthenticationInfo() { VideographerRealm videographerRealm = new VideographerRealm(); BaseAuthenticationToken baseAuthenticationToken = new BaseAuthenticationToken("username", "password", "127.0.0.1"); AuthenticationInfo authenticationInfo = videographerRealm.doGetAuthenticationInfo(baseAuthenticationToken); assertNotNull(authenticationInfo); assertEquals(baseAuthenticationToken.getCredentials(), authenticationInfo.getCredentials()); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.setAge(1000); ElapsedTimeRolloverCondition condition = new ElapsedTimeRolloverCondition(500); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] input = new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3)}; LineString lineString = factory.createLineString(input); Context context = new Context(); context.setSubsampleCount(2); GeometryOperator subsampler = new LinestringGeometrySubsampler(); Geometry result = subsampler.apply(lineString, context); Coordinate[] expectedOutput = new Coordinate[] {new Coordinate(0, 0), new Coordinate(2, 2)}; LineString expectedLineString = factory.createLineString(expectedOutput); assertEquals(expectedLineString, result); }
@Test public void testSetSecurityClassificationCode5() { MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer(null, null, null, null, null, null, null, 0.0); inputTransformer.setSecurityClassificationCode5("SECRET"); }
@Test public void testSetMonitoredAddress() throws Exception { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); String monitoredAddress = "udp: udpStreamMonitor.setMonitoredAddress(monitoredAddress); assertEquals(new URI(monitoredAddress), udpStreamMonitor.getStreamUri()); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] input = new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3)}; LineString lineString = factory.createLineString(input); Context context = new Context(); context.setSubsampleCount(2); GeometryOperator subsampler = new LinestringGeometrySubsampler(); Geometry result = subsampler.apply(lineString, context); Coordinate[] expectedOutput = new Coordinate[] {new Coordinate(0, 0), new Coordinate(2, 2)}; LineString expectedLineString = factory.createLineString(expectedOutput); assertEquals(expectedLineString, result); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> metacards = new HashSet<>(); Metacard metacard = mock(Metacard.class); metacards.add(metacard); Dictionary<String, Object> properties = new Hashtable<>(); Semaphore lock = mock(Semaphore.class); when(createResponse.getCreatedMetacards()).thenReturn(metacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(properties); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(lock); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testGetNitfSegmentsFlow() throws NitfFormatException, IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); when(resourceResponse.getResource()).thenReturn(resource); when(resource.getInputStream()).thenReturn(inputStream); NitfSegmentsFlow nitfSegmentsFlow = adapter.getNitfSegmentsFlow(resourceResponse); assertNotNull(nitfSegmentsFlow); }
@Test public void testProcess() { SecurityAttributes securityAttributes = new SecurityAttributes(); SystemHighAttributes systemHighAttributes = new SystemHighAttributes(); Map<String, String> initialValues = new HashMap<>(); DefaultSecurityAttributeValuesPlugin plugin = new DefaultSecurityAttributeValuesPlugin(securityAttributes, systemHighAttributes, initialValues); Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl("attribute1", "value1")); List<Metacard> metacards = new ArrayList<>(); metacards.add(metacard); CreateRequest createRequest = new CreateRequestImpl(metacards, null, null); CreateRequest processedRequest = plugin.process(createRequest); List<Metacard> updatedMetacards = processedRequest.getMetacards(); assertEquals(1, updatedMetacards.size()); Metacard updatedMetacard = updatedMetacards.get(0); assertNotNull(updatedMetacard.getAttribute("attribute1")); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getAccessControl())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getCaveats())); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); assertEquals(0b10101010, bitReader.readBits(8)); }
@Test public void testConvertSubpolygonsToEnvelopes() { GeometryFactory geometryFactory = new GeometryFactory(); Geometry polygon1 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(1, 0), new Coordinate(0, 0)}); Geometry polygon2 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(1, 1), new Coordinate(1, 2), new Coordinate(2, 2), new Coordinate(2, 1), new Coordinate(1, 1)}); Geometry[] polygons = new Geometry[] {polygon1, polygon2}; GeometryCollection geometryCollection = geometryFactory.createGeometryCollection(polygons); ConvertSubpolygonsToEnvelopes convertSubpolygonsToEnvelopes = new ConvertSubpolygonsToEnvelopes(); Geometry result = convertSubpolygonsToEnvelopes.apply(geometryCollection, null); assertTrue(result instanceof Polygon); }
@Test public void testSetRolloverCondition() { RolloverCondition rolloverCondition = mock(RolloverCondition.class); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setRolloverCondition(rolloverCondition); verify(udpStreamProcessor, times(1)).setRolloverCondition(rolloverCondition); }
@Test public void testToString() { PacketBuffer packetBuffer = new PacketBuffer(); String expected = "PacketBuffer{bytesWrittenToTempFile=0, incompleteFrameBytes=null}"; String actual = packetBuffer.toString(); assertEquals(expected, actual); }
@Test public void testHandle() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new KlvHandler(); Map<Integer, List<DecodedKLVMetadataPacket>> stanagMetadata = new HashMap<>(); List<DecodedKLVMetadataPacket> metadataList = new ArrayList<>(); DecodedKLVMetadataPacket metadataPacket = new DecodedKLVMetadataPacket(); metadataPacket.setDecodedKLV(new byte[]{0x01, 0x02, 0x03}); metadataList.add(metadataPacket); stanagMetadata.put(1, metadataList); PostProcessor postProcessor = new PostProcessorImpl(); Stanag4609Processor stanagProcessor = new Stanag4609ProcessorImpl(postProcessor); stanagProcessor.handle(handlers, defaultHandler, stanagMetadata); }
@Test public void testFipsToStandardCountryCode() throws NitfAttributeTransformException { NitfAttributeConverters converters = new NitfAttributeConverters(new CountryCodeConverter()); String fipsCode = "US"; String expected = "USA"; String result = converters.fipsToStandardCountryCode(fipsCode); assertEquals(expected, result); }
@Test public void testChannel() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); when(nitfSegmentsFlow.fileHeader(any())).thenReturn(true); when(nitfSegmentsFlow.forEachImageSegment(any())).thenReturn(true); RoutingSlip routingSlip = new RoutingSlip(); String result = routingSlip.channel(nitfSegmentsFlow); assertEquals("GMTI_ROUTE", result); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> metacards = new HashSet<>(); Metacard metacard = mock(Metacard.class); metacards.add(metacard); Dictionary<String, Object> properties = new Hashtable<>(); Semaphore lock = mock(Semaphore.class); when(createResponse.getCreatedMetacards()).thenReturn(metacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(properties); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(lock); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testGetLatitude2() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("lat2", geoBoxHandler.getLatitude2()); }
@Test public void testToString() { List<GeometryOperator> operatorList = new ArrayList<>(); operatorList.add(new GeometryOperatorImpl()); operatorList.add(new GeometryOperatorImpl()); GeometryOperatorList geometryOperatorList = new GeometryOperatorList(operatorList); String expected = "GeometryOperator{operatorList=" + operatorList.toString() + "}"; assertEquals(expected, geometryOperatorList.toString()); }
@Test public void testAttributeToLineString() { Attribute attribute = new Attribute(); attribute.setValue("POINT(1 1),POINT(2 2),POINT(3 3)"); GeometryOperator geometryOperator = new GeometryOperator() { @Override public Geometry apply(Geometry geometry, Context context) { return geometry; } }; GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); String result = GeometryUtility.attributeToLineString(attribute, geometryOperator, geometryOperatorContext); assertEquals("LINESTRING (1 1, 2 2, 3 3)", result); }
@Test public void testGetNitfBinaryContent() throws IOException, MimeTypeParseException, NitfFormatException { BufferedImage chip = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); NitfSegmentsFlow nitfSegmentsFlow = new NitfSegmentsFlow(); int sourceX = 0; int sourceY = 0; Semaphore lock = new Semaphore(1); CatalogOutputAdapter catalogOutputAdapter = new CatalogOutputAdapter(lock); BinaryContent binaryContent = catalogOutputAdapter.getNitfBinaryContent(chip, nitfSegmentsFlow, sourceX, sourceY); assertNotNull(binaryContent); }
@Test public void testChip() throws Exception { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = inputImage.createGraphics(); g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, 100, 100); g2d.setColor(Color.BLACK); g2d.drawLine(10, 10, 90, 90); g2d.dispose(); Polygon inputImagePolygon = new Polygon(new int[]{10, 90, 90, 10}, new int[]{10, 90, 10, 90}, 4); Polygon chipPolygon = new Polygon(new int[]{20, 80, 80, 20}, new int[]{20, 80, 20, 80}, 4); ChipService chipService = new ChipServiceImpl(); BufferedImage result = chipService.chip(inputImage, inputImagePolygon, chipPolygon); assertEquals(60, result.getWidth()); assertEquals(60, result.getHeight()); assertEquals(Color.WHITE.getRGB(), result.getRGB(0, 0)); assertEquals(Color.WHITE.getRGB(), result.getRGB(59, 59)); assertEquals(Color.BLACK.getRGB(), result.getRGB(10, 10)); assertEquals(Color.BLACK.getRGB(), result.getRGB(49, 49)); }
@Test public void testSetSecurityClassificationCode4() { MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer(null, null, null, null, null, null, null, null); inputTransformer.setSecurityClassificationCode4("SECRET"); }
@Test public void testEnd() { UpdateField updateField = new UpdateField(); UpdateParent updateParent = new UpdateParent(updateField); Context context = new Context(); Metacard parentMetacard = new MetacardImpl(); updateParent.end(context, parentMetacard); }
@Test public void testSetMegabyteCountThreshold() { MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(10); condition.setMegabyteCountThreshold(20); assertEquals(20, condition.megabyteCountThreshold); }
@Test public void testTransform() throws IOException, CatalogTransformerException { InputTransformer inputTransformer = mock(InputTransformer.class); List<MetacardType> metacardTypes = new ArrayList<>(); Stanag4609Processor stanag4609Processor = mock(Stanag4609Processor.class); KlvHandlerFactory klvHandlerFactory = mock(KlvHandlerFactory.class); KlvHandler defaultKlvHandler = mock(KlvHandler.class); StanagParserFactory stanagParserFactory = mock(StanagParserFactory.class); KlvProcessor klvProcessor = mock(KlvProcessor.class); Double distanceTolerance = 0.5; MpegTsInputTransformer mpegTsInputTransformer = new MpegTsInputTransformer(inputTransformer, metacardTypes, stanag4609Processor, klvHandlerFactory, defaultKlvHandler, stanagParserFactory, klvProcessor, distanceTolerance); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); Metacard metacard = mock(Metacard.class); when(inputTransformer.transform(inputStream)).thenReturn(metacard); Metacard result = mpegTsInputTransformer.transform(inputStream); assertEquals(metacard, result); }
@Test public void testTransform() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); Metacard metacard = mock(Metacard.class); NitfGmtiTransformer nitfGmtiTransformer = new NitfGmtiTransformer(); when(nitfSegmentsFlow.getNitfHeader()).thenReturn(mock(NitfHeader.class)); when(nitfSegmentsFlow.getImageSegments()).thenReturn(Collections.emptyList()); when(nitfSegmentsFlow.getSymbolSegments()).thenReturn(Collections.emptyList()); when(nitfSegmentsFlow.getGraphicsSegments()).thenReturn(Collections.emptyList()); when(nitfSegmentsFlow.getTextSegments()).thenReturn(Collections.emptyList()); when(nitfSegmentsFlow.getTresSegments()).thenReturn(Collections.emptyList()); nitfGmtiTransformer.transform(nitfSegmentsFlow, metacard); verify(metacard, times(1)).setLocation(any(Location.class)); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 0); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 10); processor.process(handlers, metacard, configuration); assertNotNull(metacard.getLocation()); PointImpl location = new PointImpl(1.0, 2.0); metacard.setLocation(location); processor.process(handlers, metacard, configuration); assertEquals(location, metacard.getLocation()); }
@Test public void testFormatToDMS() { CatalogOutputAdapter adapter = new CatalogOutputAdapter(new Semaphore(1)); String result = adapter.formatToDMS(37.7749, -122.4194); assertEquals("375242N1222517W", result); }
@Test public void testGetLatitudeFieldName() { String attributeName = "attributeName"; String latitudeFieldName = "latitudeFieldName"; String longitudeFieldName = "longitudeFieldName"; LatitudeLongitudeHandler handler = new LatitudeLongitudeHandler(attributeName, latitudeFieldName, longitudeFieldName); String result = handler.getLatitudeFieldName(); assertEquals(latitudeFieldName, result); }
@Test public void testAttributeToLineString() { Attribute attribute = new Attribute(); attribute.setValue("POINT(1 1),POINT(2 2),POINT(3 3)"); GeometryOperator geometryOperator = new GeometryOperator() { @Override public Geometry apply(Geometry geometry, Context context) { return geometry; } }; GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); String result = GeometryUtility.attributeToLineString(attribute, geometryOperator, geometryOperatorContext); assertEquals("LINESTRING (1 1, 2 2, 3 3)", result); }
@Test public void testConvertSubpolygonsToEnvelopes() { GeometryFactory geometryFactory = new GeometryFactory(); Geometry polygon1 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(1, 0), new Coordinate(0, 0)}); Geometry polygon2 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(1, 1), new Coordinate(1, 2), new Coordinate(2, 2), new Coordinate(2, 1), new Coordinate(1, 1)}); Geometry[] polygons = new Geometry[] {polygon1, polygon2}; GeometryCollection geometryCollection = geometryFactory.createGeometryCollection(polygons); ConvertSubpolygonsToEnvelopes operator = new ConvertSubpolygonsToEnvelopes(); Geometry result = operator.apply(geometryCollection, null); assertTrue(result instanceof Polygon); }
@Test public void testSetSecurityClassificationCode3() { MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer(null, null, null, null, null, null, null, 0.0); inputTransformer.setSecurityClassificationCode3("SECRET"); }
@Test public void testGetNalUnits() { List<NALUnit> nalUnits = new ArrayList<>(); nalUnits.add(new NALUnit()); nalUnits.add(new NALUnit()); nalUnits.add(new NALUnit()); Mpeg4DecodedStreamData mpeg4DecodedStreamData = new Mpeg4DecodedStreamData(nalUnits, 1); assertEquals(nalUnits, mpeg4DecodedStreamData.getNalUnits()); }
@Test public void testProcess() { SecurityAttributes securityAttributes = new SecurityAttributes(); SystemHighAttributes systemHighAttributes = new SystemHighAttributes(); Map<String, String> initialValues = new HashMap<>(); DefaultSecurityAttributeValuesPlugin plugin = new DefaultSecurityAttributeValuesPlugin(securityAttributes, systemHighAttributes, initialValues); Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl("attribute1", "value1")); List<Metacard> metacards = new ArrayList<>(); metacards.add(metacard); CreateRequest createRequest = new CreateRequestImpl(metacards, null, null); CreateRequest processedRequest = plugin.process(createRequest); List<Metacard> updatedMetacards = processedRequest.getMetacards(); assertEquals(1, updatedMetacards.size()); Metacard updatedMetacard = updatedMetacards.get(0); assertNotNull(updatedMetacard.getAttribute("attribute1")); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getAccessControl())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getClassification())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getOwnerProducer())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getCodeWords())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getDisseminationControls())); }
@Test public void asAttributeReturnsOptionalEmptyWhenListIsEmpty() { ListOfBasicKlvDataTypesHandler handler = new ListOfBasicKlvDataTypesHandler("attributeName", KlvDataElement.class); Optional<Attribute> attribute = handler.asAttribute(); assertFalse(attribute.isPresent()); }
@Test public void testToString() { MetacardFactory metacardFactory = new MetacardFactory(); String expectedString = String.format(MetacardFactory.TO_STRING_PATTERN, metacardFactory.getClass().getName(), MetacardFactory.ID, MetacardFactory.MIME_TYPE); String actualString = metacardFactory.toString(); assertEquals(expectedString, actualString); }
@Test public void testIsBlankString() { assertTrue(Utilities.isBlankString("")); assertTrue(Utilities.isBlankString(" ")); assertTrue(Utilities.isBlankString(null)); assertFalse(Utilities.isBlankString("not blank")); assertFalse(Utilities.isBlankString(123)); }
@Test public void testConvertSubpolygonsToEnvelopes() { GeometryFactory geometryFactory = new GeometryFactory(); Geometry polygon1 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(1, 0), new Coordinate(0, 0)}); Geometry polygon2 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(1, 1), new Coordinate(1, 2), new Coordinate(2, 2), new Coordinate(2, 1), new Coordinate(1, 1)}); Geometry[] polygons = new Geometry[] {polygon1, polygon2}; GeometryCollection geometryCollection = geometryFactory.createGeometryCollection(polygons); ConvertSubpolygonsToEnvelopes operator = new ConvertSubpolygonsToEnvelopes(); Geometry result = operator.apply(geometryCollection, null); assertTrue(result instanceof Polygon); }
@Test public void testSetMegabyteCountRolloverCondition() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); Integer count = 10; udpStreamMonitor.setMegabyteCountRolloverCondition(count); assertEquals(count, udpStreamMonitor.byteCountRolloverCondition); }
@Test public void testAttributeToLineString() { Attribute attribute = new Attribute(); attribute.setValue("POINT(1 1),POINT(2 2),POINT(3 3)"); GeometryOperator geometryOperator = new GeometryOperator() { @Override public Geometry apply(Geometry geometry, Context context) { return geometry; } }; GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); String result = GeometryUtility.attributeToLineString(attribute, geometryOperator, geometryOperatorContext); assertEquals("LINESTRING (1 1, 2 2, 3 3)", result); }
@Test public void testAccept() { DistinctSingleKlvProcessor processor = new DistinctSingleKlvProcessor("attributeName", "stanagFieldName"); Visitor visitor = mock(Visitor.class); processor.accept(visitor); verify(visitor, times(1)).visit(processor); }
@Test public void testAccept() { RolloverCondition firstCondition = mock(RolloverCondition.class); RolloverCondition secondCondition = mock(RolloverCondition.class); Visitor visitor = mock(Visitor.class); BooleanOrRolloverCondition condition = new BooleanOrRolloverCondition(firstCondition, secondCondition); condition.accept(visitor); verify(firstCondition).accept(visitor); verify(secondCondition).accept(visitor); verify(visitor).visit(condition); }
@Test public void testGetLongitude1() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("long1", geoBoxHandler.getLongitude1()); }
@Test public void testOverviewPredicate() { Metacard metacard = new MetacardImpl(); Attribute derivedResourceUris = new AttributeImpl(Core.DERIVED_RESOURCE_URI, Arrays.asList("http: metacard.setAttribute(derivedResourceUris); OverviewPredicate overviewPredicate = new OverviewPredicate(); assertTrue(overviewPredicate.test(metacard)); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testDoAction() throws Exception { FilenameGenerator filenameGenerator = mock(FilenameGenerator.class); when(filenameGenerator.generateFilename()).thenReturn("testFilename"); String filenameTemplate = "testTemplate"; CatalogFramework catalogFramework = mock(CatalogFramework.class); Context context = mock(Context.class); MetacardUpdater parentMetacardUpdater = mock(MetacardUpdater.class); UuidGenerator uuidGenerator = mock(UuidGenerator.class); SubjectOperations subjectOperations = mock(SubjectOperations.class); CatalogRolloverAction catalogRolloverAction = new CatalogRolloverAction(filenameGenerator, filenameTemplate, catalogFramework, context, parentMetacardUpdater, uuidGenerator, subjectOperations); MetacardImpl metacard = new MetacardImpl(); File tempFile = mock(File.class); when(context.getUdpStreamProcessor().getSubject()).thenReturn(mock(Subject.class)); when(context.modifyParentOrChild(any())).thenReturn(metacard); CreateResponse createResponse = mock(CreateResponse.class); when(createResponse.getCreatedMetacards()).thenReturn(Collections.singletonList(new MetacardImpl())); when(catalogFramework.create(any(CreateStorageRequest.class))).thenReturn(createResponse); catalogRolloverAction.doAction(metacard, tempFile); verify(context, times(1)).modifyParentOrChild(any()); verify(context.getUdpStreamProcessor(), times(1)).getSubject(); verify(catalogFramework, times(1)).create(any(CreateStorageRequest.class)); }
@Test public void testParse() throws Exception { ByteSource byteSource = new ByteSource(); Stanag4609TransportStreamParser parser = new Stanag4609TransportStreamParser(byteSource); parser.parse((klvStreamPid, decodedKLVMetadataPacket) -> { assertNotNull(klvStreamPid); assertNotNull(decodedKLVMetadataPacket); }); }
@Test public void testGetAge() { PacketBuffer packetBuffer = new PacketBuffer(); long age = packetBuffer.getAge(); assertEquals(0, age); }
@Test public void testFipsToStandardCountryCode() throws NitfAttributeTransformException { NitfAttributeConverters converters = new NitfAttributeConverters(new CountryCodeConverter()); String fipsCode = "US"; String expected = "USA"; String result = converters.fipsToStandardCountryCode(fipsCode); assertEquals(expected, result); }
@Test public void testSetMegabyteCountRolloverCondition() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); Integer count = 10; udpStreamMonitor.setMegabyteCountRolloverCondition(count); assertEquals(count, udpStreamMonitor.byteCountRolloverCondition); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", result.get()); }
@Test public void testSetFilenameTemplate() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); String template = "test_template"; udpStreamMonitor.setFilenameTemplate(template); assertEquals(template, udpStreamMonitor.filenameTemplate); }
@Test public void testSetCatalogFramework() { CatalogFramework catalogFramework = mock(CatalogFramework.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); udpStreamMonitor.setCatalogFramework(catalogFramework); verify(udpStreamMonitor.udpStreamProcessor).setCatalogFramework(catalogFramework); }
@Test public void testReadableBits() { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); byteBuf.writeByte(0b01010101); BitReader bitReader = new BitReader(byteBuf); assertEquals(16, bitReader.readableBits()); }
@Test public void testConvertSubpolygonsToEnvelopes() { GeometryFactory geometryFactory = new GeometryFactory(); Geometry polygon1 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(0, 0), new Coordinate(0, 1), new Coordinate(1, 1), new Coordinate(1, 0), new Coordinate(0, 0)}); Geometry polygon2 = geometryFactory.createPolygon(new Coordinate[] {new Coordinate(1, 1), new Coordinate(1, 2), new Coordinate(2, 2), new Coordinate(2, 1), new Coordinate(1, 1)}); Geometry[] polygons = new Geometry[] {polygon1, polygon2}; GeometryCollection geometryCollection = geometryFactory.createGeometryCollection(polygons); ConvertSubpolygonsToEnvelopes converter = new ConvertSubpolygonsToEnvelopes(); Geometry result = converter.apply(geometryCollection, null); assertTrue(result instanceof Polygon); assertEquals(1.0, result.getEnvelopeInternal().getMinX(), 0.0); assertEquals(0.0, result.getEnvelopeInternal().getMinY(), 0.0); assertEquals(2.0, result.getEnvelopeInternal().getMaxX(), 0.0); assertEquals(2.0, result.getEnvelopeInternal().getMaxY(), 0.0); }
@Test public void testAttributeToLineString() { Attribute attribute = new Attribute(); attribute.setValue("POINT(1 1),POINT(2 2),POINT(3 3)"); GeometryOperator geometryOperator = new GeometryOperator() { @Override public Geometry apply(Geometry geometry, Context context) { return geometry; } }; GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); String result = GeometryUtility.attributeToLineString(attribute, geometryOperator, geometryOperatorContext); assertEquals("LINESTRING (1 1, 2 2, 3 3)", result); }
@Test public void testAccept() { Visitor visitor = mock(Visitor.class); CopyPresentKlvProcessor processor = new CopyPresentKlvProcessor(); processor.accept(visitor); verify(visitor, times(1)).visit(processor); }
@Test public void testCreateIchipb() { BufferedImage chip = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); int sourceX = 0; int sourceY = 0; float selectWidth = 5.0f; float selectHeight = 5.0f; CatalogOutputAdapter adapter = new CatalogOutputAdapter(new Semaphore(1)); Tre result = adapter.createIchipb(chip, sourceX, sourceY, selectWidth, selectHeight); assertNotNull(result); assertEquals("00", result.getEntry("XFRM_FLAG").getValue()); assertEquals("0001.00000", result.getEntry("SCALE_FACTOR").getValue()); assertEquals("00", result.getEntry("ANAMRPH_CORR").getValue()); assertEquals("01", result.getEntry("SCANBLK_NUM").getValue()); assertEquals("0.5", result.getEntry("OP_ROW_11").getValue()); assertEquals("0.5", result.getEntry("OP_COL_11").getValue()); assertEquals("0.5", result.getEntry("OP_ROW_12").getValue()); assertEquals("9.5", result.getEntry("OP_COL_12").getValue()); assertEquals("9.5", result.getEntry("OP_ROW_21").getValue()); assertEquals("0.5", result.getEntry("OP_COL_21").getValue()); assertEquals("9.5", result.getEntry("OP_ROW_22").getValue()); assertEquals("9.5", result.getEntry("OP_COL_22").getValue()); assertEquals("0.5", result.getEntry("FI_ROW_11").getValue()); assertEquals("0.5", result.getEntry("FI_COL_11").getValue()); assertEquals("0.5", result.getEntry("FI_ROW_12").getValue()); assertEquals("4.5", result.getEntry("FI_COL_12").getValue()); assertEquals("4.5", result.getEntry("FI_ROW_21").getValue()); assertEquals("0.5", result.getEntry("FI_COL_21").getValue()); assertEquals("4.5", result.getEntry("FI_ROW_22").getValue()); assertEquals("4.5", result.getEntry("FI_COL_22").getValue()); assertEquals("00000000", result.getEntry("FI_ROW").getValue()); assertEquals("00000000", result.getEntry("FI_COL").getValue()); }
@Test public void testSetStreamEndPlugin() { StreamEndPlugin plugin = new StreamEndPluginImpl(); UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(new StreamMonitorImpl(), mock(BundleContext.class)); udpStreamProcessor.setStreamEndPlugin(plugin); assertEquals(plugin, udpStreamProcessor.getStreamEndPlugin()); }
@Test public void testSetFilenameGenerator() { FilenameGenerator filenameGenerator = mock(FilenameGenerator.class); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setFilenameGenerator(filenameGenerator); verify(udpStreamProcessor).setFilenameGenerator(filenameGenerator); }
@Test public void testApply() { GeometryOperator operator = new NonEmptyGeometryOperator(); Geometry geometry = new Geometry(); Context context = new Context(); Geometry result = operator.apply(geometry, context); assertNull(result); geometry = null; result = operator.apply(geometry, context); assertNull(result); geometry = new Geometry(); geometry.addPoint(new Point(0, 0)); result = operator.apply(geometry, context); assertNotNull(result); assertEquals(geometry, result); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testSetRolloverCondition() { RolloverCondition rolloverCondition = mock(RolloverCondition.class); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setRolloverCondition(rolloverCondition); verify(udpStreamProcessor, times(1)).setRolloverCondition(rolloverCondition); }
@Test public void testCallDataElementHandlers() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new DefaultKlvHandler(); KlvDataElement klvDataElement = new KlvDataElement("name", new byte[]{0x01, 0x02, 0x03}); Map<String, KlvDataElement> dataElements = new HashMap<>(); Stanag4609ProcessorImpl processor = new Stanag4609ProcessorImpl(new PostProcessor()); processor.callDataElementHandlers(handlers, defaultHandler, klvDataElement, dataElements); assertEquals(klvDataElement, dataElements.get("name")); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))", result.get()); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testDecode() { MTSParser mtsParser = new MTSParser(); PacketBuffer packetBuffer = new PacketBuffer(); UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); RawUdpDataToMTSPacketDecoder decoder = new RawUdpDataToMTSPacketDecoder(packetBuffer, udpStreamProcessor); decoder.setMtsParser(mtsParser); DatagramPacket datagramPacket = new DatagramPacket(new byte[]{1, 2, 3, 4}, 4); List<Object> out = new ArrayList<>(); decoder.decode(null, datagramPacket, out); assertEquals(1, out.size()); assertTrue(out.get(0) instanceof MTSMessage); }
@Test public void testTransform() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); Metacard metacard = mock(Metacard.class); NitfGmtiTransformer nitfGmtiTransformer = new NitfGmtiTransformer(); when(nitfSegmentsFlow.getSegment(anyString())).thenReturn(mock(Segment.class)); nitfGmtiTransformer.transform(nitfSegmentsFlow, metacard); verify(nitfSegmentsFlow, times(2)).getSegment(anyString()); verify(metacard, times(1)).setAttribute(eq(Core.LOCATION), anyString()); verify(metacard, times(1)).setAttribute(eq(Core.LOCATION), any(Geometry.class)); }
@Test public void testToString() { DateTemplateFilenameGenerator generator = new DateTemplateFilenameGenerator(); String expected = "DateTemplateFilenameGenerator{}"; String result = generator.toString(); assertEquals(expected, result); }
@Test public void testTestBit() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertTrue(bitReader.testBit()); assertFalse(bitReader.testBit()); assertTrue(bitReader.testBit()); assertFalse(bitReader.testBit()); assertTrue(bitReader.testBit()); assertFalse(bitReader.testBit()); assertTrue(bitReader.testBit()); assertFalse(bitReader.testBit()); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.WHITE.getRGB(), croppedImage.getRGB(59, 0)); assertEquals(Color.WHITE.getRGB(), croppedImage.getRGB(0, 59)); }
@Test public void testGetAttributes() { List<NitfAttribute<ImageSegment>> attributes = ImageAttribute.getAttributes(); assertNotNull(attributes); assertEquals(3, attributes.size()); assertEquals("Image Compression", attributes.get(0).getLongName()); assertEquals("IC", attributes.get(0).getShortName()); assertEquals(AttributeType.STRING, attributes.get(0).getAttributeType()); assertEquals("Image Category", attributes.get(1).getLongName()); assertEquals("CAT", attributes.get(1).getShortName()); assertEquals(AttributeType.STRING, attributes.get(1).getAttributeType()); assertEquals("Image Date and Time", attributes.get(2).getLongName()); assertEquals("IDATIM", attributes.get(2).getShortName()); assertEquals(AttributeType.DATE_TIME, attributes.get(2).getAttributeType()); }
@Test public void testTransform() { NitfSegmentsFlow nitfSegmentsFlow = new NitfSegmentsFlow(); Metacard metacard = new MetacardImpl(); NitfHeaderTransformer nitfHeaderTransformer = new NitfHeaderTransformer(); nitfSegmentsFlow.addFileHeader(new FileHeader()); nitfHeaderTransformer.transform(nitfSegmentsFlow, metacard); assertNotNull(nitfSegmentsFlow.getFileHeader()); }
@Test public void testToString() { List<MetacardUpdater> updaterList = new ArrayList<>(); updaterList.add(new MetacardUpdaterImpl()); updaterList.add(new MetacardUpdaterImpl()); ListMetacardUpdater listUpdater = new ListMetacardUpdater(updaterList); String expected = "ListMetacardUpdater{metacardUpdaterList=" + updaterList.toString() + "}"; assertEquals(expected, listUpdater.toString()); }
@Test public void testReadBit() throws EOFException { ByteBuf byteBuf = new ByteBuf(); byteBuf.writeByte((byte) 0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(1, bitReader.readBit()); assertEquals(0, bitReader.readBit()); assertEquals(1, bitReader.readBit()); assertEquals(0, bitReader.readBit()); assertEquals(1, bitReader.readBit()); assertEquals(0, bitReader.readBit()); assertEquals(1, bitReader.readBit()); assertEquals(0, bitReader.readBit()); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> metacards = new HashSet<>(); Metacard metacard = mock(Metacard.class); metacards.add(metacard); Dictionary<String, Object> properties = new Hashtable<>(); Semaphore lock = mock(Semaphore.class); when(createResponse.getCreatedMetacards()).thenReturn(metacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(properties); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(lock); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.write(new byte[1024 * 1024]); MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(2); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); packetBuffer.write(new byte[1024 * 1024]); result = condition.isRolloverReady(packetBuffer); assertTrue(result); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", result.get()); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testDoAction() throws Exception { FilenameGenerator filenameGenerator = mock(FilenameGenerator.class); String filenameTemplate = "template"; CatalogFramework catalogFramework = mock(CatalogFramework.class); Context context = mock(Context.class); MetacardUpdater parentMetacardUpdater = mock(MetacardUpdater.class); UuidGenerator uuidGenerator = mock(UuidGenerator.class); SubjectOperations subjectOperations = mock(SubjectOperations.class); CatalogRolloverAction catalogRolloverAction = new CatalogRolloverAction(filenameGenerator, filenameTemplate, catalogFramework, context, parentMetacardUpdater, uuidGenerator, subjectOperations); MetacardImpl metacard = new MetacardImpl(); File tempFile = new File("tempFile"); when(context.modifyParentOrChild(any())).thenReturn(metacard); when(context.getUdpStreamProcessor().getSubject()).thenReturn(mock(Subject.class)); when(filenameGenerator.generateFilename()).thenReturn("filename"); when(catalogFramework.create(any(CreateRequest.class))).thenReturn(mock(CreateResponse.class)); catalogRolloverAction.doAction(metacard, tempFile); verify(context, times(1)).modifyParentOrChild(any()); verify(context.getUdpStreamProcessor(), times(1)).getSubject(); verify(filenameGenerator, times(1)).generateFilename(); verify(catalogFramework, times(1)).create(any(CreateRequest.class)); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] input = new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3)}; LineString lineString = factory.createLineString(input); Context context = new Context(); context.setSubsampleCount(2); GeometryOperator subsampler = new LinestringGeometrySubsampler(); Geometry result = subsampler.apply(lineString, context); Coordinate[] expectedOutput = new Coordinate[] {new Coordinate(0, 0), new Coordinate(2, 2)}; LineString expectedLineString = factory.createLineString(expectedOutput); assertEquals(expectedLineString, result); }
@Test public void testGetResourceSiteName() { Metacard metacard = new MetacardImpl(); metacard.setSourceId("TestSourceId"); CatalogInputAdapter catalogInputAdapter = new CatalogInputAdapter(); String result = catalogInputAdapter.getResourceSiteName(metacard); assertEquals("TestSourceId", result); }
@Test public void testToString() { SimplifyGeometryFunction simplifyGeometryFunction = new SimplifyGeometryFunction(); String expected = "SimplifyGeometryFunction{}"; String actual = simplifyGeometryFunction.toString(); assertEquals(expected, actual); }
@Test public void testAccept() { Visitor visitor = mock(Visitor.class); MegabyteCountRolloverCondition condition = new MegabyteCountRolloverCondition(10L); condition.accept(visitor); verify(visitor, times(1)).visit(condition); }
@Test public void testNitfDate() { DateTime nitfDateTime = new DateTime(); nitfDateTime.setZonedDateTime(ZonedDateTime.now()); Date expectedDate = Date.from(nitfDateTime.getZonedDateTime().toInstant()); Date actualDate = NitfAttributeConverters.nitfDate(nitfDateTime); assertEquals(expectedDate, actualDate); }
@Test public void testNitfDate() { DateTime nitfDateTime = new DateTime(); nitfDateTime.setZonedDateTime(ZonedDateTime.now()); Date expectedDate = Date.from(nitfDateTime.getZonedDateTime().toInstant()); Date actualDate = NitfAttributeConverters.nitfDate(nitfDateTime); assertEquals(expectedDate, actualDate); }
@Test public void testGetNitfBinaryContent() throws IOException, MimeTypeParseException, NitfFormatException { BufferedImage chip = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); NitfSegmentsFlow nitfSegmentsFlow = new NitfSegmentsFlow(); int sourceX = 0; int sourceY = 0; Semaphore lock = new Semaphore(1); CatalogOutputAdapter catalogOutputAdapter = new CatalogOutputAdapter(lock); BinaryContent binaryContent = catalogOutputAdapter.getNitfBinaryContent(chip, nitfSegmentsFlow, sourceX, sourceY); assertNotNull(binaryContent); }
@Test public void testStreamEnded() { Context context = mock(Context.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Factory factory = mock(Factory.class); Metacard parentMetacard = mock(Metacard.class); AtomicBoolean isParentDirty = new AtomicBoolean(true); when(context.modifyParentOrChild(any(Function.class))).thenReturn(null); when(context.getParentMetacard()).thenReturn(Optional.of(parentMetacard)); FindChildrenStreamEndPlugin plugin = new FindChildrenStreamEndPlugin(filterBuilder, factory); plugin.streamEnded(context); verify(context, times(1)).modifyParentOrChild(any(Function.class)); verify(context, times(1)).getParentMetacard(); verify(parentMetacard, times(1)).handleParentMetacard(context, parentMetacard); assertFalse(isParentDirty.get()); }
@Test public void testSetMonitoredAddress() throws Exception { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); String monitoredAddress = "udp: udpStreamMonitor.setMonitoredAddress(monitoredAddress); assertEquals(new URI(monitoredAddress), udpStreamMonitor.getStreamUri()); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testTimerFactory() { TimerFactory timerFactory = new TimerFactory(); Timer timer = timerFactory.get(); assertNotNull(timer); }
@Test public void testFindStart() { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(new byte[]{0x00, 0x00, 0x01, 0xB3, 0x45, 0x67, 0x89}); BitReader bitReader = new BitReader(byteBuf); Optional<Long> start = bitReader.findStart(); assertTrue(start.isPresent()); assertEquals(0xB3, start.get().longValue()); }
@Test public void testToString() { List<MetacardType> metacardTypeList = new ArrayList<>(); metacardTypeList.add(new MetacardTypeImpl("type1")); metacardTypeList.add(new MetacardTypeImpl("type2")); CreateMetacardRolloverAction action = new CreateMetacardRolloverAction(metacardTypeList); String expected = "CreateMetacardRolloverAction{metacardTypeList=[type1, type2]}"; assertEquals(expected, action.toString()); }
@Test public void testCreateStanag4609Handlers() { KlvHandlerFactoryImpl factory = new KlvHandlerFactoryImpl(); Map<String, KlvHandler> handlers = factory.createStanag4609Handlers(); assertNotNull(handlers); assertEquals(31, handlers.size()); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.MISSION_ID)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.PLATFORM_TAIL_NUMBER)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.PLATFORM_DESIGNATION)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_1)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_1)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_2)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_2)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_3)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_3)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LATITUDE_4)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OFFSET_CORNER_LONGITUDE_4)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.PLATFORM_CALL_SIGN)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.EVENT_START_TIME)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OPERATIONAL_MODE)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LATITUDE_1)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LONGITUDE_1)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LATITUDE_2)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LONGITUDE_2)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LATITUDE_3)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LONGITUDE_3)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LATITUDE_4)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CORNER_LONGITUDE_4)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.SECURITY_CLASSIFICATION)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CLASSIFYING_COUNTRY_CODING_METHOD)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CLASSIFYING_COUNTRY)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OBJECT_COUNTRY_CODING_METHOD)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.OBJECT_COUNTRY_CODES)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.TIMESTAMP)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.CHECKSUM)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.IMAGE_COORDINATE_SYSTEM)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.IMAGE_SOURCE_SENSOR)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.TARGET_WIDTH)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.FRAME_CENTER_ELEVATION)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.SENSOR_TRUE_ALTITUDE)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.GROUND_RANGE)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.SLANT_RANGE)); assertTrue(handlers.containsKey(Stanag4609TransportStreamParser.TARGET_LOCATION_ELEVATION)); }
@Test public void testGetPacketId() { List<NALUnit> nalUnits = new ArrayList<>(); nalUnits.add(new NALUnit()); nalUnits.add(new NALUnit()); int packetId = 123; Mpeg4DecodedStreamData mpeg4DecodedStreamData = new Mpeg4DecodedStreamData(nalUnits, packetId); assertEquals(packetId, mpeg4DecodedStreamData.getPacketId()); }
@Test public void testNitfDate() { DateTime nitfDateTime = new DateTime(); nitfDateTime.setZonedDateTime(ZonedDateTime.now()); Date expectedDate = Date.from(nitfDateTime.getZonedDateTime().toInstant()); Date actualDate = NitfAttributeConverters.nitfDate(nitfDateTime); assertEquals(expectedDate, actualDate); }
@Test public void testScaleChip() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BufferedImage overview = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Map<String, Serializable> args = new HashMap<>(); args.put("x", 10); args.put("y", 20); args.put("w", 30); args.put("h", 40); CropAdapter cropAdapter = new CropAdapter(); int[] result = cropAdapter.scaleChip(original, overview, args); assertEquals(20, result[0]); assertEquals(40, result[1]); assertEquals(60, result[2]); assertEquals(80, result[3]); }
@Test public void testToString() { List<RolloverAction> actionList = new ArrayList<>(); actionList.add(new RolloverAction()); actionList.add(new RolloverAction()); ListRolloverAction listRolloverAction = new ListRolloverAction(actionList); String expected = "ListRolloverAction{actionList=" + actionList + "}"; assertEquals(expected, listRolloverAction.toString()); }
@Test public void testStreamEnded() { Context context = mock(Context.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Factory factory = mock(Factory.class); Metacard parentMetacard = mock(Metacard.class); AtomicBoolean isParentDirty = new AtomicBoolean(true); when(context.modifyParentOrChild(any(Function.class))).thenReturn(null); when(context.getParentMetacard()).thenReturn(Optional.of(parentMetacard)); FindChildrenStreamEndPlugin plugin = new FindChildrenStreamEndPlugin(filterBuilder, factory); plugin.streamEnded(context); verify(context, times(1)).modifyParentOrChild(any(Function.class)); verify(context, times(1)).getParentMetacard(); verify(parentMetacard, times(1)).handleParentMetacard(context, parentMetacard); assertFalse(isParentDirty.get()); }
@Test public void testGetStreamUri() throws Exception { BundleContext bundleContext = mock(BundleContext.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(bundleContext); Optional<URI> uri = udpStreamMonitor.getStreamUri(); assertFalse(uri.isPresent()); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); UdpStreamMonitor udpStreamMonitor2 = new UdpStreamMonitor(udpStreamProcessor); Optional<URI> uri2 = udpStreamMonitor2.getStreamUri(); assertFalse(uri2.isPresent()); }
@Test public void asAttributeTest() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); geoBoxHandler.addValue("10.0", "20.0", "30.0", "40.0", "50.0", "60.0", "70.0", "80.0"); Optional<Attribute> attribute = geoBoxHandler.asAttribute(); assertTrue(attribute.isPresent()); Attribute attr = attribute.get(); assertEquals("attributeName", attr.getName()); List<String> polygonsWkts = (List<String>) attr.getValue(); assertEquals(1, polygonsWkts.size()); assertEquals("POLYGON ((20.0 10.0, 40.0 30.0, 60.0 50.0, 80.0 70.0, 20.0 10.0))", polygonsWkts.get(0)); }
@Test public void testAccept() { DistinctKlvProcessor processor = new DistinctKlvProcessor("attributeName", "stanagFieldName"); Visitor visitor = mock(Visitor.class); processor.accept(visitor); verify(visitor, times(1)).visit(processor); }
@Test public void testHandle() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new KlvHandler(); Map<Integer, List<DecodedKLVMetadataPacket>> stanagMetadata = new HashMap<>(); List<DecodedKLVMetadataPacket> metadataList = new ArrayList<>(); DecodedKLVMetadataPacket metadataPacket = new DecodedKLVMetadataPacket(); metadataPacket.setDecodedKLV(new byte[]{0x01, 0x02, 0x03}); metadataList.add(metadataPacket); stanagMetadata.put(1, metadataList); PostProcessor postProcessor = new PostProcessorImpl(); Stanag4609Processor stanagProcessor = new Stanag4609ProcessorImpl(postProcessor); stanagProcessor.handle(handlers, defaultHandler, stanagMetadata); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] coordinates = new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2) }; Geometry geometry = factory.createLineString(coordinates); Context context = new Context(); SimplifyGeometryFunction simplifyGeometryFunction = new SimplifyGeometryFunction(); Geometry result = simplifyGeometryFunction.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testAccept() { ElapsedTimeRolloverCondition condition = new ElapsedTimeRolloverCondition(1000L); Visitor visitor = mock(Visitor.class); condition.accept(visitor); verify(visitor, times(1)).visit(condition); }
@Test public void testGetNitfBinaryContent() throws IOException, MimeTypeParseException, NitfFormatException { BufferedImage chip = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); NitfSegmentsFlow nitfSegmentsFlow = new NitfSegmentsFlow(); int sourceX = 0; int sourceY = 0; Semaphore lock = new Semaphore(1); CatalogOutputAdapter catalogOutputAdapter = new CatalogOutputAdapter(lock); BinaryContent binaryContent = catalogOutputAdapter.getNitfBinaryContent(chip, nitfSegmentsFlow, sourceX, sourceY); assertNotNull(binaryContent); }
@Test public void testUpdate() { Metacard parent = new MetacardImpl(); Metacard child = new MetacardImpl(); Context context = new ContextImpl(); List<MetacardUpdater> metacardUpdaterList = new ArrayList<>(); metacardUpdaterList.add(new MockMetacardUpdater()); ListMetacardUpdater listMetacardUpdater = new ListMetacardUpdater(metacardUpdaterList); listMetacardUpdater.update(parent, child, context); } class MockMetacardUpdater implements MetacardUpdater { @Override public void update(Metacard parent, Metacard child, Context context) { } }
@Test public void testSetMetacardTypeList() { List<MetacardType> metacardTypeList = new ArrayList<>(); metacardTypeList.add(new BasicMetacardType()); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); udpStreamMonitor.setMetacardTypeList(metacardTypeList); assertEquals(metacardTypeList, udpStreamMonitor.udpStreamProcessor.getMetacardTypeList()); }
@Test public void testAccept() { List<NALUnit> nalUnits = new ArrayList<>(); nalUnits.add(new NALUnit()); int packetId = 1; Mpeg4DecodedStreamData mpeg4DecodedStreamData = new Mpeg4DecodedStreamData(nalUnits, packetId); Visitor visitor = mock(Visitor.class); mpeg4DecodedStreamData.accept(visitor); verify(visitor, times(1)).visit(mpeg4DecodedStreamData); }
@Test public void testToString() { ElapsedTimeRolloverCondition condition = new ElapsedTimeRolloverCondition(1000L); String expected = "ElapsedTimeRolloverCondition{elapsedTimeThreshold=1000}"; assertEquals(expected, condition.toString()); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] input = new Coordinate[] {new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2), new Coordinate(3, 3)}; LineString lineString = factory.createLineString(input); Context context = new Context(); context.setSubsampleCount(2); GeometryOperator subsampler = new LinestringGeometrySubsampler(); Geometry result = subsampler.apply(lineString, context); Coordinate[] expectedOutput = new Coordinate[] {new Coordinate(0, 0), new Coordinate(2, 2)}; LineString expectedLineString = factory.createLineString(expectedOutput); assertEquals(expectedLineString, result); }
@Test public void testGetNitfSegmentsFlow() throws NitfFormatException, IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); when(resourceResponse.getResource()).thenReturn(resource); when(resource.getInputStream()).thenReturn(inputStream); NitfSegmentsFlow nitfSegmentsFlow = adapter.getNitfSegmentsFlow(resourceResponse); assertNotNull(nitfSegmentsFlow); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.setAge(1000); ElapsedTimeRolloverCondition condition = new ElapsedTimeRolloverCondition(500); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); }
@Test public void testSetElapsedTimeRolloverCondition() { Long milliseconds = 1000L; UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setElapsedTimeRolloverCondition(milliseconds); assertEquals(milliseconds, udpStreamMonitor.elapsedTimeRolloverCondition); }
@Test public void testAcftbAttribute() { AttributeDescriptor attributeDescriptor = new AttributeDescriptor(); Function<Tre, Serializable> accessorFunction = tre -> "test"; AcftbAttribute acftbAttribute = new AcftbAttribute("longName", "shortName", accessorFunction, attributeDescriptor, "extNitfName"); assertNotNull(acftbAttribute); }
@Test public void testApply() { List<GeometryOperator> operatorList = new ArrayList<>(); operatorList.add((g, c) -> g.buffer(10)); operatorList.add((g, c) -> g.convexHull()); GeometryOperatorList operator = new GeometryOperatorList(operatorList); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(0, 0)); Context context = new Context(); Geometry result = operator.apply(geometry, context); assertNotNull(result); }
@Test public void testIsRolloverReady() { PacketBuffer packetBuffer = new PacketBuffer(); packetBuffer.setAge(1000); ElapsedTimeRolloverCondition condition = new ElapsedTimeRolloverCondition(500); boolean result = condition.isRolloverReady(packetBuffer); assertFalse(result); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testCreateChannelHandlers() { StreamMonitor streamMonitor = mock(StreamMonitor.class); BundleContext bundleContext = mock(BundleContext.class); UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(streamMonitor, bundleContext); ChannelHandler[] channelHandlers = udpStreamProcessor.createChannelHandlers(); assertNotNull(channelHandlers); assertEquals(4, channelHandlers.length); assertTrue(channelHandlers[0] instanceof RawUdpDataToMTSPacketDecoder); assertTrue(channelHandlers[1] instanceof MTSPacketToPESPacketDecoder); assertTrue(channelHandlers[2] instanceof PESPacketToApplicationDataDecoder); assertTrue(channelHandlers[3] instanceof DecodedStreamDataHandler); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] coordinates = new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2) }; Geometry geometry = factory.createLineString(coordinates); Context context = new Context(); SimplifyGeometryFunction simplifyGeometryFunction = new SimplifyGeometryFunction(); Geometry result = simplifyGeometryFunction.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testPiaprdAttribute() { Tre tre = new Tre(); tre.add(new TreEntry("PIAPRD", "value")); PiaprdAttribute piaprdAttribute = new PiaprdAttribute("longName", "shortName", Tre::getTreValue, AttributeType.STRING); assertEquals("value", piaprdAttribute.getAccessorFunction().apply(tre)); }
@Test public void testHandle() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new KlvHandler(); Map<Integer, List<DecodedKLVMetadataPacket>> stanagMetadata = new HashMap<>(); List<DecodedKLVMetadataPacket> metadataList = new ArrayList<>(); DecodedKLVMetadataPacket metadataPacket = new DecodedKLVMetadataPacket(); metadataPacket.setDecodedKLV(new byte[]{0x01, 0x02, 0x03}); metadataList.add(metadataPacket); stanagMetadata.put(1, metadataList); PostProcessor postProcessor = new PostProcessorImpl(); Stanag4609Processor stanagProcessor = new Stanag4609ProcessorImpl(postProcessor); stanagProcessor.handle(handlers, defaultHandler, stanagMetadata); }
@Test public void testReadBits() throws EOFException { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeByte(0b10101010); BitReader bitReader = new BitReader(byteBuf); assertEquals(0b1, bitReader.readBits(1)); assertEquals(0b01, bitReader.readBits(2)); assertEquals(0b010, bitReader.readBits(3)); assertEquals(0b1010, bitReader.readBits(4)); }
@Test public void testIsNotStringNone() { assertTrue(Utilities.isNotStringNone("test")); assertTrue(Utilities.isNotStringNone("Test")); assertTrue(Utilities.isNotStringNone("TEST")); assertFalse(Utilities.isNotStringNone("None")); assertFalse(Utilities.isNotStringNone(" none ")); assertFalse(Utilities.isNotStringNone(null)); assertFalse(Utilities.isNotStringNone(123)); }
@Test public void testCreateParser() { ByteSource byteSource = new ByteSource(); StanagParserFactoryImpl factory = new StanagParserFactoryImpl(); Stanag4609Parser parser = factory.createParser(byteSource).parse(); assertNotNull(parser); }
@Test public void testGetLongitude2() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); String longitude2 = geoBoxHandler.getLongitude2(); assertEquals("long2", longitude2); }
@Test public void testFrameComplete() { PacketBuffer packetBuffer = new PacketBuffer(); DecodedStreamDataHandler handler = new DecodedStreamDataHandler(packetBuffer); handler.frameComplete(true); assertEquals(PacketBuffer.FrameType.IDR, packetBuffer.getCurrentFrameType()); }
@Test public void testGetRawGeoData() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "10.0", "20.0", "30.0", "40.0", "50.0", "60.0", "70.0", "80.0"); Map<String, List<Double>> expectedMap = new HashMap<>(); expectedMap.put("latitude", Arrays.asList(10.0, 30.0, 50.0, 70.0)); expectedMap.put("longitude", Arrays.asList(20.0, 40.0, 60.0, 80.0)); assertEquals(expectedMap, geoBoxHandler.getRawGeoData()); }
@Test public void testSetSecurityClassificationCode1() { MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer(null, null, null, null, null, null, null, 0.0); inputTransformer.setSecurityClassificationCode1("SECRET"); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] coordinates = new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2) }; Geometry geometry = factory.createLineString(coordinates); Context context = new Context(); SimplifyGeometryFunction function = new SimplifyGeometryFunction(); Geometry result = function.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testSetFilenameGenerator() { FilenameGenerator filenameGenerator = mock(FilenameGenerator.class); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setFilenameGenerator(filenameGenerator); verify(udpStreamProcessor).setFilenameGenerator(filenameGenerator); }
@Test public void testProcess() { SecurityAttributes securityAttributes = new SecurityAttributes(); SystemHighAttributes systemHighAttributes = new SystemHighAttributes(); Map<String, String> initialValues = new HashMap<>(); DefaultSecurityAttributeValuesPlugin plugin = new DefaultSecurityAttributeValuesPlugin(securityAttributes, systemHighAttributes, initialValues); Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl("attribute1", "value1")); List<Metacard> metacards = new ArrayList<>(); metacards.add(metacard); CreateRequest createRequest = new CreateRequestImpl(metacards, null, null); CreateRequest processedRequest = plugin.process(createRequest); List<Metacard> updatedMetacards = processedRequest.getMetacards(); assertEquals(1, updatedMetacards.size()); Metacard updatedMetacard = updatedMetacards.get(0); assertNotNull(updatedMetacard.getAttribute("attribute1")); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getAccessControl())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getClassification())); assertNotNull(updatedMetacard.getAttribute(securityAttributes.getOwnerProducer())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getCodeWords())); assertNotNull(updatedMetacard.getAttribute(systemHighAttributes.getDisseminationControls())); }
@Test public void testSetDistanceTolerance() { Double distanceTolerance = 10.0; MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer( mock(InputTransformer.class), Arrays.asList(mock(MetacardType.class)), mock(Stanag4609Processor.class), mock(KlvHandlerFactory.class), mock(KlvHandler.class), mock(StanagParserFactory.class), mock(KlvProcessor.class), distanceTolerance ); inputTransformer.setDistanceTolerance(distanceTolerance); assertEquals(distanceTolerance, inputTransformer.distanceTolerance); }
@Test public void testChannel() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); when(nitfSegmentsFlow.fileHeader(any())).thenReturn(true); when(nitfSegmentsFlow.forEachImageSegment(any())).thenReturn(true); RoutingSlip routingSlip = new RoutingSlip(); String result = routingSlip.channel(nitfSegmentsFlow); assertEquals("GMTI_ROUTE", result); }
@Test public void testApply() { Geometry geometry = new Geometry(); geometry.addPoint(0, 0); geometry.addPoint(3, 4); geometry.addPoint(6, 8); NormalizeGeometry normalizeGeometry = new NormalizeGeometry(); Context context = new Context(); Geometry result = normalizeGeometry.apply(geometry, context); assertEquals(0.0, result.getPoint(0).getX(), 0.001); assertEquals(0.0, result.getPoint(0).getY(), 0.001); assertEquals(0.375, result.getPoint(1).getX(), 0.001); assertEquals(0.5, result.getPoint(1).getY(), 0.001); assertEquals(0.75, result.getPoint(2).getX(), 0.001); assertEquals(1.0, result.getPoint(2).getY(), 0.001); }
@Test public void testEnd() { UpdateField updateField = new UpdateField(); UpdateParent updateParent = new UpdateParent(updateField); Context context = new Context(); Metacard parentMetacard = new MetacardImpl(); updateParent.end(context, parentMetacard); }
@Test public void testGetAttributes() { List<NitfAttribute<Tre>> attributes = AimidbAttribute.getAttributes(); assertNotNull(attributes); assertEquals(ATTRIBUTES.size(), attributes.size()); for (int i = 0; i < ATTRIBUTES.size(); i++) { assertEquals(ATTRIBUTES.get(i).getLongName(), attributes.get(i).getLongName()); assertEquals(ATTRIBUTES.get(i).getShortName(), attributes.get(i).getShortName()); assertEquals(ATTRIBUTES.get(i).getAttributeType(), attributes.get(i).getAttributeType()); } }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> createdMetacards = new HashSet<>(); createdMetacards.add(mock(Metacard.class)); when(createResponse.getCreatedMetacards()).thenReturn(createdMetacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(new HashMap<>()); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> metacards = new HashSet<>(); Metacard metacard = mock(Metacard.class); metacards.add(metacard); Dictionary<String, Object> properties = new Hashtable<>(); Semaphore lock = mock(Semaphore.class); when(createResponse.getCreatedMetacards()).thenReturn(metacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(properties); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(lock); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testTransform() throws IOException, CatalogTransformerException { InputTransformer inputTransformer = mock(InputTransformer.class); List<MetacardType> metacardTypes = new ArrayList<>(); Stanag4609Processor stanag4609Processor = mock(Stanag4609Processor.class); KlvHandlerFactory klvHandlerFactory = mock(KlvHandlerFactory.class); KlvHandler defaultKlvHandler = mock(KlvHandler.class); StanagParserFactory stanagParserFactory = mock(StanagParserFactory.class); KlvProcessor klvProcessor = mock(KlvProcessor.class); Double distanceTolerance = 0.5; MpegTsInputTransformer mpegTsInputTransformer = new MpegTsInputTransformer(inputTransformer, metacardTypes, stanag4609Processor, klvHandlerFactory, defaultKlvHandler, stanagParserFactory, klvProcessor, distanceTolerance); InputStream inputStream = new ByteArrayInputStream("test".getBytes()); Metacard metacard = mock(Metacard.class); when(inputTransformer.transform(inputStream)).thenReturn(metacard); Metacard result = mpegTsInputTransformer.transform(inputStream); assertEquals(metacard, result); }
@Test public void testGetBinaryContent() throws IOException, MimeTypeParseException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); BinaryContent binaryContent = adapter.getBinaryContent(image); assertNotNull(binaryContent); }
@Test public void testToString() { NormalizeGeometry normalizeGeometry = new NormalizeGeometry(); String expected = "NormalizeGeometry{}"; String result = normalizeGeometry.toString(); assertEquals(expected, result); }
@Test public void testGetImage() throws IOException { Semaphore lock = new Semaphore(1); CatalogOutputAdapter adapter = new CatalogOutputAdapter(lock); ResourceResponse resourceResponse = mock(ResourceResponse.class); Resource resource = mock(Resource.class); InputStream inputStream = new ByteArrayInputStream(new byte[]{1, 2, 3}); when(resource.getInputStream()).thenReturn(inputStream); when(resourceResponse.getResource()).thenReturn(resource); BufferedImage expectedImage = ImageIO.read(inputStream); BufferedImage actualImage = adapter.getImage(resourceResponse); assertEquals(expectedImage, actualImage); }
@Test public void testAccept() { LoggingKlvHandler handler = new LoggingKlvHandler(); KlvDataElement element = new KlvDataElement("test", "value"); handler.accept(element); }
@Test public void testChannel() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); when(nitfSegmentsFlow.fileHeader(any())).thenReturn(true); when(nitfSegmentsFlow.forEachImageSegment(any())).thenReturn(true); RoutingSlip routingSlip = new RoutingSlip(); String result = routingSlip.channel(nitfSegmentsFlow); assertEquals("GMTI_ROUTE", result); }
@Test public void testApply() { GeometryFactory factory = new GeometryFactory(); Coordinate[] coordinates = new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 1), new Coordinate(2, 2) }; Geometry geometry = factory.createLineString(coordinates); Context context = new Context(); SimplifyGeometryFunction simplifyGeometryFunction = new SimplifyGeometryFunction(); Geometry result = simplifyGeometryFunction.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testStreamEnded() { Context context = mock(Context.class); FilterBuilder filterBuilder = mock(FilterBuilder.class); Factory factory = mock(Factory.class); Metacard parentMetacard = mock(Metacard.class); AtomicBoolean isParentDirty = new AtomicBoolean(true); when(context.modifyParentOrChild(any(Function.class))).thenReturn(null); when(context.getParentMetacard()).thenReturn(Optional.of(parentMetacard)); FindChildrenStreamEndPlugin plugin = new FindChildrenStreamEndPlugin(filterBuilder, factory); plugin.streamEnded(context); verify(context, times(1)).modifyParentOrChild(any(Function.class)); verify(context, times(1)).getParentMetacard(); verify(parentMetacard, times(1)).handleParentMetacard(context, parentMetacard); assertFalse(isParentDirty.get()); }
@Test public void testBuild() { GeometryOperator geometryOperator = new GeometryOperator(); GeometryFactory geometryFactory = new GeometryFactory(); FrameCenterUpdateFieldFactory factory = new FrameCenterUpdateFieldFactory(geometryOperator, geometryFactory); UpdateParent.UpdateField updateField = factory.build(); assertNotNull(updateField); assertTrue(updateField instanceof FrameCenterUpdateField); }
@Test public void testProcess() throws PluginExecutionException { CreateResponse createResponse = mock(CreateResponse.class); Request request = mock(Request.class); Set<Metacard> createdMetacards = new HashSet<>(); createdMetacards.add(mock(Metacard.class)); when(createResponse.getCreatedMetacards()).thenReturn(createdMetacards); when(createResponse.getRequest()).thenReturn(request); when(request.getProperties()).thenReturn(new HashMap<>()); NitfPostIngestPlugin plugin = new NitfPostIngestPlugin(); CreateResponse result = plugin.process(createResponse); assertNotNull(result); assertEquals(createResponse, result); }
@Test public void testTransform() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); Metacard metacard = mock(Metacard.class); NitfGmtiTransformer nitfGmtiTransformer = new NitfGmtiTransformer(); when(nitfSegmentsFlow.getSegment(anyString())).thenReturn(mock(Segment.class)); nitfGmtiTransformer.transform(nitfSegmentsFlow, metacard); verify(nitfSegmentsFlow, times(2)).getSegment(anyString()); verify(metacard, times(1)).setAttribute(eq(Core.LOCATION), anyString()); verify(metacard, times(1)).setAttribute(eq(Core.LOCATION), any(Geometry.class)); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testSetMetacardTypeList() { List<MetacardType> metacardTypeList = new ArrayList<>(); metacardTypeList.add(new BasicMetacardType()); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); udpStreamMonitor.setMetacardTypeList(metacardTypeList); assertEquals(metacardTypeList, udpStreamMonitor.udpStreamProcessor.getMetacardTypeList()); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 0); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 10); processor.process(handlers, metacard, configuration); assertNotNull(metacard.getLocation()); PointImpl location = new PointImpl(1.0, 2.0); metacard.setLocation(location); processor.process(handlers, metacard, configuration); assertEquals(location, metacard.getLocation()); }
@Test public void testTrim() { LatitudeLongitudeHandler handler = new LatitudeLongitudeHandler("attributeName", "latitudeFieldName", "longitudeFieldName"); List<Double> latitudeList = new ArrayList<>(Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0)); List<Double> longitudeList = new ArrayList<>(Arrays.asList(6.0, 7.0, 8.0, 9.0, 10.0)); handler.addValue(latitudeList, "latitudeFieldName"); handler.addValue(longitudeList, "longitudeFieldName"); handler.trim(); assertEquals(3, handler.getValue("latitudeFieldName").size()); assertEquals(3, handler.getValue("longitudeFieldName").size()); }
@Test public void testSetSecurityClassificationCode2() { MpegTsInputTransformer inputTransformer = new MpegTsInputTransformer(null, null, null, null, null, null, null, 0.0); inputTransformer.setSecurityClassificationCode2("SECRET"); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))", result.get()); }
@Test public void testHandle() { UpdateField updateField = mock(UpdateField.class); UpdateParent updateParent = new UpdateParent(updateField); Context context = mock(Context.class); Metacard parent = mock(Metacard.class); List<Metacard> children = new ArrayList<>(); children.add(mock(Metacard.class)); updateParent.handle(context, parent, children); verify(updateField, times(1)).updateField(parent, children, context); }
@Test public void testSetOutputStreamFactory() { PacketBuffer packetBuffer = new PacketBuffer(); OutputStreamFactory outputStreamFactory = new OutputStreamFactory(); packetBuffer.setOutputStreamFactory(outputStreamFactory); assertNotNull(packetBuffer.outputStreamFactory); }
@Test public void testSafelySetAttribute() { Metacard metacard = new MetacardImpl(); Attribute attribute = new AttributeImpl("testAttribute", "testValue"); Utilities.safelySetAttribute(metacard, attribute); assertEquals("testValue", metacard.getAttribute("testAttribute").getValue()); }
@Test public void testGetLongitude3() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("long3", geoBoxHandler.getLongitude3()); }
@Test public void testGetLongitude4() { GeoBoxHandler geoBoxHandler = new GeoBoxHandler("attributeName", "lat1", "long1", "lat2", "long2", "lat3", "long3", "lat4", "long4"); assertEquals("long4", geoBoxHandler.getLongitude4()); }
@Test public void testSetMonitoredAddress() throws Exception { UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); String monitoredAddress = "udp: udpStreamMonitor.setMonitoredAddress(monitoredAddress); assertEquals(new URI(monitoredAddress), udpStreamMonitor.getStreamUri()); }
@Test public void testSetFilenameTemplate() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); String template = "test_template"; udpStreamMonitor.setFilenameTemplate(template); assertEquals(template, udpStreamMonitor.filenameTemplate); }
@Test public void testBuild() { GeometryOperator preUnionGeometryOperator = new GeometryOperator(); GeometryOperator postUnionGeometryOperator = new GeometryOperator(); LocationUpdateFieldFactory locationUpdateFieldFactory = new LocationUpdateFieldFactory(preUnionGeometryOperator, postUnionGeometryOperator); UpdateParent.UpdateField updateField = locationUpdateFieldFactory.build(); assertNotNull(updateField); assertTrue(updateField instanceof LocationUpdateField); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.WHITE.getRGB(), croppedImage.getRGB(59, 0)); assertEquals(Color.WHITE.getRGB(), croppedImage.getRGB(0, 59)); }
@Test public void testApply() { GeometryReducer geometryReducer = new GeometryReducer(); Geometry geometry = new GeometryFactory().createPoint(new Coordinate(1.0, 2.0)); Context context = new Context(); Geometry result = geometryReducer.apply(geometry, context); assertEquals(geometry, result); }
@Test public void testSetFilenameTemplate() { UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); String template = "test_template"; udpStreamMonitor.setFilenameTemplate(template); assertEquals(template, udpStreamMonitor.filenameTemplate); }
@Test public void testGetGeometryFunction() { GeometryOperator preUnionGeometryOperator = new GeometryOperatorImpl(); GeometryOperator postUnionGeometryOperator = new GeometryOperatorImpl(); LocationKlvProcessor locationKlvProcessor = new LocationKlvProcessor(preUnionGeometryOperator, postUnionGeometryOperator); assertEquals(postUnionGeometryOperator, locationKlvProcessor.getGeometryFunction()); }
@Test public void testChannel() { NitfSegmentsFlow nitfSegmentsFlow = mock(NitfSegmentsFlow.class); when(nitfSegmentsFlow.fileHeader(any())).thenReturn(true); when(nitfSegmentsFlow.forEachImageSegment(any())).thenReturn(true); RoutingSlip routingSlip = new RoutingSlip(); String result = routingSlip.channel(nitfSegmentsFlow); assertEquals("GMTI_ROUTE", result); }
@Test public void testSetElapsedTimeRolloverCondition() { Long milliseconds = 1000L; UdpStreamProcessor udpStreamProcessor = new UdpStreamProcessor(); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); udpStreamMonitor.setElapsedTimeRolloverCondition(milliseconds); assertEquals(milliseconds, udpStreamMonitor.elapsedTimeRolloverCondition); }
@Test public void testAccept() { List<KlvProcessor> klvProcessorList = new ArrayList<>(); KlvProcessor klvProcessor1 = mock(KlvProcessor.class); KlvProcessor klvProcessor2 = mock(KlvProcessor.class); klvProcessorList.add(klvProcessor1); klvProcessorList.add(klvProcessor2); Visitor visitor = mock(Visitor.class); ListKlvProcessor listKlvProcessor = new ListKlvProcessor(klvProcessorList); listKlvProcessor.accept(visitor); verify(klvProcessor1, times(1)).accept(visitor); verify(klvProcessor2, times(1)).accept(visitor); }
@Test public void testCallDataElementHandlers() { Map<String, KlvHandler> handlers = new HashMap<>(); KlvHandler defaultHandler = new DefaultKlvHandler(); KlvDataElement klvDataElement = new KlvDataElement("name", new byte[]{0x01, 0x02, 0x03}); Map<String, KlvDataElement> dataElements = new HashMap<>(); Stanag4609ProcessorImpl processor = new Stanag4609ProcessorImpl(new PostProcessor()); processor.callDataElementHandlers(handlers, defaultHandler, klvDataElement, dataElements); assertEquals(klvDataElement, dataElements.get("name")); }
@Test public void testFipsToStandardCountryCode() throws NitfAttributeTransformException { NitfAttributeConverters converters = new NitfAttributeConverters(new CountryCodeConverter()); String fipsCode = "US"; String expected = "USA"; String result = converters.fipsToStandardCountryCode(fipsCode); assertEquals(expected, result); }
@Test public void testCreateUnionOfGeometryAttribute() { WKTReader wktReader = new WKTReader(); WKTWriter wktWriter = new WKTWriter(); Attribute attribute = new Attribute("geometry", "POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))"); GeometryOperator.Context geometryOperatorContext = new GeometryOperator.Context(); Optional<String> result = GeometryUtility.createUnionOfGeometryAttribute(wktReader, wktWriter, attribute, geometryOperatorContext); assertTrue(result.isPresent()); assertEquals("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))", result.get()); }
@Test public void testDecode() throws Exception { MTSPacketToPESPacketDecoder decoder = new MTSPacketToPESPacketDecoder(new MpegTsDecoder()); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); MTSPacket mtsPacket = new MTSPacket(); List<Object> outputList = new ArrayList<>(); decoder.decode(ctx, mtsPacket, outputList); assertFalse(outputList.isEmpty()); }
@Test public void testGetStreamUri() throws Exception { BundleContext bundleContext = mock(BundleContext.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(bundleContext); Optional<URI> uri = udpStreamMonitor.getStreamUri(); assertFalse(uri.isPresent()); UdpStreamProcessor udpStreamProcessor = mock(UdpStreamProcessor.class); udpStreamMonitor = new UdpStreamMonitor(udpStreamProcessor); uri = udpStreamMonitor.getStreamUri(); assertFalse(uri.isPresent()); }
@Test public void testBuildReadRequest() throws URISyntaxException { Metacard metacard = new MetacardImpl(); metacard.setAttribute(new AttributeImpl(Core.RESOURCE_URI, "http: String qualifier = "testQualifier"; CatalogInputAdapter adapter = new CatalogInputAdapter(); ResourceRequest request = adapter.buildReadRequest(metacard, qualifier); assertNotNull(request); assertEquals(request.getAttributeName(), Core.RESOURCE_URI); assertEquals(request.getAttributeValue(), new URI("http: assertEquals(request.getProperties().get(ContentItem.QUALIFIER_KEYWORD), qualifier); }
@Test public void testDoAction() throws RolloverActionException { MetacardImpl metacard = new MetacardImpl(); File tempFile = new File("tempFile"); CreateMetacardRolloverAction action = new CreateMetacardRolloverAction(Collections.singletonList(new MetacardTypeImpl())); MetacardImpl newMetacard = action.doAction(metacard, tempFile); assertEquals(Constants.MPEGTS_MIME_TYPE, newMetacard.getContentTypeName()); }
@Test public void testSetCatalogFramework() { CatalogFramework catalogFramework = mock(CatalogFramework.class); UdpStreamMonitor udpStreamMonitor = new UdpStreamMonitor(mock(BundleContext.class)); udpStreamMonitor.setCatalogFramework(catalogFramework); verify(udpStreamMonitor.udpStreamProcessor).setCatalogFramework(catalogFramework); }
@Test public void testApply() { GeometryOperator operator = new NonEmptyGeometryOperator(); Geometry geometry = new Geometry(); Context context = new Context(); Geometry result = operator.apply(geometry, context); assertNull(result); geometry = new Geometry(); geometry.addPoint(new Point(0, 0)); result = operator.apply(geometry, context); assertNotNull(result); assertEquals(geometry, result); }
@Test public void testProcess() { Map<String, KlvHandler> handlers = new HashMap<>(); Metacard metacard = new MetacardImpl(); Configuration configuration = new ConfigurationImpl(); LocationKlvProcessor processor = new LocationKlvProcessor(); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 0); processor.process(handlers, metacard, configuration); assertNull(metacard.getLocation()); configuration.put(Configuration.SUBSAMPLE_COUNT, 10); processor.process(handlers, metacard, configuration); assertNotNull(metacard.getLocation()); PointImpl location = new PointImpl(1.0, 2.0); metacard.setLocation(location); processor.process(handlers, metacard, configuration); assertEquals(location, metacard.getLocation()); }
@Test public void testCrop() throws ChipOutOfBoundsException { BufferedImage inputImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = inputImage.createGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, 100, 100); graphics.setColor(Color.BLACK); graphics.fillRect(25, 25, 50, 50); graphics.dispose(); ChipServiceImpl chipService = new ChipServiceImpl(new Semaphore(1)); BufferedImage croppedImage = chipService.crop(inputImage, 20, 20, 60, 60); assertEquals(60, croppedImage.getWidth()); assertEquals(60, croppedImage.getHeight()); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 0)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(0, 59)); assertEquals(Color.BLACK.getRGB(), croppedImage.getRGB(59, 0)); }
@Test public void testFaparOp() { FaparOp faparOp = new FaparOp(); Pixel pixel = new Pixel(10, 20, 30); faparOp.apply(pixel); assertEquals(0.5, pixel.getRed(), 0.001); assertEquals(1.0, pixel.getGreen(), 0.001); assertEquals(0.0, pixel.getBlue(), 0.001); }
@Test public void testCompare() { Track track1 = new Track(1); Track track2 = new Track(2); TrackComparator comparator = new TrackComparator(); int result = comparator.compare(track1, track2); assertEquals(-1, result); }
@Test public void testRecentArtists() { Api api = mock(Api.class); HttpUrl url = HttpUrl.parse("https: String libKey = "libraryKey"; MediaService mediaService = new MediaService(api); Observable<MediaContainer> observable = mediaService.recentArtists(url, libKey); TestObserver<MediaContainer> testObserver = new TestObserver<>(); observable.subscribe(testObserver); testObserver.assertComplete(); testObserver.assertNoErrors(); verify(api).get(url.newBuilder() .addPathSegments("library/sections") .addPathSegment(libKey) .addPathSegment("all") .query("viewCount>=1&type=8&sort=lastViewedAt:desc") .addQueryParameter(TOKEN, url.queryParameter(TOKEN)) .build()); }
@Test public void testFirstCharacter() { Api api = mock(Api.class); MediaService mediaService = new MediaService(api); HttpUrl url = HttpUrl.parse("http: String libKey = "libraryKey"; String mediaKey = "mediaKey"; Observable<MediaContainer> observable = mediaService.firstCharacter(url, libKey, mediaKey); TestObserver<MediaContainer> testObserver = new TestObserver<>(); observable.subscribe(testObserver); testObserver.assertComplete(); testObserver.assertNoErrors(); verify(api).get(url.newBuilder() .addPathSegments("library/sections") .addPathSegment(libKey) .addPathSegment("firstCharacter") .addQueryParameter("type", mediaKey) .build()); }
@Test public void testGone() { View view = new View(); Views.gone(view); assertEquals(View.GONE, view.getVisibility()); }
@Test public void testOnPlaybackStatusChanged() { QueueManager queueManager = mock(QueueManager.class); PlaybackServiceCallback serviceCallback = mock(PlaybackServiceCallback.class); AndroidClock androidClock = mock(AndroidClock.class); Playback playback = mock(Playback.class); PlaybackManager playbackManager = new PlaybackManager(queueManager, serviceCallback, androidClock, playback); playbackManager.onPlaybackStatusChanged(); verify(serviceCallback, times(1)).onPlaybackStatusChanged(); }
@Test public void testStart() { MusicController musicController = mock(MusicController.class); QueueManager queueManager = mock(QueueManager.class); MediaService mediaService = mock(MediaService.class); Rx rx = mock(Rx.class); TimelineManager timelineManager = new TimelineManager(musicController, queueManager, mediaService, rx); timelineManager.start(); verify(musicController, times(1)).state(); verify(queueManager, times(1)).currentTrack(); verify(mediaService, times(1)).progress(); }
@Test public void testSections() { HttpUrl url = HttpUrl.parse("https: Api api = new Api(); MediaService mediaService = new MediaService(api); Observable<MediaContainer> observable = mediaService.sections(url); TestObserver<MediaContainer> testObserver = new TestObserver<>(); observable.subscribe(testObserver); testObserver.assertComplete(); testObserver.assertNoErrors(); }
@Test public void testAlbums() { Api api = mock(Api.class); HttpUrl url = HttpUrl.parse("https: MediaService mediaService = new MediaService(api); String artistKey = "12345"; Observable<MediaContainer> observable = mediaService.albums(url, artistKey); TestObserver<MediaContainer> observer = new TestObserver<>(); observable.subscribe(observer); observer.assertComplete(); observer.assertNoErrors(); verify(api).get(url.newBuilder() .addPathSegments("library/metadata") .addPathSegment(artistKey) .addPathSegment("children") .build()); }
@Test public void testPause() { Flowable<Long> seconds = Flowable.interval(1, TimeUnit.SECONDS); Rx rx = new Rx(); MusicController musicController = new MusicController(seconds, rx); mediaController = mock(MediaController.class); when(mediaController.getTransportControls().pause()).thenReturn(true); musicController.pause(); verify(mediaController.getTransportControls(), times(1)).pause(); }
@Test public void testDispose() { Scheduler io = Schedulers.io(); Scheduler ui = Schedulers.ui(); Scheduler newThread = Schedulers.newThread(); Rx rx = new Rx(io, ui, newThread); Disposable disposable = io.scheduleDirect(() -> System.out.println("Disposable")); Rx.dispose(disposable); assertTrue(disposable.isDisposed()); }
@Test public void testCompare() { Track track1 = new Track(1); Track track2 = new Track(2); TrackComparator comparator = new TrackComparator(); int result = comparator.compare(track1, track2); assertEquals(-1, result); }
@Test public void testCurrentTrack() { Random random = new Random(); QueueManager queueManager = new QueueManager(random); Track expectedTrack = queueManager.currentTrack(); Track actualTrack = queueManager.currentTrack(); assertEquals(expectedTrack, actualTrack); }
@Test public void testDispose() { Scheduler io = Schedulers.io(); Scheduler ui = Schedulers.single(); Scheduler newThread = Schedulers.newThread(); Rx rx = new Rx(io, ui, newThread); Disposable disposable = io.scheduleDirect(() -> System.out.println("Disposable")); Rx.dispose(disposable); assertTrue(disposable.isDisposed()); }
@Test public void testGetTranscodeUrl() { HttpUrl url = HttpUrl.parse("https: String imageKey = "abc123"; String expectedUrl = "https: assertEquals(expectedUrl, Urls.getTranscodeUrl(url, imageKey)); }
@Test public void testTimeline() { Api api = new Api(); HttpUrl url = HttpUrl.parse("https: long queueItemId = 123; String trackKey = "track123"; String trackRatingKey = "rating123"; String state = "playing"; long duration = 1000; long time = 500; MediaService mediaService = new MediaService(api); Completable completable = mediaService.timeline(url, queueItemId, trackKey, trackRatingKey, state, duration, time); completable.test().assertComplete(); }
@Test public void testInvisible() { View view = new View(); Views.invisible(view); assertEquals(View.INVISIBLE, view.getVisibility()); }
@Test public void testPrevious() { Flowable<Long> seconds = Flowable.just(1L, 2L, 3L); Rx rx = new Rx(); MusicController musicController = new MusicController(seconds, rx); MediaController mediaController = Mockito.mock(MediaController.class); when(mediaController.getTransportControls()).thenReturn(Mockito.mock(TransportControls.class)); musicController.mediaController = mediaController; musicController.previous(); verify(mediaController.getTransportControls(), times(1)).skipToPrevious(); }
@Test public void testStart() { MusicController musicController = mock(MusicController.class); QueueManager queueManager = mock(QueueManager.class); MediaService mediaService = mock(MediaService.class); Rx rx = mock(Rx.class); TimelineManager timelineManager = new TimelineManager(musicController, queueManager, mediaService, rx); timelineManager.start(); verify(musicController, times(1)).state(); verify(queueManager, times(1)).currentTrack(); verify(mediaService, times(1)).progress(); }
@Test public void testOnCompletion() { QueueManager queueManager = mock(QueueManager.class); when(queueManager.hasNext()).thenReturn(true).thenReturn(false); PlaybackServiceCallback serviceCallback = mock(PlaybackServiceCallback.class); AndroidClock androidClock = mock(AndroidClock.class); Playback playback = mock(Playback.class); PlaybackManager playbackManager = new PlaybackManager(queueManager, serviceCallback, androidClock, playback); playbackManager.onCompletion(); verify(queueManager, times(1)).next(); verify(serviceCallback, times(1)).onPlaybackStart(); playbackManager.onCompletion(); verify(serviceCallback, times(1)).onPlaybackStop(); }
@Test public void testAddPathToUrl() { HttpUrl url = HttpUrl.parse("https: String path = "path/to/resource"; HttpUrl expectedUrl = HttpUrl.parse("https: HttpUrl resultUrl = Urls.addPathToUrl(url, path); assertEquals(expectedUrl, resultUrl); }
@Test public void testIsBlank() { assertTrue(Strings.isBlank("")); assertTrue(Strings.isBlank(" ")); assertTrue(Strings.isBlank(null)); assertFalse(Strings.isBlank("hello")); assertFalse(Strings.isBlank(" hello ")); }
@Test public void testLogin() { String authToken = "testAuthToken"; AuthInterceptor authInterceptor = mock(AuthInterceptor.class); Prefs prefs = mock(Prefs.class); LoginManager loginManager = new LoginManager(authInterceptor, prefs); loginManager.login(authToken); verify(authInterceptor, times(1)).setAuthToken(authToken); verify(prefs, times(1)).putString(LoginManager.PREF_AUTH_TOKEN, authToken); }