method2testcases
stringlengths
118
3.08k
### Question: LogisticRegressionModel implements RegressionModel { @Override public BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x) { return applyHypothesisWithPrecision(theta, x); } LogisticRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }### Answer: @Test public void testCorrectHypothesisCalculation() throws Exception { LogisticRegressionModel logisticRegressionModel = new LogisticRegressionModel(); BigDecimal hypothesisValue = logisticRegressionModel.applyHypothesis(new DenseDoubleVector(new double[]{1, 1, 1}), new DenseDoubleVector(new double[]{2, 3, 4})); assertEquals("wrong hypothesis value for logistic regression", 0.9998766054240137682597533152954043d, hypothesisValue.doubleValue(), 0.000001); }
### Question: GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback) { this.discardCallback = discardCallback; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }### Answer: @Test void addDiscardCallback() { GcsAcceptModifiedAfterFileListFilter filter = new GcsAcceptModifiedAfterFileListFilter(); AtomicBoolean callbackTriggered = new AtomicBoolean(false); filter.addDiscardCallback(blobInfo -> callbackTriggered.set(true)); BlobInfo blobInfo = mock(BlobInfo.class); when(blobInfo.getUpdateTime()).thenReturn(1L); filter.accept(blobInfo); assertThat(callbackTriggered.get()) .isTrue(); }
### Question: GoogleConfigPropertySourceLocator implements PropertySourceLocator { public String getProjectId() { return this.projectId; } GoogleConfigPropertySourceLocator(GcpProjectIdProvider projectIdProvider, CredentialsProvider credentialsProvider, GcpConfigProperties gcpConfigProperties); @Override PropertySource<?> locate(Environment environment); String getProjectId(); }### Answer: @Test public void testProjectIdInConfigProperties() throws IOException { when(this.gcpConfigProperties.getProjectId()).thenReturn("pariah"); this.googleConfigPropertySourceLocator = new GoogleConfigPropertySourceLocator( this.projectIdProvider, this.credentialsProvider, this.gcpConfigProperties ); assertThat(this.googleConfigPropertySourceLocator.getProjectId()).isEqualTo("pariah"); }
### Question: GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public List<BlobInfo> filterFiles(BlobInfo[] blobInfos) { List<BlobInfo> list = new ArrayList<>(); for (BlobInfo file : blobInfos) { if (accept(file)) { list.add(file); } } return list; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }### Answer: @Test void filterFiles() { Instant now = Instant.now(); BlobInfo oldBlob = mock(BlobInfo.class); when(oldBlob.getUpdateTime()).thenReturn(now.toEpochMilli() - 1); BlobInfo currentBlob = mock(BlobInfo.class); when(currentBlob.getUpdateTime()).thenReturn(now.toEpochMilli()); BlobInfo newBlob = mock(BlobInfo.class); when(newBlob.getUpdateTime()).thenReturn(now.toEpochMilli() + 1); ArrayList<BlobInfo> expected = new ArrayList<>(); expected.add(currentBlob); expected.add(newBlob); assertThat( new GcsAcceptModifiedAfterFileListFilter(now).filterFiles(new BlobInfo[] { oldBlob, currentBlob, newBlob })) .isEqualTo(expected); }
### Question: GcsAcceptModifiedAfterFileListFilter implements DiscardAwareFileListFilter<BlobInfo> { @Override public boolean supportsSingleFileFiltering() { return true; } GcsAcceptModifiedAfterFileListFilter(); GcsAcceptModifiedAfterFileListFilter(Instant instant); @Override void addDiscardCallback(@Nullable Consumer<BlobInfo> discardCallback); @Override List<BlobInfo> filterFiles(BlobInfo[] blobInfos); @Override boolean accept(BlobInfo file); @Override boolean supportsSingleFileFiltering(); }### Answer: @Test void supportsSingleFileFiltering() { assertThat(new GcsAcceptModifiedAfterFileListFilter().supportsSingleFileFiltering()) .isTrue(); }
### Question: GcsPersistentAcceptOnceFileListFilter extends AbstractPersistentAcceptOnceFileListFilter<BlobInfo> { @Override protected long modified(BlobInfo blobInfo) { return (blobInfo != null && blobInfo.getUpdateTime() != null) ? blobInfo.getUpdateTime() : -1; } GcsPersistentAcceptOnceFileListFilter(ConcurrentMetadataStore store, String prefix); }### Answer: @Test public void modified_blobInfoIsNull_shouldReturnMinusOne() { assertThat(new GcsPersistentAcceptOnceFileListFilter(mock(ConcurrentMetadataStore.class), "").modified(null)) .isEqualTo(-1); } @Test public void modified_updateTimeIsNull_shouldReturnMinusOne() { BlobInfo blobInfo = mock(BlobInfo.class); when(blobInfo.getUpdateTime()).thenReturn(null); assertThat( new GcsPersistentAcceptOnceFileListFilter(mock(ConcurrentMetadataStore.class), "").modified(blobInfo)) .isEqualTo(-1); }
### Question: SliceUtil { public static <T> void sliceAndExecute(T[] elements, int sliceSize, Consumer<T[]> consumer) { int num_slices = (int) (Math.ceil((double) elements.length / sliceSize)); for (int i = 0; i < num_slices; i++) { int start = i * sliceSize; int end = Math.min(start + sliceSize, elements.length); T[] slice = Arrays.copyOfRange(elements, start, end); consumer.accept(slice); } } private SliceUtil(); static void sliceAndExecute(T[] elements, int sliceSize, Consumer<T[]> consumer); }### Answer: @Test public void sliceAndExecuteTest() { Integer[] elements = getIntegers(7); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).containsExactly(new Integer[] { 0, 1, 2 }, new Integer[] { 3, 4, 5 }, new Integer[] { 6 }); } @Test public void sliceAndExecuteEvenTest() { Integer[] elements = getIntegers(6); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).containsExactly(new Integer[] { 0, 1, 2 }, new Integer[] { 3, 4, 5 }); } @Test public void sliceAndExecuteEmptyTest() { Integer[] elements = getIntegers(0); List<Integer[]> slices = new ArrayList<>(); sliceAndExecute(elements, 3, slice -> { slices.add(slice); }); assertThat(slices).isEmpty(); }
### Question: KeyUtil { public static Key getKeyWithoutAncestors(Key entityKey) { Key.Builder ancestorLookupKey; if (entityKey.hasName()) { ancestorLookupKey = Key.newBuilder(entityKey.getProjectId(), entityKey.getKind(), entityKey.getName()); } else { ancestorLookupKey = Key.newBuilder(entityKey.getProjectId(), entityKey.getKind(), entityKey.getId()); } ancestorLookupKey.setNamespace(entityKey.getNamespace()); return ancestorLookupKey.build(); } private KeyUtil(); static Key getKeyWithoutAncestors(Key entityKey); }### Answer: @Test public void testRemoveAncestors_NamedKeys() { Key namedKey = Key.newBuilder("project", "person", "Smith") .addAncestor(PathElement.of("person", "GrandParent")) .addAncestor(PathElement.of("person", "Parent")) .build(); Key processedKey = KeyUtil.getKeyWithoutAncestors(namedKey); assertThat(processedKey.getAncestors()).isEmpty(); } @Test public void testRemoveAncestors_IdKeys() { Key idKey = Key.newBuilder("project", "person", 46L) .addAncestor(PathElement.of("person", 22L)) .addAncestor(PathElement.of("person", 18L)) .build(); Key processedKey = KeyUtil.getKeyWithoutAncestors(idKey); assertThat(processedKey.getAncestors()).isEmpty(); }
### Question: EnvironmentHelper { public static boolean isPresent(String variable) { return getIfPresent(variable) != null; } private EnvironmentHelper(); static boolean isPresent(String variable); static String get(String variable); static String getOrDefault(String variable, String defaultValue); }### Answer: @Test void testIsPresentOnRandomString() { String random = UUID.randomUUID().toString(); assertWithMessage("Should not have an environment variable with randomized key") .that(EnvironmentHelper.isPresent(random)).isFalse(); } @Test void testIsPresentOnAdded() { String someKey = UUID.randomUUID().toString(); String value = "nothing important"; System.setProperty(someKey, value); assertWithMessage("%s should be set to %s", someKey, value) .that(EnvironmentHelper.isPresent(someKey)).isTrue(); } @Test void testIsPresentButEmpty() { String someKey = UUID.randomUUID().toString(); String value = ""; System.setProperty(someKey, value); assertWithMessage("%s should be set to %s", someKey, value) .that(EnvironmentHelper.isPresent(someKey)).isFalse(); } @Test void testLogEntryForIsPresentFailureIsEmpty() { String someKey = UUID.randomUUID().toString(); String value = ""; System.setProperty(someKey, value); String message = String.format(EnvironmentHelper.NOT_FOUND, someKey); EnvironmentHelper.isPresent(someKey); assertThat(getLogs()).doesNotContain(message); }
### Question: MeasuredInputStreamSupplier implements Supplier<InputStream> { public int size() { return size; } private MeasuredInputStreamSupplier(InputStream source); static MeasuredInputStreamSupplier terminallyTransformInputStream(InputStream source); @Override InputStream get(); int size(); }### Answer: @Test void testSize() { InputStream use = stream("mock"); Truth.assertThat(MeasuredInputStreamSupplier.terminallyTransformInputStream(use).size()).isEqualTo("mock".length()); }
### Question: RestApiApplication { public static void main(String... args) { SpringApplication.run(RestApiApplication.class, args); } static void main(String... args); }### Answer: @Test void testMain() { RestApiApplication.main(); }
### Question: CommandLineRunner implements Runnable { protected Pattern getNormalPathPattern() { if (normalPathPattern == null) { String separator = "\\" + this.fileSystem.getSeparator(); normalPathPattern = Pattern.compile("[a-zA-Z0-9_\\-\\s,." + separator + "]+"); } return normalPathPattern; } CommandLineRunner(CommandLine commandLine); CommandLineRunner(CommandLine commandLine, FileSystem fileSystem); @Override void run(); static boolean isValid(Path path); }### Answer: @Test void testWindowsFileSeparator() { FileSystem mockWindowsFileSystem = mock(FileSystem.class); when(mockWindowsFileSystem.getSeparator()).thenReturn("\\"); CommandLineRunner runner = new CommandLineRunner(line(WINDOWS_FILE), mockWindowsFileSystem); Truth.assertThat(runner.getNormalPathPattern().pattern()).contains("\\\\"); } @Test void testNixFileSeparator() { FileSystem mockWindowsFileSystem = mock(FileSystem.class); when(mockWindowsFileSystem.getSeparator()).thenReturn("/"); CommandLineRunner runner = new CommandLineRunner(line(VALID_FILE), mockWindowsFileSystem); Truth.assertThat(runner.getNormalPathPattern().pattern()).contains("\\/"); }
### Question: CommandLineRunner implements Runnable { protected Pattern getGlobFinderPattern() { if (globFinderPattern == null) { globFinderPattern = Pattern.compile("(" + getNormalPathPattern().pattern() + ").+"); } return globFinderPattern; } CommandLineRunner(CommandLine commandLine); CommandLineRunner(CommandLine commandLine, FileSystem fileSystem); @Override void run(); static boolean isValid(Path path); }### Answer: @Test void testGlobPattern() { FileSystem mockWindowsFileSystem = mock(FileSystem.class); String mockSeparator = ":"; when(mockWindowsFileSystem.getSeparator()).thenReturn(mockSeparator); CommandLineRunner runner = new CommandLineRunner(line(VALID_FILE), mockWindowsFileSystem); Truth.assertThat(runner.getGlobFinderPattern().pattern()).contains(mockSeparator); }
### Question: CommandLineRunner implements Runnable { public static boolean isValid(Path path) { return Files.isRegularFile(path) && Files.isReadable(path); } CommandLineRunner(CommandLine commandLine); CommandLineRunner(CommandLine commandLine, FileSystem fileSystem); @Override void run(); static boolean isValid(Path path); }### Answer: @Test void testValidPath_valid() { Path path = Paths.get(VALID_FILE); boolean valid = CommandLineRunner.isValid(path); Truth.assertThat(valid).isTrue(); } @Test void testValidPath_invalid() { Path path = Paths.get(INVALID_FILE); boolean invalid = CommandLineRunner.isValid(path); Truth.assertThat(invalid).isFalse(); }
### Question: MeasuredInputStreamSupplier implements Supplier<InputStream> { public static MeasuredInputStreamSupplier terminallyTransformInputStream(InputStream source) { Objects.requireNonNull(source, "source"); return new MeasuredInputStreamSupplier(source); } private MeasuredInputStreamSupplier(InputStream source); static MeasuredInputStreamSupplier terminallyTransformInputStream(InputStream source); @Override InputStream get(); int size(); }### Answer: @Test void testGetInputStreamReturnsUnique() { InputStream use = stream("mock"); MeasuredInputStreamSupplier objectToTest = MeasuredInputStreamSupplier.terminallyTransformInputStream(use); int expected = 5; long count = Stream.generate(objectToTest::get).limit(expected).distinct().count(); Truth.assertThat(count).isEqualTo(expected); } @Test void testTerminallyTransformInputStreamIsTerminal() throws IOException { InputStream use = stream("mock"); MeasuredInputStreamSupplier.terminallyTransformInputStream(use); Truth.assertThat(use.available()).isEqualTo(0); }
### Question: CommandLineMain { static CommandLine cli(String... arguments) { try { return new DefaultParser().parse(OPTIONS, arguments); } catch (ParseException exception) { DEV_LOG.error("Problem parsing cli options, {}", exception.getMessage()); return null; } } static void main(String... arguments); static final String BYGONE; static final String SKIP_VALIDATION; static final String RECURSIVE; static final String HELP; }### Answer: @Test void testCliInvalidOption() { CommandLine line = CommandLineMain.cli("-" + CommandLineMain.SKIP_VALIDATION + " -InvalidArgument"); Truth.assertThat(line).isNull(); Truth.assertThat(getLogs()).isNotEmpty(); }
### Question: CommandLineMain { public static void main(String... arguments) { CommandLine commandLine = cli(arguments); if (commandLine != null) { new CommandLineRunner(commandLine).run(); } } static void main(String... arguments); static final String BYGONE; static final String SKIP_VALIDATION; static final String RECURSIVE; static final String HELP; }### Answer: @Test void testMainInvalidCli() { CommandLineMain.main("-InvalidArgument"); Truth.assertThat(getLogs()).isNotEmpty(); } @Test void testMain() { CommandLineMain.main(); Truth.assertThat(getLogs()).isEmpty(); }
### Question: CpcFileServiceImpl implements CpcFileService { @Override public InputStreamResource getQppById(String fileId) { Metadata metadata = getMetadataById(fileId); return new InputStreamResource(storageService.getFileByLocationId(metadata.getQppLocator())); } CpcFileServiceImpl(DbService dbService, StorageService storageService); @Override List<UnprocessedCpcFileData> getUnprocessedCpcPlusFiles(String orgAttribute); @Override InputStreamResource getFileById(String fileId); @Override InputStreamResource getQppById(String fileId); @Override String processFileById(String fileId, String orgName); @Override String unprocessFileById(String fileId, String orgName); @Override Metadata getMetadataById(String fileId); static final String FILE_NOT_FOUND; }### Answer: @Test void testGetQppById() throws IOException { String key = "test"; when(dbService.getMetadataById(key)).thenReturn(buildFakeMetadata(true, false, false)); when(storageService.getFileByLocationId(key)).thenReturn(new ByteArrayInputStream("1337".getBytes())); InputStreamResource outcome = objectUnderTest.getQppById(key); verify(dbService, times(1)).getMetadataById(key); verify(storageService, times(1)).getFileByLocationId(key); assertThat(IOUtils.toString(outcome.getInputStream(), StandardCharsets.UTF_8)).isEqualTo("1337"); }
### Question: XmlUtils { public static Element stringToDom(String xml) { if (xml == null) { return null; } return parseXmlStream(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))); } private XmlUtils(); static Element stringToDom(String xml); static Element parseXmlStream(InputStream xmlStream); static String buildString(String... parts); }### Answer: @Test void stringToDomCanParse() throws Exception { Element dom = XmlUtils.stringToDom(xmlFragment); assertWithMessage("returned dom should not be null") .that(dom).isNotNull(); } @Test void stringToDomRootChild() throws Exception { Element dom = XmlUtils.stringToDom(xmlFragment); List<Element> childElement = dom.getChildren(); assertWithMessage("test root has one child") .that(childElement) .hasSize(1); } @Test void stringToDomOtherDescendants() throws Exception { Element dom = XmlUtils.stringToDom(xmlFragment); List<Element> childElement = dom.getChildren(); List<Element> leafElements = childElement.get(0).getChildren(); assertWithMessage("test observation has five children") .that(leafElements).hasSize(5); } @Test void stringToDom_null() throws Exception { Element dom = XmlUtils.stringToDom(null); assertWithMessage("returned dom should be null") .that(dom).isNull(); } @Test void stringToDom_emptyString() throws Exception { Assertions.assertThrows(XmlException.class, () -> XmlUtils.stringToDom("")); } @Test void stringToDom_invalidXML() throws Exception { Assertions.assertThrows(XmlException.class, () -> XmlUtils.stringToDom("invalid XML")); }
### Question: JsonHelper { public static <T> T readJsonAtJsonPath(InputStream jsonStream, String jsonPath, TypeRef<T> returnType) { return JsonPath.parse(jsonStream).read(jsonPath, returnType); } private JsonHelper(); static T readJson(String json, Class<T> valueType); static T readJson(Path filePath, Class<T> valueType); static T readJson(InputStream json, Class<T> valueType); static T readJson(InputStream json, TypeReference<T> valueType); static T readJson(Path filePath, TypeReference<T> valueType); static T readJsonAtJsonPath(InputStream jsonStream, String jsonPath, TypeRef<T> returnType); static T readJsonAtJsonPath(String json, String jsonPath, TypeRef<T> returnType); }### Answer: @Test void readJsonAtJsonPath() throws Exception { String measureDataFileName = "measures-data.json"; List<MeasureConfig> configurations; InputStream measuresInput = ClasspathHelper.contextClassLoader().getResourceAsStream(measureDataFileName); configurations = JsonHelper.readJsonAtJsonPath(measuresInput, "$", new TypeRef<List<MeasureConfig>>() { }); assertWithMessage("Expect to get a List of measureConfigs") .that(configurations).isNotEmpty(); }
### Question: JsonHelper { public static <T> T readJson(String json, Class<T> valueType) { T returnValue; try { returnValue = new ObjectMapper().readValue(json, valueType); } catch (IOException ex) { throw new JsonReadException(PROBLEM_PARSING_JSON, ex); } return returnValue; } private JsonHelper(); static T readJson(String json, Class<T> valueType); static T readJson(Path filePath, Class<T> valueType); static T readJson(InputStream json, Class<T> valueType); static T readJson(InputStream json, TypeReference<T> valueType); static T readJson(Path filePath, TypeReference<T> valueType); static T readJsonAtJsonPath(InputStream jsonStream, String jsonPath, TypeRef<T> returnType); static T readJsonAtJsonPath(String json, String jsonPath, TypeRef<T> returnType); }### Answer: @Test void exceptionForReadJsonInputStream() { String testJson = "{ \"DogCow\": [ }"; try { JsonHelper.readJson(new ByteArrayInputStream(testJson.getBytes()), Map.class); Assertions.fail("An exception should have been thrown."); } catch(JsonReadException exception) { assertWithMessage("Wrong exception reason.") .that(exception).hasMessageThat().isSameInstanceAs("Problem parsing json string"); } catch(Exception exception) { Assertions.fail("Incorrect exception was thrown."); } } @Test void exceptionForReadJsonString() { String testJson = "{ \"DogCow\": [ }"; try { JsonHelper.readJson(testJson, Map.class); Assertions.fail("An exception should have been thrown."); } catch(JsonReadException exception) { assertWithMessage("Wrong exception reason.") .that(exception).hasMessageThat().isSameInstanceAs("Problem parsing json string"); } catch(Exception exception) { Assertions.fail("Incorrect exception was thrown."); } }
### Question: CpcFileServiceImpl implements CpcFileService { @Override public InputStreamResource getFileById(String fileId) { Metadata metadata = getMetadataById(fileId); if (isAnUnprocessedCpcFile(metadata)) { return new InputStreamResource(storageService.getFileByLocationId(metadata.getSubmissionLocator())); } throw new NoFileInDatabaseException(FILE_NOT_FOUND); } CpcFileServiceImpl(DbService dbService, StorageService storageService); @Override List<UnprocessedCpcFileData> getUnprocessedCpcPlusFiles(String orgAttribute); @Override InputStreamResource getFileById(String fileId); @Override InputStreamResource getQppById(String fileId); @Override String processFileById(String fileId, String orgName); @Override String unprocessFileById(String fileId, String orgName); @Override Metadata getMetadataById(String fileId); static final String FILE_NOT_FOUND; }### Answer: @Test void testGetFileById() throws IOException { when(dbService.getMetadataById(anyString())).thenReturn(buildFakeMetadata(true, false, false)); when(storageService.getFileByLocationId("test")).thenReturn(new ByteArrayInputStream("1337".getBytes())); InputStreamResource outcome = objectUnderTest.getFileById("test"); verify(dbService, times(1)).getMetadataById(anyString()); verify(storageService, times(1)).getFileByLocationId(anyString()); assertThat(IOUtils.toString(outcome.getInputStream(), StandardCharsets.UTF_8)).isEqualTo("1337"); }
### Question: DuplicationCheckHelper { public static int calculateDuplications(Node node, String type) { List<String> valueCountList = node.getDuplicateValues(type); return (valueCountList != null) ? (valueCountList.size() + ACCOUNT_FOR_ORIGINAL_VALUE) : ACCOUNT_FOR_MISSING_VALUE; } private DuplicationCheckHelper(); static int calculateDuplications(Node node, String type); static final int ACCOUNT_FOR_ORIGINAL_VALUE; static final int ACCOUNT_FOR_MISSING_VALUE; }### Answer: @Test void testDuplicateCheckerWithNoDuplicateAggregateCounts() { Node node = new Node(TemplateId.PI_AGGREGATE_COUNT); node.putValue(AggregateCountDecoder.AGGREGATE_COUNT, "1234", false); int duplicationValue = DuplicationCheckHelper.calculateDuplications(node, AggregateCountDecoder.AGGREGATE_COUNT); assertThat(duplicationValue).isEqualTo(0); } @Test void testDuplicateCheckerWithDuplicateAggregateCounts() { Node node = new Node(TemplateId.PI_AGGREGATE_COUNT); node.putValue(AggregateCountDecoder.AGGREGATE_COUNT, "1234", false); node.putValue(AggregateCountDecoder.AGGREGATE_COUNT, "1234", false); int duplicationValue = DuplicationCheckHelper.calculateDuplications(node, AggregateCountDecoder.AGGREGATE_COUNT); assertThat(duplicationValue).isEqualTo(2); }
### Question: FormatHelper { public static LocalDate formattedDateParse(String date) { String parse = cleanString(date); parse = parse.replace("-", "").replace("/", ""); if (parse.length() > DATE_FORMAT.length()) { parse = parse.substring(0, DATE_FORMAT.length()); } return LocalDate.parse(cleanString(parse), DateTimeFormatter.ofPattern(DATE_FORMAT)); } private FormatHelper(); static LocalDate formattedDateParse(String date); static String cleanString(String value); }### Answer: @Test void testFormattedDateParseRemovesDashes() { LocalDate date = FormatHelper.formattedDateParse(VALID_DASH_DATE); assertThat(date).isEqualTo(DATE_COMPARED); } @Test void testFormattedDateParseRemovesSlashes() { LocalDate date = FormatHelper.formattedDateParse(VALID_SLASH_DATE); assertThat(date).isEqualTo(DATE_COMPARED); } @Test void testFormattedDateParseRemovesTimeAndZone() { LocalDate date = FormatHelper.formattedDateParse(VALID_TIMEZONED_DATE); assertThat(date).isEqualTo(DATE_COMPARED); }
### Question: MeasureConfigHelper { public static MeasureConfig getMeasureConfig(Node node) { String measureId = node.getValue(MEASURE_ID); return findMeasureConfigByUuid(measureId); } private MeasureConfigHelper(); static MeasureConfig getMeasureConfig(Node node); static String getMeasureConfigIdByUuidOrDefault(String uuid); static String getPrioritizedId(Node node); static List<Node> createSubPopulationGrouping(Node node, MeasureConfig measureConfig); static boolean checkMultiToSinglePerformanceRateId(String measureId); static void setMultiToSinglePerfRateMeasureId(Set<String> multiToSinglePerfRateMeasureIdSet); static final String MEASURE_ID; static final String NO_MEASURE; static final String SINGLE_TO_MULTIPLE_SUP_POPULATION; final static String SINGLE_TO_MULTI_PERF_RATE_MEASURE_ID; }### Answer: @Test void testGetMeasureConfigSuccess() { Node measureNode = new Node(TemplateId.MEASURE_REFERENCE_RESULTS_CMS_V4); measureNode.putValue(MeasureConfigHelper.MEASURE_ID, THE_UUID); MeasureConfig config = MeasureConfigHelper.getMeasureConfig(measureNode); assertThat(config).isNotNull(); }
### Question: StorageServiceImpl extends AnyOrderActionService<Supplier<PutObjectRequest>, String> implements StorageService { @Override public InputStream getFileByLocationId(String fileLocationId) { String bucketName = environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE); if (StringUtils.isEmpty(bucketName)) { API_LOG.warn("No bucket name is specified."); return null; } API_LOG.info("Retrieving file {} from bucket {}", fileLocationId, bucketName); GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, fileLocationId); S3Object s3Object = amazonS3.getObject(getObjectRequest); API_LOG.info("Successfully retrieved file {} from S3 bucket {}", getObjectRequest.getKey(), getObjectRequest.getBucketName()); return s3Object.getObjectContent(); } StorageServiceImpl(TaskExecutor taskExecutor, TransferManager s3TransferManager, Environment environment, AmazonS3 amazonS3); @Override CompletableFuture<String> store(String keyName, Supplier<InputStream> inStream, long size); @Override InputStream getFileByLocationId(String fileLocationId); @Override InputStream getCpcPlusValidationFile(); @Override InputStream getApmValidationFile(); }### Answer: @Test void noBucket() { Mockito.when(environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE)).thenReturn(null); InputStream inStream = underTest.getFileByLocationId("meep"); assertThat(inStream).isNull(); } @Test void envVariablesPresent() { S3Object s3ObjectMock = mock(S3Object.class); s3ObjectMock.setObjectContent(new ByteArrayInputStream("1234".getBytes())); Mockito.when(amazonS3Client.getObject(any(GetObjectRequest.class))).thenReturn(s3ObjectMock); Mockito.when(environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE)).thenReturn("meep"); underTest.getFileByLocationId("meep"); verify(s3ObjectMock, times(1)).getObjectContent(); }
### Question: ReportingParametersActEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { encodeDate(wrapper, node, PERFORMANCE_START); encodeDate(wrapper, node, PERFORMANCE_END); } ReportingParametersActEncoder(Context context); static final String PERFORMANCE_START; static final String PERFORMANCE_END; }### Answer: @Test void internalEncode() throws Exception { Node reportingParametersActNode = new Node(TemplateId.REPORTING_PARAMETERS_ACT); reportingParametersActNode.putValue(ReportingParametersActEncoder.PERFORMANCE_START,"20170101"); reportingParametersActNode.putValue(ReportingParametersActEncoder.PERFORMANCE_END,"20171231"); JsonWrapper outputWrapper = new JsonWrapper(); ReportingParametersActEncoder encoder = new ReportingParametersActEncoder(new Context()); encoder.internalEncode(outputWrapper, reportingParametersActNode); String performanceStart = outputWrapper.getString(ReportingParametersActEncoder.PERFORMANCE_START); String performanceEnd = outputWrapper.getString(ReportingParametersActEncoder.PERFORMANCE_END); assertThat(performanceStart).isEqualTo("2017-01-01"); assertThat(performanceEnd).isEqualTo("2017-12-31"); } @Test void missingValuesTest() throws Exception { Node reportingParametersActNode = new Node(TemplateId.REPORTING_PARAMETERS_ACT); JsonWrapper outputWrapper = new JsonWrapper(); ReportingParametersActEncoder encoder = new ReportingParametersActEncoder(new Context()); encoder.internalEncode(outputWrapper, reportingParametersActNode); String performanceStart = outputWrapper.getString(ReportingParametersActEncoder.PERFORMANCE_START); String performanceEnd = outputWrapper.getString(ReportingParametersActEncoder.PERFORMANCE_END); assertThat(performanceStart).isNull(); assertThat(performanceEnd).isNull(); }
### Question: StorageServiceImpl extends AnyOrderActionService<Supplier<PutObjectRequest>, String> implements StorageService { @Override public InputStream getApmValidationFile() { String bucketName = environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE); if (StringUtils.isEmpty(bucketName)) { API_LOG.warn("No bucket name and/or key specified"); return null; } API_LOG.info("Retrieving APM validation file from bucket {}", bucketName); GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, Constants.APM_FILE_NAME_KEY); S3Object s3Object = amazonS3.getObject(getObjectRequest); return s3Object.getObjectContent(); } StorageServiceImpl(TaskExecutor taskExecutor, TransferManager s3TransferManager, Environment environment, AmazonS3 amazonS3); @Override CompletableFuture<String> store(String keyName, Supplier<InputStream> inStream, long size); @Override InputStream getFileByLocationId(String fileLocationId); @Override InputStream getCpcPlusValidationFile(); @Override InputStream getApmValidationFile(); }### Answer: @Test void test_getApmValidationFile() { S3ObjectInputStream expected = new S3ObjectInputStream(null, null); S3Object mockS3Obj = mock(S3Object.class); Mockito.when(mockS3Obj.getObjectContent()).thenReturn(expected); Mockito.when(environment.getProperty(Constants.BUCKET_NAME_ENV_VARIABLE)).thenReturn("Mock_Bucket"); Mockito.when(amazonS3Client.getObject( any(GetObjectRequest.class) )).thenReturn(mockS3Obj); InputStream actual = underTest.getApmValidationFile(); assertThat(actual).isEqualTo(expected); }
### Question: EnvironmentHelper { public static String get(String variable) { String value = getIfPresent(variable); if (value == null) { LOG.warn( String.format(NOT_FOUND, variable)); } return value; } private EnvironmentHelper(); static boolean isPresent(String variable); static String get(String variable); static String getOrDefault(String variable, String defaultValue); }### Answer: @Test void testLogEntryForFailures() { String random = UUID.randomUUID().toString(); String message = String.format(EnvironmentHelper.NOT_FOUND, random); EnvironmentHelper.get(random); assertThat(getLogs()).contains(message); }
### Question: PiProportionNumeratorEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { Node piNumeratorNode = node.findFirstNode(TemplateId.PI_AGGREGATE_COUNT); if (piNumeratorNode != null) { JsonWrapper numerator = encodeChild(piNumeratorNode); if (null != numerator.getInteger(VALUE)) { wrapper.put(ENCODE_LABEL, numerator.getInteger(VALUE)); wrapper.mergeMetadata(numerator, ENCODE_LABEL); } } } PiProportionNumeratorEncoder(Context context); }### Answer: @Test void testInternalEncode() throws EncodeException { PiProportionNumeratorEncoder piProportionNumeratorEncoder = new PiProportionNumeratorEncoder(new Context()); piProportionNumeratorEncoder.internalEncode(jsonWrapper, piProportionNumeratorNode); assertThat(jsonWrapper.getInteger("numerator")) .isEqualTo(600); } @Test void testEncoderWithoutChild() throws EncodeException { piProportionNumeratorNode.getChildNodes().remove(numeratorDenominatorValueNode); PiProportionNumeratorEncoder piProportionNumeratorEncoder = new PiProportionNumeratorEncoder(new Context()); piProportionNumeratorEncoder.internalEncode(jsonWrapper, piProportionNumeratorNode); assertThat(jsonWrapper.getInteger("numerator")) .isNull(); } @Test void testEncoderWithoutValue() throws EncodeException { numeratorDenominatorValueNode.putValue("aggregateCount", null); PiProportionNumeratorEncoder piProportionNumeratorEncoder = new PiProportionNumeratorEncoder(new Context()); piProportionNumeratorEncoder.internalEncode(jsonWrapper, piProportionNumeratorNode); assertThat(jsonWrapper.getInteger("numerator")) .isNull(); }
### Question: PiNumeratorDenominatorEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { Map<TemplateId, Node> childMapByTemplateId = node.getChildNodes().stream().collect( Collectors.toMap(Node::getType, Function.identity(), (v1, v2) -> v1, LinkedHashMap::new)); JsonWrapper childWrapper = encodeChildren(childMapByTemplateId); wrapper.put("measureId", node.getValue("measureId")); wrapper.put(VALUE, childWrapper); } PiNumeratorDenominatorEncoder(Context context); }### Answer: @Test void testInternalEncode() throws EncodeException { JsonWrapper jsonWrapper = new JsonWrapper(); PiNumeratorDenominatorEncoder objectUnderTest = new PiNumeratorDenominatorEncoder(new Context()); objectUnderTest.internalEncode(jsonWrapper, piProportionMeasureNode); assertThat(jsonWrapper.getString("measureId")) .isEqualTo(MEASURE_ID); assertThat(jsonWrapper.toObject()) .isNotNull(); assertThat(jsonWrapper.toObject()) .isInstanceOf(Map.class); assertThat(((Map<?, ?>)jsonWrapper.toObject()).get("value")) .isNotNull(); } @Test void testNoChildEncoder() throws EncodeException { JsonWrapper jsonWrapper = new JsonWrapper(); PiNumeratorDenominatorEncoder objectUnderTest = new PiNumeratorDenominatorEncoder(new Context()); Node unknownNode = new Node(); piProportionMeasureNode.addChildNode(unknownNode); objectUnderTest.internalEncode(jsonWrapper, piProportionMeasureNode); assertThat(objectUnderTest.getErrors()) .hasSize(1); assertWithMessage("The validation error must be the inability to find an encoder") .that(objectUnderTest.getErrors().get(0).getMessage()) .isEqualTo(ProblemCode.CT_LABEL + "Failed to find an encoder"); }
### Question: MeasurePerformedEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { wrapper.putBoolean(VALUE, node.getValue("measurePerformed")); } MeasurePerformedEncoder(Context context); }### Answer: @Test void testMeasurePerformedEncodesIntoWrapper() throws EncodeException { Node measurePerformedNode = new Node(TemplateId.MEASURE_PERFORMED); measurePerformedNode.putValue("measurePerformed", "Y"); JsonWrapper jsonWrapper = new JsonWrapper(); QppOutputEncoder qppOutputEncoder = new QppOutputEncoder(new Context()); qppOutputEncoder.internalEncode(jsonWrapper, measurePerformedNode); assertThat(jsonWrapper.getBoolean("value")).isTrue(); }
### Question: DefaultEncoder extends JsonOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { DEV_LOG.debug("Default JSON encoder {} is handling templateId {} and is described as '{}' ", getClass(), node.getType().name(), description); JsonWrapper childWrapper = new JsonWrapper(); for (Node child : node.getChildNodes()) { encode(childWrapper, child); } for (String name : node.getKeys()) { String nameForEncode = name.replace("Decoder", "Encoder"); childWrapper.put(nameForEncode, node.getValue(name)); } wrapper.put(node.getType().name(), childWrapper); } DefaultEncoder(String description); }### Answer: @Test void encodeDefaultNode() throws EncodeException { Node root = new Node(TemplateId.DEFAULT); Node placeHolder = new Node(TemplateId.PLACEHOLDER, root); root.addChildNode(placeHolder); JsonWrapper wrapper = new JsonWrapper(); new DefaultEncoder("Default Encode test").internalEncode(wrapper, root); assertThat(wrapper.toString()).hasLength(3); } @Test void encodeNodes() throws EncodeException { Node root = new Node(TemplateId.DEFAULT); Node placeHolder = new Node(TemplateId.PLACEHOLDER, root); root.addChildNode(placeHolder); placeHolder.putValue("name1", "value1"); Node qed = new Node(TemplateId.QED, root); root.addChildNode(qed); qed.putValue("name2", "value2"); JsonWrapper wrapper = new JsonWrapper(); new DefaultEncoder("Default Encode test").internalEncode(wrapper, root); String json = wrapper.toString(); String acutal = json.replaceAll("\\s", ""); String expect = "{\"DEFAULT\":{\"PLACEHOLDER\":{\"name1\":\"value1\"},\"QED\":{\"name2\":\"value2\"}}}"; assertThat(acutal).isEqualTo(expect); }
### Question: DbServiceImpl extends AnyOrderActionService<Metadata, Metadata> implements DbService { public Metadata getMetadataById(String uuid) { if (mapper.isPresent()) { API_LOG.info("Read item {} from DynamoDB", uuid); return mapper.get().load(Metadata.class, uuid); } else { API_LOG.warn("Skipping reading of item from DynamoDB with UUID {} because the dynamodb mapper is absent", uuid); return null; } } DbServiceImpl(TaskExecutor taskExecutor, Optional<DynamoDBMapper> mapper, Environment environment); @Override CompletableFuture<Metadata> write(Metadata meta); List<Metadata> getUnprocessedCpcPlusMetaData(String orgAttribute); Metadata getMetadataById(String uuid); }### Answer: @Test void testGetMetadataByIdWithMissingDynamoDbMapper() { underTest = new DbServiceImpl(taskExecutor, Optional.empty(), environment); assertThat(underTest.getMetadataById(null)).isNull(); } @Test void testGetMetadataById() { String fakeUuid = "1337-f4ke-uuid"; when(dbMapper.load(eq(Metadata.class), anyString())).thenReturn(Metadata.create()); Metadata fakeMetadata = underTest.getMetadataById(fakeUuid); verify(dbMapper, times(1)).load(eq(Metadata.class), anyString()); assertThat(fakeMetadata).isNotNull(); }
### Question: PlaceholderEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { for (Node child : node.getChildNodes()) { JsonOutputEncoder encoder = encoders.get(child.getType()); if (encoder != null) { encoder.encode(wrapper, child); } else { addValidationError(Detail.forProblemAndNode(ProblemCode.ENCODER_MISSING, child)); } } } PlaceholderEncoder(Context context); }### Answer: @Test void encodePlaceholderNodeNegative() throws EncodeException { Node placeHolder = new Node(TemplateId.PLACEHOLDER); placeHolder.addChildNode(new Node()); JsonWrapper wrapper = new JsonWrapper(); PlaceholderEncoder encoder = new PlaceholderEncoder(new Context()); encoder.internalEncode(wrapper, placeHolder); assertThat(encoder.getErrors()).hasSize(1); }
### Question: AggregateCountEncoder extends QppOutputEncoder { @Override protected void internalEncode(JsonWrapper wrapper, Node node) { wrapper.putInteger(VALUE, node.getValue(AggregateCountDecoder.AGGREGATE_COUNT)); } AggregateCountEncoder(Context context); }### Answer: @Test void testEncoder() { AggregateCountEncoder encoder = new AggregateCountEncoder(new Context()); encoder.setNodes(nodes); JsonWrapper json = new JsonWrapper(); try { encoder.internalEncode(json, numeratorDenominatorNode); } catch (EncodeException e) { Assertions.fail("Failure to encode: " + e.getMessage()); } assertThat(json.getInteger("value")) .isEqualTo(600); }
### Question: EncodeException extends RuntimeException { public String getTemplateId() { return templateId; } EncodeException(String message); EncodeException(String message, Exception cause); EncodeException(String message, String templateId); EncodeException(String message, Exception cause, String templateId); String getTemplateId(); }### Answer: @Test void getTemplateId() throws Exception { EncodeException e = new EncodeException("ErrorMessage", "templateId"); String value = e.getTemplateId(); assertThat(value) .isEqualTo("templateId"); }
### Question: Context { public boolean isDoValidation() { return doValidation; } Context(); Context(ApmEntityIds apmEntityIds); Program getProgram(); void setProgram(Program program); boolean isHistorical(); void setHistorical(boolean historical); boolean isDoValidation(); void setDoValidation(boolean doValidation); PiiValidator getPiiValidator(); void setPiiValidator(PiiValidator piiValidator); ApmEntityIds getApmEntityIds(); void setApmEntityIds(final ApmEntityIds apmEntityIds); @SuppressWarnings("unchecked") Registry<R> getRegistry(Class<A> annotation); static final String REPORTING_YEAR; }### Answer: @Test void testDoesValidationByDefault() { assertThat(new Context().isDoValidation()).isTrue(); }
### Question: Context { public boolean isHistorical() { return historical; } Context(); Context(ApmEntityIds apmEntityIds); Program getProgram(); void setProgram(Program program); boolean isHistorical(); void setHistorical(boolean historical); boolean isDoValidation(); void setDoValidation(boolean doValidation); PiiValidator getPiiValidator(); void setPiiValidator(PiiValidator piiValidator); ApmEntityIds getApmEntityIds(); void setApmEntityIds(final ApmEntityIds apmEntityIds); @SuppressWarnings("unchecked") Registry<R> getRegistry(Class<A> annotation); static final String REPORTING_YEAR; }### Answer: @Test void testIsNotHistoricalByDefault() { assertThat(new Context().isHistorical()).isFalse(); }
### Question: Context { public Program getProgram() { return program; } Context(); Context(ApmEntityIds apmEntityIds); Program getProgram(); void setProgram(Program program); boolean isHistorical(); void setHistorical(boolean historical); boolean isDoValidation(); void setDoValidation(boolean doValidation); PiiValidator getPiiValidator(); void setPiiValidator(PiiValidator piiValidator); ApmEntityIds getApmEntityIds(); void setApmEntityIds(final ApmEntityIds apmEntityIds); @SuppressWarnings("unchecked") Registry<R> getRegistry(Class<A> annotation); static final String REPORTING_YEAR; }### Answer: @Test void testProgramIsAllByDefault() { assertThat(new Context().getProgram()) .isSameInstanceAs(Program.ALL); }
### Question: Context { @SuppressWarnings("unchecked") public <A extends Annotation, R> Registry<R> getRegistry(Class<A> annotation) { return (Registry<R>) registries.computeIfAbsent(annotation, key -> new Registry<>(this, key)); } Context(); Context(ApmEntityIds apmEntityIds); Program getProgram(); void setProgram(Program program); boolean isHistorical(); void setHistorical(boolean historical); boolean isDoValidation(); void setDoValidation(boolean doValidation); PiiValidator getPiiValidator(); void setPiiValidator(PiiValidator piiValidator); ApmEntityIds getApmEntityIds(); void setApmEntityIds(final ApmEntityIds apmEntityIds); @SuppressWarnings("unchecked") Registry<R> getRegistry(Class<A> annotation); static final String REPORTING_YEAR; }### Answer: @Test void testGetRegistryReturnsValid() { assertThat(new Context().getRegistry(Decoder.class)).isNotNull(); } @Test void testGetRegistryIdentity() { Context context = new Context(); assertThat(context.getRegistry(Decoder.class)) .isSameInstanceAs(context.getRegistry(Decoder.class)); }
### Question: ApmEntityIds { public boolean idExists(String apmEntityId) { return validApmEntityIds.contains(apmEntityId); } ApmEntityIds(InputStream fileStream); ApmEntityIds(String fileName); ApmEntityIds(); boolean idExists(String apmEntityId); static final String DEFAULT_APM_ENTITY_FILE_NAME; }### Answer: @Test void testIdExists() { assertThat(apmEntityIds.idExists(APM_ID_THAT_EXISTS)).isTrue(); } @Test void testIdDoesNotExistDueToCapitalization() { assertThat(apmEntityIds.idExists(APM_ID_THAT_EXISTS.toUpperCase(Locale.ENGLISH))).isFalse(); } @Test void testIdDoesNotExists() { assertThat(apmEntityIds.idExists("PropertyTaxes")).isFalse(); }
### Question: Node { public boolean isNotValidated() { return !isValidated(); } Node(); Node(TemplateId type, Node parent); Node(TemplateId templateId); String getValue(String name); String getValueOrDefault(String name, String defaultValue); List<String> getDuplicateValues(String name); void putValue(String name, String value); void putValue(String name, String value, boolean replace); void removeValue(String name); boolean hasValue(String name); List<Node> getChildNodes(); Stream<Node> getChildNodes(TemplateId... templateIds); Stream<Node> getChildNodes(Predicate<Node> filter); Node findChildNode(Predicate<Node> filter); void setChildNodes(Node... childNodes); void addChildNodes(Node... childNodes); void addChildNode(Node childNode); boolean removeChildNode(Node childNode); Set<String> getKeys(); Node getParent(); void setParent(Node parent); void setType(TemplateId type); TemplateId getType(); void setLine(int line); int getLine(); void setColumn(int column); int getColumn(); String getOrComputePath(); Element getElementForLocation(); void setElementForLocation(Element elementForLocation); String getDefaultNsUri(); void setDefaultNsUri(String newDefaultNsUri); List<Node> findNode(TemplateId templateId); Node findFirstNode(TemplateId templateId); void setValidated(boolean validated); boolean isNotValidated(); Node findParentNodeWithHumanReadableTemplateId(); @Override String toString(); @Override final boolean equals(final Object o); @Override final int hashCode(); static final int DEFAULT_LOCATION_NUMBER; }### Answer: @Test void testNotValidatedMember() { Node node = new Node(); assertThat(node.isNotValidated()).isTrue(); }
### Question: Node { public List<Node> findNode(TemplateId templateId) { return findNode(templateId, null); } Node(); Node(TemplateId type, Node parent); Node(TemplateId templateId); String getValue(String name); String getValueOrDefault(String name, String defaultValue); List<String> getDuplicateValues(String name); void putValue(String name, String value); void putValue(String name, String value, boolean replace); void removeValue(String name); boolean hasValue(String name); List<Node> getChildNodes(); Stream<Node> getChildNodes(TemplateId... templateIds); Stream<Node> getChildNodes(Predicate<Node> filter); Node findChildNode(Predicate<Node> filter); void setChildNodes(Node... childNodes); void addChildNodes(Node... childNodes); void addChildNode(Node childNode); boolean removeChildNode(Node childNode); Set<String> getKeys(); Node getParent(); void setParent(Node parent); void setType(TemplateId type); TemplateId getType(); void setLine(int line); int getLine(); void setColumn(int column); int getColumn(); String getOrComputePath(); Element getElementForLocation(); void setElementForLocation(Element elementForLocation); String getDefaultNsUri(); void setDefaultNsUri(String newDefaultNsUri); List<Node> findNode(TemplateId templateId); Node findFirstNode(TemplateId templateId); void setValidated(boolean validated); boolean isNotValidated(); Node findParentNodeWithHumanReadableTemplateId(); @Override String toString(); @Override final boolean equals(final Object o); @Override final int hashCode(); static final int DEFAULT_LOCATION_NUMBER; }### Answer: @Test void testFindNode() { Node parent = new Node(); Node childOne = new Node(); Node childTwo = new Node(); Node childThree = new Node(TemplateId.PLACEHOLDER); parent.addChildNodes(childOne, childTwo, childThree); List<Node> results = parent.findNode(TemplateId.PLACEHOLDER); assertWithMessage("should find first child that has the searched id") .that(results).hasSize(1); }
### Question: Node { public void removeValue(String name) { data.remove(name); } Node(); Node(TemplateId type, Node parent); Node(TemplateId templateId); String getValue(String name); String getValueOrDefault(String name, String defaultValue); List<String> getDuplicateValues(String name); void putValue(String name, String value); void putValue(String name, String value, boolean replace); void removeValue(String name); boolean hasValue(String name); List<Node> getChildNodes(); Stream<Node> getChildNodes(TemplateId... templateIds); Stream<Node> getChildNodes(Predicate<Node> filter); Node findChildNode(Predicate<Node> filter); void setChildNodes(Node... childNodes); void addChildNodes(Node... childNodes); void addChildNode(Node childNode); boolean removeChildNode(Node childNode); Set<String> getKeys(); Node getParent(); void setParent(Node parent); void setType(TemplateId type); TemplateId getType(); void setLine(int line); int getLine(); void setColumn(int column); int getColumn(); String getOrComputePath(); Element getElementForLocation(); void setElementForLocation(Element elementForLocation); String getDefaultNsUri(); void setDefaultNsUri(String newDefaultNsUri); List<Node> findNode(TemplateId templateId); Node findFirstNode(TemplateId templateId); void setValidated(boolean validated); boolean isNotValidated(); Node findParentNodeWithHumanReadableTemplateId(); @Override String toString(); @Override final boolean equals(final Object o); @Override final int hashCode(); static final int DEFAULT_LOCATION_NUMBER; }### Answer: @Test void testRemoveValue() { Node node = new Node(); node.putValue("test", "hello"); node.removeValue("test"); assertThat(node.hasValue("test")).isFalse(); }
### Question: Node { public boolean removeChildNode(Node childNode) { return this.childNodes.remove(childNode); } Node(); Node(TemplateId type, Node parent); Node(TemplateId templateId); String getValue(String name); String getValueOrDefault(String name, String defaultValue); List<String> getDuplicateValues(String name); void putValue(String name, String value); void putValue(String name, String value, boolean replace); void removeValue(String name); boolean hasValue(String name); List<Node> getChildNodes(); Stream<Node> getChildNodes(TemplateId... templateIds); Stream<Node> getChildNodes(Predicate<Node> filter); Node findChildNode(Predicate<Node> filter); void setChildNodes(Node... childNodes); void addChildNodes(Node... childNodes); void addChildNode(Node childNode); boolean removeChildNode(Node childNode); Set<String> getKeys(); Node getParent(); void setParent(Node parent); void setType(TemplateId type); TemplateId getType(); void setLine(int line); int getLine(); void setColumn(int column); int getColumn(); String getOrComputePath(); Element getElementForLocation(); void setElementForLocation(Element elementForLocation); String getDefaultNsUri(); void setDefaultNsUri(String newDefaultNsUri); List<Node> findNode(TemplateId templateId); Node findFirstNode(TemplateId templateId); void setValidated(boolean validated); boolean isNotValidated(); Node findParentNodeWithHumanReadableTemplateId(); @Override String toString(); @Override final boolean equals(final Object o); @Override final int hashCode(); static final int DEFAULT_LOCATION_NUMBER; }### Answer: @Test void testRemoveChildNodeNull() { Node node = new Node(); assertThat(node.removeChildNode(null)).isFalse(); } @Test void testRemoveChildNodeSelf() { Node node = new Node(); assertThat(node.removeChildNode(node)).isFalse(); }
### Question: Error implements Serializable { @JsonProperty("details") public List<Detail> getDetails() { return details; } Error(); Error(String sourceIdentifier, List<Detail> details); String getSourceIdentifier(); void setSourceIdentifier(final String sourceIdentifier); String getType(); void setType(final String type); String getMessage(); void setMessage(final String message); @JsonProperty("details") List<Detail> getDetails(); @JsonProperty("details") void setDetails(final List<Detail> details); void addValidationError(final Detail detail); @Override String toString(); }### Answer: @Test void testValidationErrorInit() { Error objectUnderTest = new Error(); assertWithMessage("The validation errors should have been empty at first") .that(objectUnderTest.getDetails()).isEmpty(); }
### Question: Error implements Serializable { public void addValidationError(final Detail detail) { if (null == details) { details = new ArrayList<>(); } details.add(detail); } Error(); Error(String sourceIdentifier, List<Detail> details); String getSourceIdentifier(); void setSourceIdentifier(final String sourceIdentifier); String getType(); void setType(final String type); String getMessage(); void setMessage(final String message); @JsonProperty("details") List<Detail> getDetails(); @JsonProperty("details") void setDetails(final List<Detail> details); void addValidationError(final Detail detail); @Override String toString(); }### Answer: @Test void testAddValidationError() { Error objectUnderTest = new Error(); objectUnderTest.addValidationError(new Detail()); objectUnderTest.addValidationError(new Detail()); assertWithMessage("The list should have two items") .that(objectUnderTest.getDetails()).hasSize(2); }
### Question: Error implements Serializable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("sourceIdentifier", sourceIdentifier) .add("type", type) .add("message", message) .add("details", details) .toString(); } Error(); Error(String sourceIdentifier, List<Detail> details); String getSourceIdentifier(); void setSourceIdentifier(final String sourceIdentifier); String getType(); void setType(final String type); String getMessage(); void setMessage(final String message); @JsonProperty("details") List<Detail> getDetails(); @JsonProperty("details") void setDetails(final List<Detail> details); void addValidationError(final Detail detail); @Override String toString(); }### Answer: @Test void testToString() { Error objectUnderTest = new Error(); objectUnderTest.setSourceIdentifier("sourceID"); objectUnderTest.setDetails(Collections.singletonList(Detail.forProblemCode(ProblemCode.UNEXPECTED_ERROR))); objectUnderTest.setType("aType"); objectUnderTest.setMessage("coolMessage"); StringSubject subject = assertWithMessage("Must contain formatted string") .that(objectUnderTest.toString()); subject.contains(String.valueOf(objectUnderTest.getSourceIdentifier())); subject.contains(String.valueOf(objectUnderTest.getDetails())); subject.contains(String.valueOf(objectUnderTest.getType())); subject.contains(String.valueOf(objectUnderTest.getMessage())); }
### Question: Detail implements Serializable { private static String computeLocation(Node node) { StringBuilder location = new StringBuilder(); Node importantParentNode = node.findParentNodeWithHumanReadableTemplateId(); if (importantParentNode != null) { String importantParentTitle = importantParentNode.getType().getHumanReadableTitle(); String possibleMeasureId = importantParentNode.getValue("measureId"); location.append(importantParentTitle); if (!StringUtils.isEmpty(possibleMeasureId)) { location.append(" "); location.append(possibleMeasureId); String possibleElectronicMeasureId = MeasureConfigHelper.getMeasureConfigIdByUuidOrDefault(possibleMeasureId); if (!StringUtils.isEmpty(possibleElectronicMeasureId)) { location.append(" ("); location.append(possibleElectronicMeasureId); location.append(")"); } } } return location.toString(); } Detail(); Detail(Detail copy); static Detail forProblemAndNode(LocalizedProblem problem, Node node); static Detail forProblemCode(LocalizedProblem problem); Integer getErrorCode(); void setErrorCode(Integer errorCode); String getMessage(); void setMessage(String message); String getValue(); void setValue(String value); String getType(); void setType(String type); Location getLocation(); void setLocation(Location location); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test void testComputeLocation() { Node node = new Node(TemplateId.CLINICAL_DOCUMENT); Detail detail = Detail.forProblemAndNode(ProblemCode.UNEXPECTED_ERROR, node); assertThat(detail.getLocation().getLocation()).isEqualTo(node.getType().getHumanReadableTitle()); }
### Question: AllErrors implements Serializable { public List<Error> getErrors() { return errors; } AllErrors(); AllErrors(List<Error> errors); List<Error> getErrors(); void setErrors(final List<Error> errors); void addError(Error error); @Override String toString(); }### Answer: @Test void testErrorSourceInit() { AllErrors objectUnderTest = new AllErrors(); assertWithMessage("The error sources should have been null at first") .that(objectUnderTest.getErrors()) .isNull(); } @Test void testArgConstructor() { List<Error> errors = new ArrayList<>(); errors.add(new Error()); new AllErrors(errors); assertThat(new AllErrors(errors).getErrors()) .containsAtLeastElementsIn(errors); }
### Question: AllErrors implements Serializable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("errors", errors) .toString(); } AllErrors(); AllErrors(List<Error> errors); List<Error> getErrors(); void setErrors(final List<Error> errors); void addError(Error error); @Override String toString(); }### Answer: @Test void testToString() { AllErrors objectUnderTest = new AllErrors(); Error error = new Error(); objectUnderTest.addError(error); assertWithMessage("Must contain formatted string") .that(objectUnderTest.toString()).contains(error.toString()); }
### Question: Registry { public void register(ComponentKey registryKey, Class<? extends R> handler) { DEV_LOG.debug("Registering " + handler.getName() + " to '" + registryKey + "' for " + annotationClass.getSimpleName() + "."); if (registryMap.containsKey(registryKey)) { DEV_LOG.error("Duplicate registered handler for " + registryKey + " both " + registryMap.get(registryKey).getName() + " and " + handler.getName()); } registryMap.put(registryKey, handler); } Registry(Context context, Class<? extends Annotation> annotationClass); R get(TemplateId registryKey); Set<R> inclusiveGet(TemplateId registryKey); void register(ComponentKey registryKey, Class<? extends R> handler); int size(); }### Answer: @Test void testRegistryExistsByDefault() { try { registry.register(new ComponentKey(TemplateId.PLACEHOLDER, Program.ALL), Placeholder.class); } catch (NullPointerException e) { Assertions.fail("Registry should always exist."); } }
### Question: QrdaServiceImpl implements QrdaService { @Override public ConversionReport convertQrda3ToQpp(Source source) { Converter converter = initConverter(source); API_LOG.info("Performing QRDA3 to QPP conversion"); converter.transform(); return converter.getReport(); } QrdaServiceImpl(StorageService storageService); @PostConstruct void preloadMeasureConfigs(); @PostConstruct void loadCpcValidationData(); @PostConstruct void loadApmData(); @Override ConversionReport convertQrda3ToQpp(Source source); @Override InputStream retrieveCpcPlusValidationFile(); }### Answer: @Test void testConvertQrda3ToQppSuccess() { JsonWrapper qpp = objectUnderTest.convertQrda3ToQpp(MOCK_SUCCESS_QRDA_SOURCE).getEncodedWithMetadata(); assertThat(qpp.getString(KEY)).isSameInstanceAs(MOCK_SUCCESS_QPP_STRING); } @Test void testConvertQrda3ToQppError() { TransformException exception = assertThrows(TransformException.class, () -> objectUnderTest.convertQrda3ToQpp(MOCK_ERROR_QRDA_SOURCE)); AllErrors allErrors = exception.getDetails(); assertThat(allErrors.getErrors().get(0).getSourceIdentifier()).isSameInstanceAs(MOCK_ERROR_SOURCE_IDENTIFIER); }
### Question: Registry { Set<ComponentKey> getComponentKeys(Class<?> annotatedClass) { Annotation annotation = annotatedClass.getAnnotation(annotationClass); Set<ComponentKey> values = new HashSet<>(); if (annotation instanceof Decoder) { Decoder decoder = (Decoder) annotation; values.add(new ComponentKey(decoder.value(), decoder.program())); } if (annotation instanceof Encoder) { Encoder encoder = (Encoder) annotation; values.add(new ComponentKey(encoder.value(), encoder.program())); } if (annotation instanceof Validator) { Validator validator = (Validator) annotation; values.add(new ComponentKey(validator.value(), validator.program())); } return values; } Registry(Context context, Class<? extends Annotation> annotationClass); R get(TemplateId registryKey); Set<R> inclusiveGet(TemplateId registryKey); void register(ComponentKey registryKey, Class<? extends R> handler); int size(); }### Answer: @Test void testRegistry_getTemplateIds() { Set<ComponentKey> componentKeys = registry.getComponentKeys(AggregateCountDecoder.class); assertWithMessage("A componentKey is expected") .that(componentKeys).hasSize(1); for (ComponentKey componentKey : componentKeys) { assertWithMessage("The templateId should be") .that(componentKey.getTemplate()).isSameInstanceAs(TemplateId.PI_AGGREGATE_COUNT); } componentKeys = context.getRegistry(Encoder.class).getComponentKeys(AggregateCountEncoder.class); assertWithMessage("A componentKey is expected") .that(componentKeys).hasSize(1); for (ComponentKey componentKey : componentKeys) { assertWithMessage("The templateId should be") .that(componentKey.getTemplate()).isSameInstanceAs(TemplateId.PI_AGGREGATE_COUNT); } } @Test void testRegistry_getTemplateIds_NullReturn() { Set<ComponentKey> componentKeys = context.getRegistry(SuppressWarnings.class).getComponentKeys(Placeholder.class); assertWithMessage("A componentKey is not expected") .that(componentKeys).isEmpty(); }
### Question: Registry { public int size() { return registryMap.size(); } Registry(Context context, Class<? extends Annotation> annotationClass); R get(TemplateId registryKey); Set<R> inclusiveGet(TemplateId registryKey); void register(ComponentKey registryKey, Class<? extends R> handler); int size(); }### Answer: @Test void testSize() { assertThat(registry.size()).isGreaterThan(0); }
### Question: PathSource extends SkeletalSource { @Override public InputStream toInputStream() { try { return Files.newInputStream(path); } catch (IOException exception) { throw new UncheckedIOException(exception); } } PathSource(Path path); @Override InputStream toInputStream(); @Override long getSize(); @Override String getPurpose(); }### Answer: @Test void testInputStream() throws IOException { String content = IOUtils.toString(source.toInputStream(), StandardCharsets.UTF_8); assertWithMessage("stream content was not as expected") .that(content).isEqualTo("hello, world"); }
### Question: PathSource extends SkeletalSource { @Override public String getPurpose() { return null; } PathSource(Path path); @Override InputStream toInputStream(); @Override long getSize(); @Override String getPurpose(); }### Answer: @Test void testIsTest() { assertThat(source.getPurpose()).isNull(); }
### Question: QrdaServiceImpl implements QrdaService { @PostConstruct public void preloadMeasureConfigs() { MeasureConfigs.init(); } QrdaServiceImpl(StorageService storageService); @PostConstruct void preloadMeasureConfigs(); @PostConstruct void loadCpcValidationData(); @PostConstruct void loadApmData(); @Override ConversionReport convertQrda3ToQpp(Source source); @Override InputStream retrieveCpcPlusValidationFile(); }### Answer: @Test void testPostConstructForCoverage() { objectUnderTest.preloadMeasureConfigs(); }
### Question: QrdaDecoderEngine extends XmlDecoderEngine { private List<Element> getUniqueTemplateIdElements(final List<Element> childElements) { Set<TemplateId> uniqueTemplates = EnumSet.noneOf(TemplateId.class); List<Element> children = childElements.stream() .filter(filterElement -> { boolean isTemplateId = TEMPLATE_ID.equals(filterElement.getName()); TemplateId filterTemplateId = getTemplateId(filterElement); boolean elementWillStay = true; if (isTemplateId) { if (getDecoder(filterTemplateId) == null || uniqueTemplates.contains(filterTemplateId)) { elementWillStay = false; } uniqueTemplates.add(filterTemplateId); } return elementWillStay; }) .collect(Collectors.toList()); return (uniqueTemplates.isEmpty() || uniqueTemplates.stream().anyMatch(template -> TemplateId.UNIMPLEMENTED != template)) ? children : new ArrayList<>(); } QrdaDecoderEngine(Context context); @Override Node decode(Element xmlDoc); }### Answer: @Test void testGetUniqueTemplateIdElements() { Element rootElement = createRootElement(); Element middleElement = createGenericElement(); Element initialTemplateIdElement = createContinueElement(); Element duplicateTemplateIdElement = createContinueElement(); Element fourthLevelElement = createGenericElement(); Element fifthLevelElement = createFinishElement(); addChildToParent(rootElement, middleElement); addChildToParent(middleElement, initialTemplateIdElement); addChildToParent(middleElement, duplicateTemplateIdElement); addChildToParent(middleElement, fourthLevelElement); addChildToParent(fourthLevelElement, fifthLevelElement); QrdaDecoderEngine objectUnderTest = new QrdaDecoderEngine(context); Node decodedNodes = objectUnderTest.decode(rootElement); assertNodeCount(decodedNodes, 1, 1, 0); }
### Question: ConversionReport { public Node getDecoded() { return CloneHelper.deepClone(decoded); } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void testGetDecoded() { assertThat(report.getDecoded()).isNotNull(); }
### Question: ConversionReport { public JsonWrapper getEncodedWithMetadata() { return CloneHelper.deepClone(encodedWithMetadata); } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void testGetEncoded() { assertThat(report.getEncodedWithMetadata().toString()) .isEqualTo(wrapper.toString()); }
### Question: ConversionReport { public AllErrors getReportDetails() { return reportDetails; } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void getReportDetails() { assertThat(errorReport.getReportDetails()).isNotNull(); }
### Question: ConversionReport { public Source getQrdaSource() { return source; } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void testGetQrdaSource() { assertThat(report.getQrdaSource()).isEqualTo(inputSource); }
### Question: ConversionReport { public Source getQppSource() { return getEncodedWithMetadata().toSource(); } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void testGetQppSource() throws IOException { assertThat(IOUtils.toString(report.getQppSource().toInputStream(), StandardCharsets.UTF_8)) .isEqualTo(IOUtils.toString(wrapper.toSource().toInputStream(), StandardCharsets.UTF_8)); }
### Question: ConversionReport { public Source getValidationErrorsSource() { try { byte[] validationErrorBytes = mapper.writeValueAsBytes(reportDetails); return new InputStreamSupplierSource("ValidationErrors", new ByteArrayInputStream(validationErrorBytes)); } catch (JsonProcessingException e) { throw new EncodeException("Issue serializing error report details", e); } } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void getGoodReportDetails() { assertThat(errorReport.getValidationErrorsSource().toInputStream()).isNotNull(); }
### Question: ConversionReport { public Source getRawValidationErrorsOrEmptySource() { String raw = (qppValidationDetails != null) ? qppValidationDetails : ""; byte[] rawValidationErrorBytes = raw.getBytes(StandardCharsets.UTF_8); return new InputStreamSupplierSource("RawValidationErrors", new ByteArrayInputStream(rawValidationErrorBytes)); } ConversionReport(Source source, List<Detail> errors, List<Detail> warnings, Node decoded, JsonWrapper encodedWithMetadata); Node getDecoded(); JsonWrapper getEncodedWithMetadata(); AllErrors getReportDetails(); void setReportDetails(AllErrors details); void setRawValidationDetails(String details); Source getQrdaSource(); Source getQppSource(); Source getValidationErrorsSource(); List<Detail> getWarnings(); void setWarnings(List<Detail> warnings); Source getRawValidationErrorsOrEmptySource(); String getPurpose(); }### Answer: @Test void emptyRawValidationErrors() throws IOException { String details = IOUtils.toString(errorReport.getRawValidationErrorsOrEmptySource().toInputStream(), "UTF-8"); assertThat(details).isEmpty(); }
### Question: PathCorrelator { public static String getXpath(String base, String attribute, String uri) { String key = PathCorrelator.getKey(base, attribute); Goods goods = pathCorrelationMap.get(key); return (goods == null) ? null : goods.getRelativeXPath().replace(uriSubstitution, uri); } private PathCorrelator(); static String getXpath(String base, String attribute, String uri); static String prepPath(String jsonPath, JsonWrapper wrapper); static final String KEY_DELIMITER; }### Answer: @Test void pathCorrelatorInitilization() { String xpath = PathCorrelator.getXpath(TemplateId.CLINICAL_DOCUMENT.name(), ClinicalDocumentDecoder.PROGRAM_NAME, "meep"); assertThat(xpath).isNotNull(); }
### Question: PathCorrelator { public static String prepPath(String jsonPath, JsonWrapper wrapper) { String base = "$"; String leaf = jsonPath; int lastIndex = jsonPath.lastIndexOf('.'); if (lastIndex > 0) { base = jsonPath.substring(0, lastIndex); leaf = jsonPath.substring(lastIndex + 1); } JsonPath compiledPath = JsonPath.compile(base); String json = wrapper.toStringWithMetadata(); Map<String, Object> jsonMap = compiledPath.read(json); Map<String, String> metaMap = getMetaMap(jsonMap, leaf); String preparedPath = ""; if (metaMap != null) { preparedPath = makePath(metaMap, leaf); } return preparedPath; } private PathCorrelator(); static String getXpath(String base, String attribute, String uri); static String prepPath(String jsonPath, JsonWrapper wrapper); static final String KEY_DELIMITER; }### Answer: @Test void unacknowledgedEncodedLabel() { JsonWrapper metadata = new JsonWrapper(); metadata.putMetadata("meep", "meep"); metadata.putMetadata(JsonWrapper.ENCODING_KEY, "mawp"); JsonWrapper wrapper = new JsonWrapper(); wrapper.addMetadata(metadata); wrapper.put("mop","mop"); String actual = PathCorrelator.prepPath("$.mawp", wrapper); assertThat(actual).isEmpty(); } @Test void unacknowledgedEncodedLabel_multipleMetadata() { JsonWrapper metadata = new JsonWrapper(); metadata.putMetadata("meep", "meep"); metadata.putMetadata(JsonWrapper.ENCODING_KEY, "mawp"); JsonWrapper metadata2 = new JsonWrapper(); metadata2.putMetadata("template", "mip"); metadata2.putMetadata("nsuri", "mip"); metadata2.putMetadata(JsonWrapper.ENCODING_KEY, "mip"); JsonWrapper wrapper = new JsonWrapper(); wrapper.addMetadata(metadata); wrapper.addMetadata(metadata2); wrapper.put("mop","mop"); String actual = PathCorrelator.prepPath("$.mawp", wrapper); assertThat(actual).isEmpty(); }
### Question: Converter { public ConversionReport getReport() { return new ConversionReport(source, errors, warnings, decoded, encoded); } Converter(Source source); Converter(Source source, Context context); Context getContext(); JsonWrapper transform(); ConversionReport getReport(); }### Answer: @Test public void testTestSourceCreatesTestReport() { Source source = mock(Source.class); when(source.getPurpose()).thenReturn("Test"); Truth.assertThat(new Converter(source).getReport().getPurpose()).isEqualTo("Test"); } @Test public void testNormalSourceCreatesNormalReport() { Source source = mock(Source.class); when(source.getPurpose()).thenReturn(null); Truth.assertThat(new Converter(source).getReport().getPurpose()).isNull(); }
### Question: InputStreamSupplierSource extends SkeletalSource { @Override public InputStream toInputStream() { return stream.get(); } InputStreamSupplierSource(String name, InputStream source); InputStreamSupplierSource(String name, InputStream source, String purpose); @Override InputStream toInputStream(); @Override long getSize(); @Override String getPurpose(); }### Answer: @Test void testInputStream() throws IOException { String actual = IOUtils.toString(stream("src/test/resources/arbitrary.txt"), StandardCharsets.UTF_8); String content = IOUtils.toString(source.toInputStream(), StandardCharsets.UTF_8); assertThat(actual).isEqualTo(content); }
### Question: InputStreamSupplierSource extends SkeletalSource { @Override public long getSize() { return stream.size(); } InputStreamSupplierSource(String name, InputStream source); InputStreamSupplierSource(String name, InputStream source, String purpose); @Override InputStream toInputStream(); @Override long getSize(); @Override String getPurpose(); }### Answer: @Test void testSpecificSize() { String text = "mock"; InputStreamSupplierSource source = new InputStreamSupplierSource("DogCow name", new ByteArrayInputStream(text.getBytes())); assertThat(source.getSize()).isEqualTo(text.length()); } @Test void testUnspecifiedSize() { byte [] bytes = "Moof".getBytes(); InputStreamSupplierSource source = new InputStreamSupplierSource("DogCow name", new ByteArrayInputStream(bytes)); assertThat(source.getSize()).isEqualTo(bytes.length); }
### Question: ValidationServiceImpl implements ValidationService { HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE); headers.add(HttpHeaders.ACCEPT, CONTENT_TYPE); String submissionToken = environment.getProperty(Constants.SUBMISSION_API_TOKEN_ENV_VARIABLE); if (submissionToken != null && !submissionToken.isEmpty()) { headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + submissionToken); } return headers; } ValidationServiceImpl(final Environment environment); @PostConstruct void checkForValidationUrlVariable(); @Override void validateQpp(ConversionReport conversionReport); static final String SV_LABEL; }### Answer: @Test void testHeaderCreation() { HttpHeaders headers = objectUnderTest.getHeaders(); assertThat(headers.getFirst(HttpHeaders.CONTENT_TYPE)).isEqualTo(ValidationServiceImpl.CONTENT_TYPE); assertThat(headers.getFirst(HttpHeaders.ACCEPT)).isEqualTo(ValidationServiceImpl.CONTENT_TYPE); } @Test void testHeaderCreationNoAuth() { when(environment.getProperty(eq(Constants.SUBMISSION_API_TOKEN_ENV_VARIABLE))).thenReturn(null); HttpHeaders headers = objectUnderTest.getHeaders(); assertThat(headers.get(HttpHeaders.AUTHORIZATION)).isNull(); } @Test void testHeaderCreationNoAuthEmpty() { when(environment.getProperty(eq(Constants.SUBMISSION_API_TOKEN_ENV_VARIABLE))).thenReturn(""); HttpHeaders headers = objectUnderTest.getHeaders(); assertThat(headers.get(HttpHeaders.AUTHORIZATION)).isNull(); } @Test void testHeaderCreationAuth() { when(environment.getProperty(eq(Constants.SUBMISSION_API_TOKEN_ENV_VARIABLE))).thenReturn("meep"); HttpHeaders headers = objectUnderTest.getHeaders(); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).contains("meep"); }
### Question: InputStreamSupplierSource extends SkeletalSource { @Override public String getPurpose() { return purpose; } InputStreamSupplierSource(String name, InputStream source); InputStreamSupplierSource(String name, InputStream source, String purpose); @Override InputStream toInputStream(); @Override long getSize(); @Override String getPurpose(); }### Answer: @Test void testTestIsTest() { String text = "mock"; InputStreamSupplierSource source = new InputStreamSupplierSource("DogCow name", new ByteArrayInputStream(text.getBytes()), "Test"); Truth.assertThat(source.getPurpose()).isEqualTo("Test"); } @Test void testNormalIsNotTest() { String text = "mock"; InputStreamSupplierSource source = new InputStreamSupplierSource("DogCow name", new ByteArrayInputStream(text.getBytes()), null); Truth.assertThat(source.getPurpose()).isNull(); } @Test void testDefaultIsNotTest() { String text = "mock"; InputStreamSupplierSource source = new InputStreamSupplierSource("DogCow name", new ByteArrayInputStream(text.getBytes())); Truth.assertThat(source.getPurpose()).isNull(); }
### Question: CpcClinicalDocumentValidator extends NodeValidator { private ZonedDateTime now() { ZoneId zone = ZoneId.of("US/Eastern"); return ZonedDateTime.now(zone); } CpcClinicalDocumentValidator(Context context); }### Answer: @Test void testCpcPlusSubmissionBeforeEndDate() { System.setProperty(CpcClinicalDocumentValidator.END_DATE_VARIABLE, ZonedDateTime.now(CpcClinicalDocumentValidator.EASTERN_TIME_ZONE).plusYears(3) .format(CpcClinicalDocumentValidator.INPUT_END_DATE_FORMAT)); Node clinicalDocument = createValidCpcPlusClinicalDocument(); List<Detail> errors = cpcValidator.validateSingleNode(clinicalDocument).getErrors(); assertThat(errors) .isEmpty(); }
### Question: QrdaValidator { private void validateSingleNode(final Node node) { getValidators(node.getType()) .filter(this::isValidationRequired) .forEach(validatorForNode -> { ValidationResult problems = validatorForNode.validateSingleNode(node); errors.addAll(problems.getErrors()); warnings.addAll(problems.getWarnings()); }); } QrdaValidator(Context context); ValidationResult validate(Node rootNode); }### Answer: @Test public void testValidateSingleNode() { Node testRootNode = new Node(TEST_REQUIRED_TEMPLATE_ID); final String testKey = "testKey"; final String testValue = "testValue"; testRootNode.putValue(testKey, testValue); List<Detail> details = objectUnderTest.validate(testRootNode).getErrors(); assertNodeList(nodesPassedIntoValidateSingleNode, 1, TEST_REQUIRED_TEMPLATE_ID, testKey, testValue); assertWithMessage("The validation errors is missing items from the expected templateId") .that(details).contains(TEST_VALIDATION_ERROR_FOR_SINGLE_NODE); }
### Question: Checker { Checker valueIn(LocalizedProblem code, String name, String... values) { boolean contains = false; if (name == null) { details.add(detail(code)); return this; } lastAppraised = node.getValue(name); if (lastAppraised == null || values == null || values.length == 0) { details.add(detail(code)); return this; } for (String value : values) { if (((String) lastAppraised).equalsIgnoreCase(value)) { contains = true; break; } } if (!contains) { details.add(detail(code)); } return this; } private Checker(Node node, List<Detail> details, boolean force); boolean shouldShortcut(); Checker value(LocalizedProblem code, String name); Checker singleValue(LocalizedProblem code, String name); Checker isValidDate(LocalizedProblem code, String name); Checker childMinimum(LocalizedProblem code, int minimum, TemplateId... types); Checker childMaximum(LocalizedProblem code, int maximum, TemplateId... types); Checker childExact(LocalizedProblem code, int exactCount, TemplateId... types); }### Answer: @Test void testValueIn() throws Exception { String key = "My Key"; String value = "My Value"; Node testNode = makeTestNode(key, value); Checker checker = Checker.check(testNode, details); checker.valueIn(ERROR_MESSAGE, key, "No Value" , "Some Value", "My Value"); assertWithMessage("There should be no errors") .that(details).isEmpty(); }
### Question: ValidationServiceImpl implements ValidationService { AllErrors convertQppValidationErrorsToQrda(String validationResponse, JsonWrapper wrapper) { AllErrors errors = new AllErrors(); if (validationResponse == null) { return errors; } Error error = getError(validationResponse); error.getDetails().forEach(detail -> { detail.setMessage(SV_LABEL + detail.getMessage()); String newPath = UNABLE_PROVIDE_XPATH; try { newPath = PathCorrelator.prepPath(detail.getLocation().getPath(), wrapper); } catch (ClassCastException | JsonPathException exc) { API_LOG.warn("Failed to convert from json path to an XPath.", exc); } detail.getLocation().setPath(newPath); }); errors.addError(error); return errors; } ValidationServiceImpl(final Environment environment); @PostConstruct void checkForValidationUrlVariable(); @Override void validateQpp(ConversionReport conversionReport); static final String SV_LABEL; }### Answer: @Test void testJsonDesrializationDuplicateEntry() throws IOException { String errorJson = new String(Files.readAllBytes(pathToSubmissionDuplicateEntryError)); convertedErrors = service.convertQppValidationErrorsToQrda(errorJson, qppWrapper); assertWithMessage("Error json should map to AllErrors") .that(convertedErrors.getErrors()) .hasSize(1); assertThat(convertedErrors.getErrors().get(0).getDetails().get(0).getMessage()) .startsWith(ValidationServiceImpl.SV_LABEL); } @Test void testInvalidSubmissionResponseJsonPath() throws IOException { pathToSubmissionError = Paths.get("src/test/resources/invalidSubmissionErrorFixture.json"); String errorJson = FileUtils.readFileToString(pathToSubmissionError.toFile(), StandardCharsets.UTF_8); convertedErrors = service.convertQppValidationErrorsToQrda(errorJson, qppWrapper); convertedErrors.getErrors().stream().flatMap(error -> error.getDetails().stream()) .map(Detail::getLocation).map(Location::getPath).forEach(path -> assertThat(path).isEqualTo(ValidationServiceImpl.UNABLE_PROVIDE_XPATH)); }
### Question: ValidationServiceImpl implements ValidationService { Error getError(String response) { return JsonHelper.readJson(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)), ErrorMessage.class) .getError(); } ValidationServiceImpl(final Environment environment); @PostConstruct void checkForValidationUrlVariable(); @Override void validateQpp(ConversionReport conversionReport); static final String SV_LABEL; }### Answer: @Test void testQppToQrdaErrorPathConversion() { Detail detail = submissionError.getError().getDetails().get(0); Detail mappedDetails = convertedErrors.getErrors().get(0).getDetails().get(0); assertWithMessage("Json path should be converted to xpath") .that(detail.getLocation().getPath()) .isNotEqualTo(mappedDetails.getLocation().getPath()); }
### Question: ManifestVersionService implements VersionService { @Override public String getImplementationVersion() { return Manifests.read("Implementation-Version"); } @Override String getImplementationVersion(); }### Answer: @Test void testReadsVersionFromManifest() { Truth.assertThat(new ManifestVersionService().getImplementationVersion()).isNotEmpty(); }
### Question: AuditServiceImpl implements AuditService { @Override public CompletableFuture<Void> failConversion(ConversionReport conversionReport) { if (noAudit()) { return null; } API_LOG.info("Writing audit information for a conversion failure scenario"); Metadata metadata = initMetadata(conversionReport, Outcome.CONVERSION_ERROR); Source qrdaSource = conversionReport.getQrdaSource(); Source validationErrorSource = conversionReport.getValidationErrorsSource(); CompletableFuture<Void> allWrites = CompletableFuture.allOf( storeContent(validationErrorSource).thenAccept(metadata::setConversionErrorLocator), storeContent(qrdaSource).thenAccept(metadata::setSubmissionLocator)); return allWrites.whenComplete((ignore, thrown) -> persist(metadata, thrown)); } AuditServiceImpl(final StorageService storageService, final DbService dbService, final Environment environment); @Override CompletableFuture<Metadata> success(ConversionReport conversionReport); @Override CompletableFuture<Void> failConversion(ConversionReport conversionReport); @Override CompletableFuture<Void> failValidation(ConversionReport conversionReport); }### Answer: @Test public void testAuditConversionFailureHappy() { when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn(null); errorPrep(); allGood(); underTest.failConversion(report); assertThat(metadata.getConversionErrorLocator()).isSameInstanceAs(AN_ID); assertThat(metadata.getSubmissionLocator()).isSameInstanceAs(AN_ID); } @Test public void testAuditConversionFailureNoAudit() { when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn("yep"); errorPrep(); allGood(); underTest.failConversion(report); verify(storageService, times(0)).store(any(String.class), any(), anyLong()); verify(dbService, times(0)).write(metadata); }
### Question: UnprocessedCpcFileData { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("fileId", fileId) .add("filename", "*could hold PII*") .add("apm", apm) .add("conversionDate", conversionDate) .add("validationSuccess", validationSuccess) .add("purpose", purpose) .toString(); } UnprocessedCpcFileData(Metadata metadata); String getFileId(); String getFilename(); String getApm(); String getConversionDate(); Boolean getValidationSuccess(); String getPurpose(); @Override String toString(); }### Answer: @Test @DisplayName("should give a string representation of its state") void testToString() { UnprocessedCpcFileData data = new UnprocessedCpcFileData(Metadata.create()); String strung = data.toString(); assertThat(strung).matches(".*fileId.*filename.*apm.*conversionDate.*validationSuccess.*purpose.*"); }
### Question: ConcurrencyConfig { @Bean public TaskExecutor taskExecutor() { return new SyncTaskExecutor(); } @Bean TaskExecutor taskExecutor(); }### Answer: @Test void testIsSync() { TaskExecutor executor = new ConcurrencyConfig().taskExecutor(); assertThat(executor).isInstanceOf(SyncTaskExecutor.class); }
### Question: StringHelper { public static String join(Iterable<String> iterable, String separator, String conjunction) { separator = separator + " "; conjunction = conjunction + " "; StringBuilder creator = new StringBuilder(); int timeThroughLoop = 0; Iterator<String> iterator = iterable.iterator(); while (iteratorHasAnotherItem(iterator)) { timeThroughLoop++; String currentString = iterator.next(); if (iteratorHasAnotherItem(iterator)) { appendStringAndThenString(creator, currentString, separator); } else if (isFirstItem(timeThroughLoop)) { creator.append(currentString); } else { if (isSecondItem(timeThroughLoop)) { deletePreviousConjunction(conjunction, creator); } appendStringAndThenString(creator, conjunction, currentString); } } return creator.toString(); } private StringHelper(); static String join(Iterable<String> iterable, String separator, String conjunction); static String join(String[] toIterate, String separator, String conjunction); }### Answer: @Test void testJoining() { String joined = StringHelper.join(Arrays.asList("Dog", "Cow", "Moof"), ",", "or"); assertThat(joined).isEqualTo("Dog, Cow, or Moof"); } @Test void testJoiningOneElement() { String joined = StringHelper.join(Collections.singletonList("Dog"), ",", "or"); assertThat(joined).isEqualTo("Dog"); } @Test void testJoiningTwoElement() { String joined = StringHelper.join(Arrays.asList("Dog", "Cow"), ",", "or"); assertThat(joined).isEqualTo("Dog or Cow"); } @Test void testSomethingDifferent() { String joined = StringHelper.join( Arrays.asList("Completely", "Utterly", "Incontrovertibly", "Capriciously"), " DogCow,", "and even perhaps"); assertThat(joined).isEqualTo("Completely DogCow, Utterly DogCow, Incontrovertibly DogCow, and even perhaps Capriciously"); }
### Question: DynamoDbConfigFactory { public static DynamoDBMapper createDynamoDbMapper( final AmazonDynamoDB dynamoDb, final DynamoDBMapperConfig config, final AttributeTransformer transformer) { return new DynamoDBMapper(dynamoDb, config, transformer); } private DynamoDbConfigFactory(); static DynamoDBMapper createDynamoDbMapper( final AmazonDynamoDB dynamoDb, final DynamoDBMapperConfig config, final AttributeTransformer transformer); }### Answer: @Test void testFactory() { DynamoDBMapper dynamoDBMapper = DynamoDbConfigFactory.createDynamoDbMapper(null, null, null); assertWithMessage("The DynamoDB mapper must not be null.").that(dynamoDBMapper).isNotNull(); }
### Question: S3Config { @Bean public TransferManager s3TransferManager(AmazonS3 s3Client) { return TransferManagerBuilder.standard().withS3Client(s3Client).build(); } @Bean AmazonS3 s3client(); @Bean TransferManager s3TransferManager(AmazonS3 s3Client); }### Answer: @Test public void testTransferManagerIsNotNull() { assertWithMessage("Transfer manager should not be null.") .that(underTest.s3TransferManager(Mockito.mock(AmazonS3.class))).isNotNull(); }
### Question: HealthCheckController { @GetMapping @ResponseStatus(HttpStatus.OK) public @ResponseBody HealthCheck health() { HealthCheck healthCheck = new HealthCheck(); healthCheck.setEnvironmentVariables(new ArrayList<>(System.getenv().keySet())); healthCheck.setSystemProperties( System.getProperties().keySet().stream().map(String::valueOf).collect(Collectors.toList())); healthCheck.setImplementationVersion(version.getImplementationVersion()); return healthCheck; } HealthCheckController(VersionService version); @GetMapping @ResponseStatus(HttpStatus.OK) @ResponseBody HealthCheck health(); }### Answer: @Test void testHealthCheckContainsAllSystemProperties() { List<String> systemProperties = System.getProperties().keySet().stream().map(String::valueOf) .collect(Collectors.toList()); Truth.assertThat(service.health().getSystemProperties()).containsExactlyElementsIn(systemProperties); } @Test void testHealthCheckContainsAllEnvironmentVariables() { Set<String> environmentVariables = System.getenv().keySet(); Truth.assertThat(service.health().getEnvironmentVariables()) .containsExactlyElementsIn(environmentVariables); } @Test void testHealthCheckContainsImplementationVersion() { Mockito.when(version.getImplementationVersion()).thenReturn("Mock Version"); Truth.assertThat(service.health().getImplementationVersion()).isEqualTo("Mock Version"); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(TransformException.class) @ResponseBody ResponseEntity<AllErrors> handleTransformException(TransformException exception) { API_LOG.error("Transform exception occurred", exception); auditService.failConversion(exception.getConversionReport()); return cope(exception); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testTransformExceptionStatusCode() { TransformException exception = new TransformException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleTransformException(exception); assertWithMessage("The response entity's status code must be 422.") .that(responseEntity.getStatusCode()) .isEquivalentAccordingToCompareTo(HttpStatus.UNPROCESSABLE_ENTITY); } @Test void testTransformExceptionHeaderContentType() { TransformException exception = new TransformException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleTransformException(exception); assertThat(responseEntity.getHeaders().getContentType()) .isEquivalentAccordingToCompareTo(MediaType.APPLICATION_JSON); } @Test void testTransformExceptionBody() { TransformException exception = new TransformException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleTransformException(exception); assertThat(responseEntity.getBody()).isEqualTo(allErrors); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(QppValidationException.class) @ResponseBody ResponseEntity<AllErrors> handleQppValidationException(QppValidationException exception) { API_LOG.error("Validation exception occurred", exception); auditService.failValidation(exception.getConversionReport()); return cope(exception); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testQppValidationExceptionStatusCode() { QppValidationException exception = new QppValidationException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleQppValidationException(exception); assertWithMessage("The response entity's status code must be 422.") .that(responseEntity.getStatusCode()) .isEquivalentAccordingToCompareTo(HttpStatus.UNPROCESSABLE_ENTITY); } @Test void testQppValidationExceptionHeaderContentType() { QppValidationException exception = new QppValidationException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleQppValidationException(exception); assertThat(responseEntity.getHeaders().getContentType()) .isEquivalentAccordingToCompareTo(MediaType.APPLICATION_JSON); } @Test void testQppValidationExceptionBody() { QppValidationException exception = new QppValidationException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleQppValidationException(exception); assertThat(responseEntity.getBody()).isEqualTo(allErrors); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(NoFileInDatabaseException.class) @ResponseBody ResponseEntity<String> handleFileNotFoundException(NoFileInDatabaseException exception) { API_LOG.error("A database error occurred", exception); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>(exception.getMessage(), httpHeaders, HttpStatus.NOT_FOUND); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testFileNotFoundExceptionStatusCode() { NoFileInDatabaseException exception = new NoFileInDatabaseException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleFileNotFoundException(exception); assertWithMessage("The response entity's status code must be 422.") .that(responseEntity.getStatusCode()) .isEquivalentAccordingToCompareTo(HttpStatus.NOT_FOUND); } @Test void testFileNotFoundExceptionHeaderContentType() { NoFileInDatabaseException exception = new NoFileInDatabaseException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleFileNotFoundException(exception); assertThat(responseEntity.getHeaders().getContentType()) .isEquivalentAccordingToCompareTo(MediaType.TEXT_PLAIN); } @Test void testFileNotFoundExceptionBody() { NoFileInDatabaseException exception = new NoFileInDatabaseException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleFileNotFoundException(exception); assertThat(responseEntity.getBody()).isEqualTo(CpcFileServiceImpl.FILE_NOT_FOUND); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(InvalidFileTypeException.class) @ResponseBody ResponseEntity<String> handleInvalidFileTypeException(InvalidFileTypeException exception) { API_LOG.error("A file type error occurred", exception); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>(exception.getMessage(), httpHeaders, HttpStatus.NOT_FOUND); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testInvalidFileTypeExceptionStatusCode() { InvalidFileTypeException exception = new InvalidFileTypeException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleInvalidFileTypeException(exception); assertWithMessage("The response entity's status code must be 422.") .that(responseEntity.getStatusCode()) .isEquivalentAccordingToCompareTo(HttpStatus.NOT_FOUND); } @Test void testInvalidFileTypeExceptionHeaderContentType() { InvalidFileTypeException exception = new InvalidFileTypeException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleInvalidFileTypeException(exception); assertThat(responseEntity.getHeaders().getContentType()) .isEquivalentAccordingToCompareTo(MediaType.TEXT_PLAIN); } @Test void testInvalidFileTypeExceptionBody() { InvalidFileTypeException exception = new InvalidFileTypeException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleInvalidFileTypeException(exception); assertThat(responseEntity.getBody()).isEqualTo(CpcFileServiceImpl.FILE_NOT_FOUND); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(AmazonServiceException.class) @ResponseBody ResponseEntity<String> handleAmazonException(AmazonServiceException exception) { API_LOG.error("An AWS error occured", exception); return ResponseEntity.status(exception.getStatusCode()) .contentType(MediaType.TEXT_PLAIN) .body(exception.getMessage()); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testHandleAmazonExceptionStatusCode() { AmazonServiceException exception = new AmazonServiceException("some message"); exception.setStatusCode(404); ResponseEntity<String> response = objectUnderTest.handleAmazonException(exception); Truth.assertThat(response.getStatusCodeValue()).isEqualTo(404); } @Test void testHandleAmazonExceptionResponseBody() { AmazonServiceException exception = new AmazonServiceException("some message"); ResponseEntity<String> response = objectUnderTest.handleAmazonException(exception); Truth.assertThat(response.getBody()).contains("some message"); }
### Question: ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(InvalidPurposeException.class) @ResponseBody ResponseEntity<String> handleInvalidPurposeException(InvalidPurposeException exception) { API_LOG.error("An invalid purpose error occured", exception); return ResponseEntity.badRequest() .contentType(MediaType.TEXT_PLAIN) .body(exception.getMessage()); } ExceptionHandlerControllerV1(final AuditService auditService); }### Answer: @Test void testHandleInvalidPurposeExceptionExceptionResponseBody() { InvalidPurposeException exception = new InvalidPurposeException("some message"); ResponseEntity<String> response = objectUnderTest.handleInvalidPurposeException(exception); Truth.assertThat(response.getBody()).contains("some message"); }
### Question: XMLSerializer extends AbstractSerializer<T> { @Override protected T deserialize(JsonNode root) throws IOException { String name = root.get("name").asText(); JsonNode element = root.get("TopicData"); if (topicDataType.getName().equals(name) && element != null && element.isObject()) { JacksonInterchangeSerializer serializer = new JacksonInterchangeSerializer((ObjectNode) element, false); T data = topicDataType.createData(); topicDataType.deserialize(serializer, data); return data; } else { return null; } } XMLSerializer(TopicDataType<T> topicDataType); }### Answer: @Test public void test() throws IOException { ChatMessagePubSubType dataType = new ChatMessagePubSubType(); XMLSerializer<ChatMessage> serializer = new XMLSerializer<>(dataType); ChatMessage msg = new ChatMessage(); msg.getSender().append("Java"); msg.getMsg().append("Hello World"); String xml = serializer.serializeToString(msg); ChatMessage res = serializer.deserialize(xml); assertEquals(msg, res); }
### Question: CopyFile { void copyFileWithSixChannel(String from, String dest) { InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; BufferedWriter bufferedWriter = null; try { inputStream = new FileInputStream(from); inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); outputStream = new FileOutputStream(dest); outputStreamWriter = new OutputStreamWriter(outputStream); bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.flush(); String L; while ((L = bufferedReader.readLine()) != null) { bufferedWriter.write(L + "\r\n"); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { ResourceTool.close(bufferedReader, inputStreamReader, inputStream); log.info("close all input stream"); ResourceTool.close(bufferedWriter, outputStreamWriter, outputStream); log.info("close all output stream"); } catch (Exception e) { log.error(e.getMessage(), e); } } } }### Answer: @Test public void testFirst() throws IOException { file.copyFileWithSixChannel(from, dest); validateResultFile(); }
### Question: TimeClient { void sendMsg(String msg) { timeClientHandler.sendMsg(msg); } }### Answer: @Test(threadPoolSize = 5, invocationCount = 20) public void testClient() throws Exception { startClient(); timeClient.sendMsg(Command.QUERY_TIME); }
### Question: TimeServer { public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 512) .childHandler(new ChannelInit(this)); ChannelFuture future = serverBootstrap.bind(port).sync(); this.channel = future.channel(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } void start(); void stop(); }### Answer: @Test public void testServer() throws Exception { timeServer.start(); }
### Question: InstantiationAndConstructor implements Serializable, Cloneable { @Override protected InstantiationAndConstructor clone() throws CloneNotSupportedException { return (InstantiationAndConstructor) super.clone(); } InstantiationAndConstructor(); InstantiationAndConstructor(String name); }### Answer: @Test public void testInitByClone() throws CloneNotSupportedException { String name = "clone"; InstantiationAndConstructor target = new InstantiationAndConstructor(name); log.info("start clone"); InstantiationAndConstructor clone = target.clone(); assertThat(target, equalTo(clone)); assertThat(clone == target, equalTo(false)); assertThat(clone.getName(), equalTo("clone")); }
### Question: HeapOOM { void createArray() { List<byte[]> data = new ArrayList<>(); while (true) { data.add(new byte[1024 * 1024]); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } void otherThreadWithOOM(); }### Answer: @Test public void testCreateArray() { heapOOM.createArray(); }
### Question: HeapOOM { void createMap() { Map<Key, String> map = new HashMap<>(); testMap(map); } void otherThreadWithOOM(); }### Answer: @Test public void testCreateMap() { heapOOM.createMap(); }