method2testcases stringlengths 118 3.08k |
|---|
### Question:
DBAppraiserManager extends DBManager<Appraiser> implements AppraiserManager { @Override public final Appraiser saveAppraiser(final Appraiser appraiser) throws AppraiserManagerException { LOGGER.debug("saving appraiser: {}", appraiser); try { return super.save(appraiser); } catch (DBManagerException e) { throw new AppraiserManagerException(e); } } DBAppraiserManager(final SessionFactory sessionFactory); @Override final Appraiser saveAppraiser(final Appraiser appraiser); @Override final void updateAppraiser(final Appraiser appraiser); @Override final List<Appraiser> getAppraiserList(); @Override final List<Appraiser> getAppraiserList(final Class<? extends Appraiser> clazz); @Override final Appraiser getAppraiser(final String name); @Override final boolean deleteAppraiser(final String name); }### Answer:
@Test public void testSave() { TestAppraiser testAppraiser = new TestAppraiser(APPRAISER_NAME); Appraiser savedAppraiser = appraiserManager.saveAppraiser(testAppraiser); Assert.assertNotNull(savedAppraiser.getId()); } |
### Question:
DBAppraiserManager extends DBManager<Appraiser> implements AppraiserManager { @Override public final Appraiser getAppraiser(final String name) throws AppraiserManagerException { LOGGER.debug("getting appraiser: {}", name); try { return super.get(name); } catch (DBManagerException e) { throw new AppraiserManagerException(e); } } DBAppraiserManager(final SessionFactory sessionFactory); @Override final Appraiser saveAppraiser(final Appraiser appraiser); @Override final void updateAppraiser(final Appraiser appraiser); @Override final List<Appraiser> getAppraiserList(); @Override final List<Appraiser> getAppraiserList(final Class<? extends Appraiser> clazz); @Override final Appraiser getAppraiser(final String name); @Override final boolean deleteAppraiser(final String name); }### Answer:
@Test public void testGetNonexistent() { Appraiser retrievedAppraiser = appraiserManager.getAppraiser(APPRAISER_NAME); Assert.assertNull(retrievedAppraiser); } |
### Question:
IntegrityReportRequest implements ReportRequest { public final void addReportRequest(final ReportRequest request) { LOGGER.debug("Entering addReportRequest"); if (request == null) { throw new NullPointerException("request"); } reportRequests.add(request); Collections.sort(reportRequests, REPORT_REQUEST_COLLECTION_ORDER_COMPARATOR); LOGGER.debug("Added report request {}", request.getReportType()); LOGGER.debug("Exiting addReportRequest"); } final void addReportRequest(final ReportRequest request); List<ReportRequest> getReportRequest(); @Override final Class<? extends Report> getReportType(); void setWaitForAppraisalCompletionEnabled(
final boolean waitForAppraisalCompletionEnabled); boolean isWaitForAppraisalCompletionEnabled(); }### Answer:
@Test public final void addReportRequest() { IMAReportRequest imaReportRequest = new IMAReportRequest(); IntegrityReportRequest reportRequest = new IntegrityReportRequest(); reportRequest.addReportRequest(imaReportRequest); List<ReportRequest> requests = reportRequest.getReportRequest(); Assert.assertEquals(requests.get(0).getReportType(), imaReportRequest.getReportType()); } |
### Question:
IntegrityReportRequest implements ReportRequest { public List<ReportRequest> getReportRequest() { return Collections.unmodifiableList(reportRequests); } final void addReportRequest(final ReportRequest request); List<ReportRequest> getReportRequest(); @Override final Class<? extends Report> getReportType(); void setWaitForAppraisalCompletionEnabled(
final boolean waitForAppraisalCompletionEnabled); boolean isWaitForAppraisalCompletionEnabled(); }### Answer:
@Test public final void getReportRequest() { IMAReportRequest imaReportRequest = new IMAReportRequest(); IntegrityReportRequest reportRequest = new IntegrityReportRequest(); reportRequest.addReportRequest(imaReportRequest); List<ReportRequest> requests = reportRequest.getReportRequest(); Assert.assertEquals(requests.get(0).getReportType(), imaReportRequest.getReportType()); } |
### Question:
AppraiserPluginManager { public List<AppraiserPlugin> getAppraisers() { return Collections.unmodifiableList(appraiserPlugins); } List<AppraiserPlugin> getAppraisers(); }### Answer:
@Test public void pluginListPopulatedUsingSpringInjection() { Assert.assertNotNull(appraiserPluginManager, "Verify spring is configured to autowire the AppraiserPluginManager"); List<AppraiserPlugin> pluginList = appraiserPluginManager.getAppraisers(); Assert.assertNotNull(pluginList); Assert.assertEquals(pluginList.size(), 1, "Unexpected plugin count in list"); Assert.assertTrue(pluginList.get(0) instanceof TestAppraiserPlugin, "First plugin in list was not a " + TestAppraiserPlugin.class); }
@Test public void pluginListEmptyWithoutInjectedPlugins() { AppraiserPluginManager emptyManager = new AppraiserPluginManager(); Assert.assertTrue(emptyManager.getAppraisers().isEmpty(), "collector list should be empty with no configured plugins"); } |
### Question:
Appraiser { public Appraiser(final String name) { setName(name); } Appraiser(final String name); protected Appraiser(); final Long getId(); String getName(); final void setName(final String name); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public void testAppraiser() { final String name = "Test Appraiser"; new TestAppraiser(name); } |
### Question:
Appraiser { public String getName() { return this.name; } Appraiser(final String name); protected Appraiser(); final Long getId(); String getName(); final void setName(final String name); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public void testGetName() { final String name = "Test Appraiser"; final Appraiser appraiser = new TestAppraiser(name); Assert.assertEquals(appraiser.getName(), name); } |
### Question:
Appraiser { public final void setName(final String name) { if (name == null) { LOGGER.error("null name argument"); throw new NullPointerException("name"); } this.name = name; } Appraiser(final String name); protected Appraiser(); final Long getId(); String getName(); final void setName(final String name); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public void testSetName() { final String originalName = "Test Appraiser"; final Appraiser appraiser = new TestAppraiser(originalName); Assert.assertEquals(appraiser.getName(), originalName); final String newName = "Awesome Test Appraiser"; appraiser.setName(newName); Assert.assertEquals(appraiser.getName(), newName); } |
### Question:
ReportRequestState extends State { public void setDueDate(final Date dueDate) { this.dueDate = new Date(dueDate.getTime()); } final Device getDevice(); void setDevice(final Device device); ReportRequestType getReportRequestType(); void setReportRequestType(final ReportRequestType reportRequestType); Date getDueDate(); void setDueDate(final Date dueDate); void setDueDate(final long delayThreshold); byte[] getNonce(); void setNonce(final byte[] nonce); @Override String toString(); }### Answer:
@Test public final void setDueDate() { ReportRequestState state = new ReportRequestState(); Date currentTime = new Date(); state.setDueDate(DeviceGroup.MINUTE_MS_INTERVAL); Date setDate = state.getDueDate(); Assert.assertTrue(currentTime.before(setDate)); } |
### Question:
ResourceProperties extends Properties { public final Map<String, Map<String, String>> getItems( final String listProperty) { Map<String, Map<String, String>> itemProperties = new HashMap<>(); for (String itemName : getList(listProperty)) { itemProperties.put( itemName, getItemMap(String.format("%s.%s", listProperty, itemName)) ); } return itemProperties; } ResourceProperties(); @SuppressFBWarnings( value = "UI_INHERITANCE_UNSAFE_GETRESOURCE", justification = "Not a problem since resourceName should be given" + "relative to root of classpath") ResourceProperties(final String resourceName); final Map<String, Map<String, String>> getItems(
final String listProperty); final List<String> getList(final String listProperty); final Map<String, String> getItemMap(final String basePropertyName); final boolean propertyEnabled(final String property); }### Answer:
@Test public final void testGetItemsNullParameter() throws Exception { Assert.assertEquals( getResourceProperties().getItems(null), EMPTY_ITEM_MAP ); }
@Test public final void testGetItemsNonexistentParameter() throws Exception { Assert.assertEquals( getResourceProperties().getItems("list.fake_items"), EMPTY_ITEM_MAP ); }
@Test public final void testGetItemsEmptyParameter() throws Exception { Assert.assertEquals( getResourceProperties().getItems("list.empty_items"), EMPTY_ITEM_MAP ); }
@Test public final void testGetItems() throws Exception { Map<String, Map<String, String>> items = getResourceProperties() .getItems(LIST_PROP); Assert.assertNotNull(items); Assert.assertEquals(items.get("item_one").get("size"), "small"); Assert.assertEquals(items.get("item_one").get("priority"), "high"); Assert.assertEquals(items.get("item_two").get("size"), "large"); Assert.assertEquals(items.get("item_two").get("priority"), "low"); } |
### Question:
ResourceProperties extends Properties { public final Map<String, String> getItemMap(final String basePropertyName) { Map<String, String> values = new HashMap<>(); if (basePropertyName == null) { return values; } for (String propertyName : stringPropertyNames()) { if (propertyName.startsWith(basePropertyName)) { values.put( propertyName.replaceAll(basePropertyName + ".", ""), getProperty(propertyName) ); } } return values; } ResourceProperties(); @SuppressFBWarnings( value = "UI_INHERITANCE_UNSAFE_GETRESOURCE", justification = "Not a problem since resourceName should be given" + "relative to root of classpath") ResourceProperties(final String resourceName); final Map<String, Map<String, String>> getItems(
final String listProperty); final List<String> getList(final String listProperty); final Map<String, String> getItemMap(final String basePropertyName); final boolean propertyEnabled(final String property); }### Answer:
@Test public final void testGetItemMapNullParameter() throws Exception { Assert.assertEquals( getResourceProperties().getItemMap(null), EMPTY_ITEM_MAP ); }
@Test public final void testGetItemMapNonexistentParameter() throws Exception { Assert.assertEquals( getResourceProperties().getItemMap("list.items.fake_item"), EMPTY_ITEM_MAP ); }
@Test public final void testGetItemMap() throws Exception { Map<String, String> itemMap = getResourceProperties(). getItemMap("list.items.item_one"); Assert.assertNotNull(itemMap); Assert.assertEquals(itemMap.get("size"), "small"); Assert.assertEquals(itemMap.get("priority"), "high"); } |
### Question:
ResourceProperties extends Properties { public final List<String> getList(final String listProperty) { List<String> list = new ArrayList<>(); if (listProperty == null) { return list; } String itemNames = getProperty(listProperty); if (itemNames == null) { return list; } itemNames = itemNames.trim(); if (itemNames.length() == 0) { return list; } list.addAll(Arrays.asList(itemNames.split("\\s*,\\s*"))); return list; } ResourceProperties(); @SuppressFBWarnings( value = "UI_INHERITANCE_UNSAFE_GETRESOURCE", justification = "Not a problem since resourceName should be given" + "relative to root of classpath") ResourceProperties(final String resourceName); final Map<String, Map<String, String>> getItems(
final String listProperty); final List<String> getList(final String listProperty); final Map<String, String> getItemMap(final String basePropertyName); final boolean propertyEnabled(final String property); }### Answer:
@Test public final void testGetList() throws Exception { List<String> itemList = getResourceProperties().getList(LIST_PROP); Assert.assertNotNull(itemList); Assert.assertEquals(itemList.get(0), "item_one"); Assert.assertEquals(itemList.get(1), "item_two"); }
@Test public final void testGetListTrim() throws Exception { List<String> itemList = getResourceProperties() .getList("list.items.spaces"); Assert.assertNotNull(itemList); Assert.assertEquals(itemList.get(0), "item_one"); Assert.assertEquals(itemList.get(1), "item_two"); Assert.assertEquals(itemList.get(2), "item_three"); } |
### Question:
IMAReport extends Report { public IMAReport() { imaRecords = new LinkedHashSet<>(); index = 0; } IMAReport(); @Override final String getReportType(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); @JsonIgnore Set<IMAMeasurementRecord> getRecords(); final void addRecord(final IMAMeasurementRecord record); final boolean removeRecord(final IMAMeasurementRecord record); final boolean isFullReport(); int getRecordCount(); }### Answer:
@Test public final void imaReportTest() { new IMAReport(); } |
### Question:
ResourceProperties extends Properties { public final boolean propertyEnabled(final String property) { return "true".equalsIgnoreCase((String) get(property)); } ResourceProperties(); @SuppressFBWarnings( value = "UI_INHERITANCE_UNSAFE_GETRESOURCE", justification = "Not a problem since resourceName should be given" + "relative to root of classpath") ResourceProperties(final String resourceName); final Map<String, Map<String, String>> getItems(
final String listProperty); final List<String> getList(final String listProperty); final Map<String, String> getItemMap(final String basePropertyName); final boolean propertyEnabled(final String property); }### Answer:
@Test public final void testPropertyEnabled() throws Exception { ResourceProperties props = getResourceProperties(); Assert.assertEquals(props.propertyEnabled("testEnabled.one"), true); Assert.assertEquals(props.propertyEnabled("testEnabled.two"), true); Assert.assertEquals(props.propertyEnabled("testEnabled.three"), false); Assert.assertEquals(props.propertyEnabled("testEnabled.four"), false); Assert.assertEquals(props.propertyEnabled("testEnabled.five"), false); Assert.assertEquals(props.propertyEnabled("testEnabled.dne"), false); } |
### Question:
HIRSClientProperties extends ResourceProperties { public final Map<String, String> getMainAppraiserConfig() { try { return this.getAppraiserConfigurationList().get(0); } catch (IndexOutOfBoundsException e) { return new HashMap<>(); } } HIRSClientProperties(); HIRSClientProperties(final String resourceName); Map<String, Map<String, String>> getAppraiserConfigs(); final Map<String, String> getMainAppraiserConfig(); final Map<String, String> getAppraiserConfig(final String appraiserHostname); List<Map<String, String>> getAppraiserConfigurationList(); static final String DEFAULT_PROPERTY_FILENAME; static final String TPM_ENABLED; static final String IMA_ENABLED; static final String DEVICE_ENABLED; static final String APPRAISER_LIST; static final String APPRAISER_URL; static final String APPRAISER_TRUSTSTORE; static final String APPRAISER_TRUSTSTORE_PASSWORD; static final String APPRAISER_IDENTITY_UUID; static final String APPRAISER_IDENTITY_AUTH_MODE; static final String APPRAISER_IDENTITY_AUTH_VALUE; static final String APPRAISER_IDENTITY_CERT; static final String GOLDEN_BASELINE_PORTAL_URL; static final String GOLDEN_BASELINE_DEFAULT_NAME; }### Answer:
@Test public final void testGetSingleAppraiserEmptyFile() throws IOException { HIRSClientProperties prop = getEmptyHIRSClientProps(); Assert.assertEquals( prop.getMainAppraiserConfig(), new HashMap<String, String>() ); }
@Test public final void testGetSingleAppraiserConfig() throws IOException { HIRSClientProperties prop = getHIRSClientProps(); Assert.assertEquals( prop.getMainAppraiserConfig().get( HIRSClientProperties.APPRAISER_TRUSTSTORE_PASSWORD ), "password" ); } |
### Question:
HIRSClientProperties extends ResourceProperties { public Map<String, Map<String, String>> getAppraiserConfigs() { return getItems(APPRAISER_LIST); } HIRSClientProperties(); HIRSClientProperties(final String resourceName); Map<String, Map<String, String>> getAppraiserConfigs(); final Map<String, String> getMainAppraiserConfig(); final Map<String, String> getAppraiserConfig(final String appraiserHostname); List<Map<String, String>> getAppraiserConfigurationList(); static final String DEFAULT_PROPERTY_FILENAME; static final String TPM_ENABLED; static final String IMA_ENABLED; static final String DEVICE_ENABLED; static final String APPRAISER_LIST; static final String APPRAISER_URL; static final String APPRAISER_TRUSTSTORE; static final String APPRAISER_TRUSTSTORE_PASSWORD; static final String APPRAISER_IDENTITY_UUID; static final String APPRAISER_IDENTITY_AUTH_MODE; static final String APPRAISER_IDENTITY_AUTH_VALUE; static final String APPRAISER_IDENTITY_CERT; static final String GOLDEN_BASELINE_PORTAL_URL; static final String GOLDEN_BASELINE_DEFAULT_NAME; }### Answer:
@Test public final void testGetAppraiserConfigsEmpty() throws IOException { HIRSClientProperties prop = getEmptyHIRSClientProps(); Assert.assertEquals( prop.getAppraiserConfigs(), new HashMap<String, Map<String, String>>() ); }
@Test public final void testGetAppraiserConfigs() throws IOException { HIRSClientProperties prop = getHIRSClientProps(); Map<String, Map<String, String>> appraiserConfigs = prop.getAppraiserConfigs(); Assert.assertEquals(appraiserConfigs.size(), 1); Assert.assertNotNull(appraiserConfigs.get(APPRAISER_NAME)); Assert.assertEquals( appraiserConfigs.get(APPRAISER_NAME).get( HIRSClientProperties.APPRAISER_TRUSTSTORE_PASSWORD ), "password" ); } |
### Question:
CompositeAlertService implements AlertService { public final void alert(final Alert alert) { LOGGER.debug("Sending alerts to all Managed Alert Services"); alertManager.saveAlert(alert); for (ManagedAlertService currentService : alertServices) { if (currentService.isEnabled()) { currentService.alert(alert); } } } final void alert(final Alert alert); final void alertSummary(final ReportSummary summary); }### Answer:
@Test @SuppressFBWarnings( value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", justification = "These method calls are made for verification purposes with Mockito" ) public final void testAlert() { Alert alert = mock(Alert.class); when(enabledService.isEnabled()).thenReturn(true); when(disabledService.isEnabled()).thenReturn(false); doNothing().when(enabledService).alert(any(Alert.class)); alertService.alert(alert); verify(enabledService).isEnabled(); verify(disabledService).isEnabled(); verify(alertManager).saveAlert(alert); verify(enabledService).alert(alert); verifyNoMoreInteractions(alert, enabledService, disabledService); } |
### Question:
CompositeAlertService implements AlertService { public final void alertSummary(final ReportSummary summary) { LOGGER.debug("Sending alert summaries to all Managed Alert Services"); for (ManagedAlertService currentService : alertServices) { if (currentService.isEnabled()) { currentService.alertSummary(summary); } } } final void alert(final Alert alert); final void alertSummary(final ReportSummary summary); }### Answer:
@Test @SuppressFBWarnings( value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", justification = "These method calls are made for verification purposes with Mockito" ) public final void testAlertSummary() { ReportSummary reportSummary = mock(ReportSummary.class); when(enabledService.isEnabled()).thenReturn(true); when(disabledService.isEnabled()).thenReturn(false); doNothing().when(enabledService).alertSummary(any(ReportSummary.class)); alertService.alertSummary(reportSummary); verify(enabledService).isEnabled(); verify(disabledService).isEnabled(); verify(enabledService).alertSummary(reportSummary); verifyNoMoreInteractions(reportSummary, enabledService, disabledService); } |
### Question:
IMAReport extends Report { public final String getBootcycleId() { return this.bootcycleId; } IMAReport(); @Override final String getReportType(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); @JsonIgnore Set<IMAMeasurementRecord> getRecords(); final void addRecord(final IMAMeasurementRecord record); final boolean removeRecord(final IMAMeasurementRecord record); final boolean isFullReport(); int getRecordCount(); }### Answer:
@Test public final void getDefaultBootcycleId() { final IMAReport report = new IMAReport(); Assert.assertEquals(report.getBootcycleId(), null); }
@Test public final void marshalUnmarshalTest() throws Exception { final IMAReport imaReport = getTestReport(); final String xml = getXMLFromReport(imaReport); final IMAReport imaReportFromXML = getReportFromXML(xml); Assert.assertEquals(imaReportFromXML.getBootcycleId(), imaReport.getBootcycleId()); } |
### Question:
SpacewalkPackage extends RPMRepoPackage { public static SpacewalkPackage buildSpacewalkPackage(final Map<String, Object> packageMap, final Repository sourceRepository) throws IllegalArgumentException { if (null == packageMap) { throw new NullPointerException("packageMap is null"); } if (null == sourceRepository) { throw new NullPointerException("sourceRepository is null"); } String name = tryGet(packageMap, "name").toString(); String version = tryGet(packageMap, "version").toString(); String release = tryGet(packageMap, "release").toString(); String architecture = tryGet(packageMap, "arch_label").toString(); int spacewalkPackageId = (int) tryGet(packageMap, "id"); return new SpacewalkPackage(name, version, release, architecture, sourceRepository, spacewalkPackageId); } protected SpacewalkPackage(); SpacewalkPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository,
final int spacewalkPackageId); static SpacewalkPackage buildSpacewalkPackage(final Map<String, Object> packageMap,
final Repository sourceRepository); int getSpacewalkPackageId(); }### Answer:
@Test( expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*packageMap.*null*") public void exceptionWithNullMap() { SpacewalkPackage.buildSpacewalkPackage(null, new TestRepository("zzz")); }
@Test( expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*sourceRepository.*null*") public void exceptionWithNullRepository() { SpacewalkPackage.buildSpacewalkPackage(validPackageMap, null); }
@Test( expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = ".*version*") public void parseInvalidPackageMap() { Map<String, Object> insufficientMap = new HashMap<String, Object>(validPackageMap); insufficientMap.remove("version"); SpacewalkPackage.buildSpacewalkPackage(insufficientMap, new TestRepository("zzz")); } |
### Question:
IMAReport extends Report { public final void setIndex(final int index) { if (index < 0) { final String msg = "index cannot be less than zero"; LOGGER.warn(msg); throw new IllegalArgumentException(msg); } this.index = index; } IMAReport(); @Override final String getReportType(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); @JsonIgnore Set<IMAMeasurementRecord> getRecords(); final void addRecord(final IMAMeasurementRecord record); final boolean removeRecord(final IMAMeasurementRecord record); final boolean isFullReport(); int getRecordCount(); }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public final void setInvalidIndex() { final IMAReport report = new IMAReport(); final int invalidIndex = -1; report.setIndex(invalidIndex); } |
### Question:
RPMRepoPackage extends RepoPackage { public static boolean isRpmFilename(final String filename) { return RPM_FILENAME.matcher(filename).matches(); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testIsRpmFilename() { Assert.assertTrue(RPMRepoPackage.isRpmFilename(RPM_FILENAME)); Assert.assertFalse(RPMRepoPackage.isRpmFilename(INVALID_RPM_FILENAME)); Assert.assertFalse(RPMRepoPackage.isRpmFilename(NOT_AN_RPM_FILENAME)); } |
### Question:
RPMRepoPackage extends RepoPackage { public static String parseRPMCompleteVersion(final String filename) { if (!isRpmFilename(filename)) { return null; } return String.format("%s-%s.%s", parseVersion(filename), parseRelease(filename), parseArchitecture(filename) ); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testParseRPMCompleteVersion() { Assert.assertEquals(RPMRepoPackage.parseRPMCompleteVersion(RPM_FILENAME), RPM_COMPLETE_VER); Assert.assertNull(RPMRepoPackage.parseRPMCompleteVersion(INVALID_RPM_FILENAME)); Assert.assertNull(RPMRepoPackage.parseRPMCompleteVersion(NOT_AN_RPM_FILENAME)); } |
### Question:
RPMRepoPackage extends RepoPackage { public static String parseName(final String filename) { return parseItem(filename, "name"); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testParseName() { Assert.assertEquals(RPMRepoPackage.parseName(RPM_FILENAME), RPM_NAME); Assert.assertNull(RPMRepoPackage.parseName(INVALID_RPM_FILENAME)); Assert.assertNull(RPMRepoPackage.parseName(NOT_AN_RPM_FILENAME)); } |
### Question:
RPMRepoPackage extends RepoPackage { public static String parseVersion(final String filename) { return parseItem(filename, "version"); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testParseVersion() { Assert.assertEquals(RPMRepoPackage.parseVersion(RPM_FILENAME), RPM_VER); Assert.assertNull(RPMRepoPackage.parseVersion(INVALID_RPM_FILENAME)); Assert.assertNull(RPMRepoPackage.parseVersion(NOT_AN_RPM_FILENAME)); } |
### Question:
IMAReport extends Report { public final void addRecord(final IMAMeasurementRecord record) { if (record == null) { LOGGER.error("null record"); throw new NullPointerException("record"); } imaRecords.add(record); LOGGER.debug("record added: {}", record); } IMAReport(); @Override final String getReportType(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); @JsonIgnore Set<IMAMeasurementRecord> getRecords(); final void addRecord(final IMAMeasurementRecord record); final boolean removeRecord(final IMAMeasurementRecord record); final boolean isFullReport(); int getRecordCount(); }### Answer:
@Test public final void addRecord() { IMAReport report = new IMAReport(); IMAMeasurementRecord record; record = getTestRecord(DEFAULT_PATH, DEFAULT_DIGEST); report.addRecord(record); Set<IMAMeasurementRecord> records = report.getRecords(); Set<IMAMeasurementRecord> expectedRecords = new LinkedHashSet<>(); expectedRecords.add(record); Assert.assertEquals(records, expectedRecords); }
@Test(expectedExceptions = NullPointerException.class) public final void addNullRecord() { IMAReport report = new IMAReport(); report.addRecord(null); } |
### Question:
RPMRepoPackage extends RepoPackage { public static String parseRelease(final String filename) { return parseItem(filename, "release"); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testParseRelease() { Assert.assertEquals(RPMRepoPackage.parseRelease(RPM_FILENAME), RPM_REL); Assert.assertNull(RPMRepoPackage.parseRelease(INVALID_RPM_FILENAME)); Assert.assertNull(RPMRepoPackage.parseRelease(NOT_AN_RPM_FILENAME)); } |
### Question:
RPMRepoPackage extends RepoPackage { public static String parseArchitecture(final String filename) { return parseItem(filename, "architecture"); } RPMRepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RPMRepoPackage(); final String getRPMIdentifier(); static String parseRPMCompleteVersion(final String filename); static String parseName(final String filename); static String parseVersion(final String filename); static String parseRelease(final String filename); static String parseArchitecture(final String filename); static boolean isRpmFilename(final String filename); }### Answer:
@Test public void testParseArchitecture() { Assert.assertEquals(RPMRepoPackage.parseArchitecture(RPM_FILENAME), RPM_ARCH); Assert.assertNull(RPMRepoPackage.parseArchitecture(INVALID_RPM_FILENAME)); Assert.assertNull(RPMRepoPackage.parseArchitecture(NOT_AN_RPM_FILENAME)); } |
### Question:
RepoPackage { public final String getName() { return name; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetName() { Assert.assertEquals(repoPackage.getName(), NAME); } |
### Question:
RepoPackage { public final String getVersion() { return version; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetVersion() { Assert.assertEquals(repoPackage.getVersion(), VERSION); } |
### Question:
RepoPackage { public final String getRelease() { return release; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetRelease() { Assert.assertEquals(repoPackage.getRelease(), RELEASE); } |
### Question:
RepoPackage { public final String getArchitecture() { return architecture; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetArchitecture() { Assert.assertEquals(repoPackage.getArchitecture(), ARCHITECTURE); } |
### Question:
RepoPackage { public final Repository<?> getSourceRepository() { return sourceRepository; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetSourceRepository() { Assert.assertEquals(repoPackage.getSourceRepository(), REPOSITORY); } |
### Question:
RepoPackage { public final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords, final Digest packageMeasurement) { if (packageRecords == null) { throw new IllegalArgumentException("Measurements cannot be null."); } if (packageMeasurement == null) { throw new IllegalArgumentException("Package measurement cannot be null."); } if (!measured) { this.packageRecords = new HashSet<>(packageRecords); this.packageMeasurement = packageMeasurement; measured = true; measurementDate = new Date(); } else { throw new IllegalStateException("RepoPackage measurements already set."); } } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testSetMeasurements() throws UnsupportedEncodingException { repoPackage.setAllMeasurements(new HashSet<IMABaselineRecord>(), getTestDigest()); }
@Test(expectedExceptions = RuntimeException.class) public final void testSetMeasurementsTwice() throws UnsupportedEncodingException { repoPackage.setAllMeasurements(new HashSet<IMABaselineRecord>(), getTestDigest()); repoPackage.setAllMeasurements(new HashSet<IMABaselineRecord>(), getTestDigest()); } |
### Question:
RepoPackage { public final Set<IMABaselineRecord> getPackageRecords() { if (!measured) { throw new IllegalStateException("Package measurements not yet set."); } return new HashSet<>(packageRecords); } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test(expectedExceptions = RuntimeException.class) public final void testGetPackageRecordsWithoutBeingSet() { repoPackage.getPackageRecords(); } |
### Question:
RepoPackage { public final boolean isMeasured() { return measured; } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testIsMeasured() throws UnsupportedEncodingException { Assert.assertFalse(repoPackage.isMeasured()); repoPackage.setAllMeasurements(new HashSet<IMABaselineRecord>(), getTestDigest()); Assert.assertTrue(repoPackage.isMeasured()); } |
### Question:
RepoPackage { public final Date getMeasurementDate() { if (measurementDate == null) { return null; } return new Date(measurementDate.getTime()); } RepoPackage(final String name, final String version, final String release,
final String architecture, final Repository sourceRepository); protected RepoPackage(); final String getName(); final String getVersion(); final String getRelease(); final String getArchitecture(); final Repository<?> getSourceRepository(); final void setAllMeasurements(final Set<IMABaselineRecord> packageRecords,
final Digest packageMeasurement); final Set<IMABaselineRecord> getPackageRecords(); final Digest getPackageMeasurement(); final boolean isMeasured(); final Date getMeasurementDate(); final UUID getId(); @Override final boolean equals(final Object o); @Override final int hashCode(); @Override final String toString(); static final String PACKAGE_RECORDS_FIELD; }### Answer:
@Test public final void testGetMeasurementDate() throws UnsupportedEncodingException { repoPackage.setAllMeasurements(new HashSet<IMABaselineRecord>(), getTestDigest()); Assert.assertNotNull(repoPackage.getMeasurementDate()); }
@Test public final void testGetMeasurementDateWithoutBeingSet() { Assert.assertNull(repoPackage.getMeasurementDate()); } |
### Question:
YumRepository extends RPMRepository<RPMRepoPackage> { public final URL getMirrorListUrl() { return mirrorListUrl; } YumRepository(final String name,
final URL mirrorListUrl,
final URL baseUrl,
final boolean gpgCheck,
final String gpgKey); YumRepository(final String name); protected YumRepository(); final URL getMirrorListUrl(); final boolean isGpgCheck(); final String getGpgKey(); @Override final Set<RPMRepoPackage> listRemotePackages(); @Override final void measurePackage(final RPMRepoPackage repoPackage,
final int maxDownloadAttempts); final void measurePackage(final RPMRepoPackage repoPackage); }### Answer:
@Test public void testGetMirrorListUrl() { YumRepository repository; try { repository = new YumRepository(REPO_NAME, new URL(fullUrlPath), null, GPG_CHECK, null); } catch (Exception e) { LOGGER.error("unexpected exception", e); throw new RuntimeException("unexpected exception", e); } Assert.assertEquals(repository.getMirrorListUrl().toString(), fullUrlPath); } |
### Question:
YumRepository extends RPMRepository<RPMRepoPackage> { public final boolean isGpgCheck() { return gpgCheck; } YumRepository(final String name,
final URL mirrorListUrl,
final URL baseUrl,
final boolean gpgCheck,
final String gpgKey); YumRepository(final String name); protected YumRepository(); final URL getMirrorListUrl(); final boolean isGpgCheck(); final String getGpgKey(); @Override final Set<RPMRepoPackage> listRemotePackages(); @Override final void measurePackage(final RPMRepoPackage repoPackage,
final int maxDownloadAttempts); final void measurePackage(final RPMRepoPackage repoPackage); }### Answer:
@Test public void testIsGpgCheck() { Assert.assertEquals(repo.isGpgCheck(), GPG_CHECK); } |
### Question:
YumRepository extends RPMRepository<RPMRepoPackage> { public final String getGpgKey() { return gpgKey; } YumRepository(final String name,
final URL mirrorListUrl,
final URL baseUrl,
final boolean gpgCheck,
final String gpgKey); YumRepository(final String name); protected YumRepository(); final URL getMirrorListUrl(); final boolean isGpgCheck(); final String getGpgKey(); @Override final Set<RPMRepoPackage> listRemotePackages(); @Override final void measurePackage(final RPMRepoPackage repoPackage,
final int maxDownloadAttempts); final void measurePackage(final RPMRepoPackage repoPackage); }### Answer:
@Test public void testGetGpgKey() { YumRepository repository; try { repository = new YumRepository(REPO_NAME, null, baseUrl, GPG_CHECK, GPG_KEY); } catch (Exception e) { LOGGER.error("unexpected exception", e); throw new RuntimeException("unexpected exception", e); } Assert.assertEquals(repository.getGpgKey(), GPG_KEY); } |
### Question:
IMAReport extends Report { @JsonIgnore public Set<IMAMeasurementRecord> getRecords() { return Collections.unmodifiableSet(imaRecords); } IMAReport(); @Override final String getReportType(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); @JsonIgnore Set<IMAMeasurementRecord> getRecords(); final void addRecord(final IMAMeasurementRecord record); final boolean removeRecord(final IMAMeasurementRecord record); final boolean isFullReport(); int getRecordCount(); }### Answer:
@Test public final void getRecords() { IMAReport report = new IMAReport(); IMAMeasurementRecord record; record = getTestRecord(DEFAULT_PATH, DEFAULT_DIGEST); report.addRecord(record); Set<IMAMeasurementRecord> records = report.getRecords(); Set<IMAMeasurementRecord> expectedRecords = new LinkedHashSet<>(); expectedRecords.add(record); Assert.assertEquals(records, expectedRecords); } |
### Question:
JobExecutor { public final void scheduleJob(final Job<?> job) { if (state != State.RUNNING) { throw new IllegalStateException("Cannot schedule new job on a JobExecutor that has" + " been shut down."); } runningJobs.add(job); job.submitTasks(executorService, new Callable<Void>() { @Override public Void call() throws Exception { runningJobs.remove(job); return null; } }); } JobExecutor(); JobExecutor(final int threadCountMultiplier); final void scheduleJob(final Job<?> job); final State getState(); @SuppressFBWarnings( value = "SWL_SLEEP_WITH_LOCK_HELD", justification = "No resources are being consumed or waited on; reentrant threads should" + "remain locked out while .") final synchronized void shutdown(); final void shutdownNow(); }### Answer:
@Test(expectedExceptions = IllegalStateException.class) public final void testGetResultsJobNotFinished() { List<Callable<Void>> tasks = new ArrayList<>(); tasks.add(longTask); Job<Void> job = new Job<>(tasks); jobExecutor.scheduleJob(job); job.getResults(longTask); }
@Test(expectedExceptions = IllegalStateException.class) public final void testGetFailuresJobNotFinished() { List<Callable<Integer>> tasks = new ArrayList<>(); tasks.add(incrementTask); Job<Integer> job = new Job<>(tasks); jobExecutor.scheduleJob(job); job.getFailures(incrementTask); }
@Test(expectedExceptions = IllegalStateException.class) public final void testGetAllFailuresJobNotFinished() { List<Callable<Integer>> tasks = new ArrayList<>(); tasks.add(incrementTask); Job<Integer> job = new Job<>(tasks); jobExecutor.scheduleJob(job); job.getAllFailures(); } |
### Question:
VersionHelper { public static String getVersion() { return getVersion(VERSION_FILENAME); } private VersionHelper(); static String getVersion(); static String getVersion(final String filename); }### Answer:
@Test public void testGetVersionFail() { String actual = VersionHelper.getVersion("somefile"); Assert.assertTrue(actual.startsWith("")); }
@Test public void testGetVersionDefault() { String expected = "Test.Version"; String actual = VersionHelper.getVersion(); Assert.assertEquals(actual, expected); } |
### Question:
RegexFilePathMatcher implements FilePathMatcher { public void setPatterns(final String... patterns) throws IllegalArgumentException { if (ArrayUtils.isEmpty(patterns)) { throw new IllegalArgumentException("a RegexFilePathMatcher needs at least one pattern"); } this.inputPatterns = patterns; this.validator = new RegexValidator(patterns); } RegexFilePathMatcher(final String... inputPatterns); boolean isMatch(final String path); void setPatterns(final String... patterns); }### Answer:
@Test public final void setPatterns() throws Exception { String path1 = "/foo.txt"; String path2 = "/bar.txt"; String patterns1 = "/foo.txt"; String[] patterns2 = {"/foo.txt", "/bar.txt"}; RegexFilePathMatcher matcher = new RegexFilePathMatcher(patterns1); Assert.assertTrue(matcher.isMatch(path1)); Assert.assertFalse(matcher.isMatch(path2)); matcher.setPatterns(patterns2); Assert.assertTrue(matcher.isMatch(path1)); Assert.assertTrue(matcher.isMatch(path2)); } |
### Question:
Functional { public static <T> List<T> select(final Collection<T> items, final Callback<T, Boolean> filter) { List<T> selectedItems = new ArrayList<>(); for (T item : items) { if (filter.call(item)) { selectedItems.add(item); } } return selectedItems; } private Functional(); static List<T> select(final Collection<T> items, final Callback<T, Boolean> filter); }### Answer:
@Test public void testEmptyCollection() { Assert.assertEquals(EMPTY_LIST, Functional.select(EMPTY_LIST, ODD_FILTER)); }
@Test public void testSelectMany() { List<Integer> results = Functional.select(INPUT_LIST, ODD_FILTER); Assert.assertEquals(TWO, results.size()); Assert.assertTrue(results.contains(ONE)); Assert.assertTrue(results.contains(THREE)); }
@Test public void testSelectSingleElement() { List<Integer> results = Functional.select(INPUT_LIST, TWO_FILTER); Assert.assertEquals(ONE, results.size()); Assert.assertTrue(results.contains(TWO)); }
@Test public void testSelectNone() { Assert.assertEquals(EMPTY_LIST, Functional.select(INPUT_LIST, NONE_FILTER)); } |
### Question:
TPMReport extends Report { protected TPMReport() { this.quoteData = null; } protected TPMReport(); TPMReport(final QuoteData quoteData); final QuoteData getQuoteData(); final List<TPMMeasurementRecord> getTPMMeasurementRecords(); final TPMMeasurementRecord getTPMMeasurementRecord(final int pcr); @Override final String getReportType(); }### Answer:
@Test public final void testTPMReport() { new TPMReport(getTestQuoteData()); } |
### Question:
ExecBuilder { public final SynchronousExecResult exec() throws IOException { try { int exitStatus = getExecutor().execute(getCommandLine(), env); return new SynchronousExecResult(stdOut, exitStatus); } catch (ExecuteException e) { throw logFailureAndGetIOException(toString(), e, stdOut, stdErr); } } ExecBuilder(final String command); ExecBuilder(final String command, final boolean handleQuoting); final ExecBuilder args(final String... args); final ExecBuilder timeout(final long timeout); final ExecBuilder stdIn(final InputStream stdIn); final ExecBuilder stdOutAndErr(final OutputStream stdOut, final OutputStream stdErr); final ExecBuilder workingDirectory(final Path workingDirectory); final ExecBuilder environment(final Map<String, String> env); final ExecBuilder exitValues(final int[] exitValues); final SynchronousExecResult exec(); final AsynchronousExecResult asyncExec(); @Override final String toString(); }### Answer:
@Test(expectedExceptions = IOException.class) public final void testSyncExecNonexistentCommand() throws Exception { new ExecBuilder("/bin/veryfakeprogram").exec(); } |
### Question:
ExecBuilder { public final AsynchronousExecResult asyncExec() throws IOException { DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); getExecutor().execute(getCommandLine(), env, resultHandler); return new AsynchronousExecResult(resultHandler, stdOut, stdErr, toString()); } ExecBuilder(final String command); ExecBuilder(final String command, final boolean handleQuoting); final ExecBuilder args(final String... args); final ExecBuilder timeout(final long timeout); final ExecBuilder stdIn(final InputStream stdIn); final ExecBuilder stdOutAndErr(final OutputStream stdOut, final OutputStream stdErr); final ExecBuilder workingDirectory(final Path workingDirectory); final ExecBuilder environment(final Map<String, String> env); final ExecBuilder exitValues(final int[] exitValues); final SynchronousExecResult exec(); final AsynchronousExecResult asyncExec(); @Override final String toString(); }### Answer:
@Test(expectedExceptions = IOException.class) public final void testAsyncExecNonexistentCommand() throws Exception { AsynchronousExecResult result = new ExecBuilder("/bin/veryfakeprogram").asyncExec(); result.waitFor(); Assert.assertTrue(result.isFinished()); Assert.assertFalse(result.isSuccessful()); result.throwExceptionIfFailed(); } |
### Question:
ExecPipe { public AsynchronousExecResult exec() throws IOException { PipedInputStream inputStream = null; PipedOutputStream outputStream = null; for (int i = 0; i < builders.size(); i++) { ExecBuilder builder = builders.get(i); if (i != 0) { builder.stdIn(inputStream); } if (i != builders.size() - 1) { outputStream = new PipedOutputStream(); builder.stdOutAndErr(outputStream, null); inputStream = new PipedInputStream(outputStream); } } AsynchronousExecResult lastAsyncResult = null; for (ExecBuilder builder : builders) { lastAsyncResult = builder.asyncExec(); } return lastAsyncResult; } ExecPipe(final ExecBuilder... execBuilders); ExecPipe(final List<ExecBuilder> execBuilders); AsynchronousExecResult exec(); static ExecPipe pipeOf(final boolean quoteArgs, final String[]... commands); @Override String toString(); }### Answer:
@Test public void testOneStagePipe() throws IOException, InterruptedException { ExecPipe pipe = new ExecPipe( new ExecBuilder("echo").args("test") ); AsynchronousExecResult result = pipe.exec(); result.waitFor(); Assert.assertTrue(result.isSuccessful()); Assert.assertEquals(result.getStdOutResult(), "test\n"); }
@Test public void testSimplePipe() throws IOException, InterruptedException { ExecPipe pipe = new ExecPipe( new ExecBuilder("echo").args("test"), new ExecBuilder("grep").args("te"), new ExecBuilder("wc").args("-l") ); AsynchronousExecResult result = pipe.exec(); result.waitFor(); Assert.assertTrue(result.isSuccessful()); Assert.assertEquals(result.getStdOutResult(), "1\n"); } |
### Question:
ExecPipe { public static ExecPipe pipeOf(final boolean quoteArgs, final String[]... commands) { List<ExecBuilder> builders = new ArrayList<>(); for (String[] command : commands) { List<String> commandParts = Arrays.asList(command); ExecBuilder builder = new ExecBuilder(commandParts.get(0), quoteArgs); List<String> args = commandParts.subList(1, commandParts.size()); String[] argsArr = new String[args.size()]; builder.args(args.toArray(argsArr)); builders.add(builder); } return new ExecPipe(builders); } ExecPipe(final ExecBuilder... execBuilders); ExecPipe(final List<ExecBuilder> execBuilders); AsynchronousExecResult exec(); static ExecPipe pipeOf(final boolean quoteArgs, final String[]... commands); @Override String toString(); }### Answer:
@Test public void testPipeOf() throws IOException, InterruptedException { AsynchronousExecResult result = ExecPipe.pipeOf(false, new String[][]{ {"echo", "test"}, {"grep", "te"}, {"wc", "-l"} }).exec(); result.waitFor(); Assert.assertTrue(result.isSuccessful()); Assert.assertEquals(result.getStdOutResult(), "1\n"); } |
### Question:
SynchronousExecResult implements ExecResult { @Override public String getStdOutResult() { return stdOutResult; } SynchronousExecResult(final OutputStream stdOut, final int exitStatus); @Override boolean isFinished(); @Override boolean isSuccessful(); @Override String getStdOutResult(); @Override final int getExitStatus(); @Override final String toString(); }### Answer:
@Test public final void testGetOutput() { Assert.assertEquals( new SynchronousExecResult(getTestOutputStream(), 0).getStdOutResult(), "Success" ); }
@Test public final void testGetNullOutput() { Assert.assertNull(new SynchronousExecResult(null, 0).getStdOutResult()); } |
### Question:
SynchronousExecResult implements ExecResult { @Override public final int getExitStatus() { return exitStatus; } SynchronousExecResult(final OutputStream stdOut, final int exitStatus); @Override boolean isFinished(); @Override boolean isSuccessful(); @Override String getStdOutResult(); @Override final int getExitStatus(); @Override final String toString(); }### Answer:
@Test public final void testGetExitStatus() { Assert.assertEquals( new SynchronousExecResult(getTestOutputStream(), EXIT_STATUS).getExitStatus(), EXIT_STATUS ); } |
### Question:
HexUtils { public static byte[] hexStringToByteArray(final String s) { int sizeInt = s.length() / 2; byte[] returnArray = new byte[sizeInt]; String byteVal; for (int i = 0; i < sizeInt; i++) { int index = 2 * i; byteVal = s.substring(index, index + 2); returnArray[i] = (byte) (Integer.parseInt(byteVal, HEX_BASIS)); } return returnArray; } private HexUtils(); static byte[] hexStringToByteArray(final String s); static String byteArrayToHexString(final byte[] b); static Integer hexToInt(final String s); static byte[] subarray(final byte[] b, final int start, final int end); static byte[] leReverseByte(final byte[] in); static int leReverseInt(final byte[] in); static long bytesToLong(final byte[] bytes); static final int HEX_BASIS; static final int FF_BYTE; }### Answer:
@Test public void testHexStringToByteArray() { String s = "abcd1234"; byte[] target = {-85, -51, 18, 52}; byte[] b = HexUtils.hexStringToByteArray(s); Assert.assertEquals(b, target); } |
### Question:
HexUtils { public static String byteArrayToHexString(final byte[] b) { StringBuilder sb = new StringBuilder(); String returnStr = ""; for (int i = 0; i < b.length; i++) { String singleByte = Integer.toHexString(b[i] & FF_BYTE); if (singleByte.length() != 2) { singleByte = "0" + singleByte; } returnStr = sb.append(singleByte).toString(); } return returnStr; } private HexUtils(); static byte[] hexStringToByteArray(final String s); static String byteArrayToHexString(final byte[] b); static Integer hexToInt(final String s); static byte[] subarray(final byte[] b, final int start, final int end); static byte[] leReverseByte(final byte[] in); static int leReverseInt(final byte[] in); static long bytesToLong(final byte[] bytes); static final int HEX_BASIS; static final int FF_BYTE; }### Answer:
@Test public void testByteArrayToHexString() { String target = "abcd1234"; byte[] b = {-85, -51, 18, 52}; String s = HexUtils.byteArrayToHexString(b); Assert.assertEquals(s, target); }
@Test public void testByteArrayToHexStringConditional() { String target = "abcd0100"; byte[] b = {-85, -51, 1, 0}; String s = HexUtils.byteArrayToHexString(b); Assert.assertEquals(s, target); } |
### Question:
TPMReport extends Report { public final List<TPMMeasurementRecord> getTPMMeasurementRecords() { return this.quoteData.getQuote2().getQuoteInfo2().getPcrInfoShort() .getPcrComposite().getPcrValueList(); } protected TPMReport(); TPMReport(final QuoteData quoteData); final QuoteData getQuoteData(); final List<TPMMeasurementRecord> getTPMMeasurementRecords(); final TPMMeasurementRecord getTPMMeasurementRecord(final int pcr); @Override final String getReportType(); }### Answer:
@Test public final void marshalUnmarshalTest() throws JAXBException { TPMReport tpmReport = new TPMReport(getTestQuoteData()); String xml = getXMLFromReport(tpmReport); TPMReport tpmReportFromXML = getReportFromXML(xml); Assert.assertEquals(1, tpmReportFromXML.getTPMMeasurementRecords().size()); } |
### Question:
HexUtils { public static Integer hexToInt(final String s) { Integer i = Integer.parseInt(s, HEX_BASIS); return i; } private HexUtils(); static byte[] hexStringToByteArray(final String s); static String byteArrayToHexString(final byte[] b); static Integer hexToInt(final String s); static byte[] subarray(final byte[] b, final int start, final int end); static byte[] leReverseByte(final byte[] in); static int leReverseInt(final byte[] in); static long bytesToLong(final byte[] bytes); static final int HEX_BASIS; static final int FF_BYTE; }### Answer:
@Test public void testHexToInt() { String s = "ff"; Integer i = HexUtils.hexToInt(s); Assert.assertEquals((int) i, HexUtils.FF_BYTE); } |
### Question:
HexUtils { public static byte[] subarray(final byte[] b, final int start, final int end) { byte[] copy = new byte[end - start + 1]; System.arraycopy(b, start, copy, 0, end - start + 1); return copy; } private HexUtils(); static byte[] hexStringToByteArray(final String s); static String byteArrayToHexString(final byte[] b); static Integer hexToInt(final String s); static byte[] subarray(final byte[] b, final int start, final int end); static byte[] leReverseByte(final byte[] in); static int leReverseInt(final byte[] in); static long bytesToLong(final byte[] bytes); static final int HEX_BASIS; static final int FF_BYTE; }### Answer:
@Test public void testSubarray() { byte[] b = {-85, -51, 18, 52}; byte[] target = {-51, 18}; byte[] sub = HexUtils.subarray(b, 1, 2); Assert.assertEquals(sub, target); } |
### Question:
CollectionHelper { public static <T> HashSet<T> getHashSetOf( final Class<T> clazz, final Collection<?> collection ) { return getCollectionOf(clazz, collection, new HashSet<>()); } private CollectionHelper(); static Collection<T> getCollectionOf(
final Class<T> clazz,
final Collection<?> collection
); static ArrayList<T> getArrayListOf(
final Class<T> clazz,
final Collection<?> collection
); static HashSet<T> getHashSetOf(
final Class<T> clazz,
final Collection<?> collection
); static U getCollectionOf(
final Class<T> clazz,
final Collection<?> collection,
final U resultCollection
); }### Answer:
@Test public void testGetSet() { Set<String> casted = CollectionHelper.getHashSetOf(String.class, OBJ_COLLECTION_OF_STRINGS); Assert.assertEquals(casted.size(), EXPECTED_SIZE); } |
### Question:
CollectionHelper { public static <T> ArrayList<T> getArrayListOf( final Class<T> clazz, final Collection<?> collection ) { return getCollectionOf(clazz, collection, new ArrayList<>()); } private CollectionHelper(); static Collection<T> getCollectionOf(
final Class<T> clazz,
final Collection<?> collection
); static ArrayList<T> getArrayListOf(
final Class<T> clazz,
final Collection<?> collection
); static HashSet<T> getHashSetOf(
final Class<T> clazz,
final Collection<?> collection
); static U getCollectionOf(
final Class<T> clazz,
final Collection<?> collection,
final U resultCollection
); }### Answer:
@Test public void testGetList() { List<String> casted = CollectionHelper.getArrayListOf( String.class, OBJ_COLLECTION_OF_STRINGS ); Assert.assertEquals(casted.size(), EXPECTED_SIZE); } |
### Question:
CollectionHelper { public static <T> Collection<T> getCollectionOf( final Class<T> clazz, final Collection<?> collection ) { return getCollectionOf(clazz, collection, new ArrayList<>()); } private CollectionHelper(); static Collection<T> getCollectionOf(
final Class<T> clazz,
final Collection<?> collection
); static ArrayList<T> getArrayListOf(
final Class<T> clazz,
final Collection<?> collection
); static HashSet<T> getHashSetOf(
final Class<T> clazz,
final Collection<?> collection
); static U getCollectionOf(
final Class<T> clazz,
final Collection<?> collection,
final U resultCollection
); }### Answer:
@Test public void testGetCollectionEmpty() { Collection<String> casted = CollectionHelper.getCollectionOf( String.class, Collections.EMPTY_LIST ); Assert.assertEquals(casted, Collections.EMPTY_LIST); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testHomogenousCollection() { Collection<Object> notAllStrings = Arrays.asList("one", "two", new HashMap<>()); CollectionHelper.getCollectionOf(String.class, notAllStrings); }
@Test public void testGetCollectionCustom() { TreeSet<String> casted = CollectionHelper.getCollectionOf( String.class, OBJ_COLLECTION_OF_STRINGS, new TreeSet<>() ); Assert.assertEquals(casted.size(), EXPECTED_SIZE); Assert.assertEquals(casted.getClass(), TreeSet.class); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testGetCollectionCustomOnNonemptyResultCollection() { CollectionHelper.getCollectionOf( String.class, OBJ_COLLECTION_OF_STRINGS, Collections.singletonList("test") ); } |
### Question:
IMAReportRequest implements ReportRequest { public String getBootcycleId() { return bootcycleId; } IMAReportRequest(); IMAReportRequest(final String bootcycleId, final int i); @Override Class<? extends Report> getReportType(); String getBootcycleId(); int getIMAIndex(); @Override String toString(); }### Answer:
@Test public final void getBootcycleId() { final IMAReportRequest imaReportRequest = new IMAReportRequest(BOOT_ID, INDEX); Assert.assertEquals(imaReportRequest.getBootcycleId(), BOOT_ID); } |
### Question:
IMAReportRequest implements ReportRequest { public int getIMAIndex() { return index; } IMAReportRequest(); IMAReportRequest(final String bootcycleId, final int i); @Override Class<? extends Report> getReportType(); String getBootcycleId(); int getIMAIndex(); @Override String toString(); }### Answer:
@Test public final void getIMAIndex() { final IMAReportRequest imaReportRequest = new IMAReportRequest(BOOT_ID, INDEX); Assert.assertEquals(imaReportRequest.getIMAIndex(), INDEX); } |
### Question:
IMAReportRequest implements ReportRequest { @Override public Class<? extends Report> getReportType() { return IMAReport.class; } IMAReportRequest(); IMAReportRequest(final String bootcycleId, final int i); @Override Class<? extends Report> getReportType(); String getBootcycleId(); int getIMAIndex(); @Override String toString(); }### Answer:
@Test public final void getReportType() { IMAReportRequest imaReportRequest = new IMAReportRequest(BOOT_ID, FULL); Assert.assertEquals(imaReportRequest.getReportType(), IMAReport.class); } |
### Question:
TPMReportRequest implements ReportRequest { public byte[] getNonce() { return nonce.clone(); } protected TPMReportRequest(); TPMReportRequest(final byte[] nonce, final int mask); @Override Class<? extends Report> getReportType(); int getPcrMask(); byte[] getNonce(); }### Answer:
@Test public final void getNonce() { TPMReportRequest tpmRepReq = new TPMReportRequest(TEST_NONCE, TEST_MASK); Assert.assertEquals(tpmRepReq.getNonce(), TEST_NONCE); } |
### Question:
TPMReportRequest implements ReportRequest { public int getPcrMask() { return pcrMask; } protected TPMReportRequest(); TPMReportRequest(final byte[] nonce, final int mask); @Override Class<? extends Report> getReportType(); int getPcrMask(); byte[] getNonce(); }### Answer:
@Test public final void getPcrMask() { TPMReportRequest tpmRepReq = new TPMReportRequest(TEST_NONCE, TEST_MASK); Assert.assertEquals(tpmRepReq.getPcrMask(), TEST_MASK); } |
### Question:
TPMReportRequest implements ReportRequest { @Override public Class<? extends Report> getReportType() { return TPMReport.class; } protected TPMReportRequest(); TPMReportRequest(final byte[] nonce, final int mask); @Override Class<? extends Report> getReportType(); int getPcrMask(); byte[] getNonce(); }### Answer:
@Test public final void getReportType() { TPMReportRequest tpmRepReq = new TPMReportRequest(TEST_NONCE, TEST_MASK); Assert.assertEquals(tpmRepReq.getReportType(), TPMReport.class); } |
### Question:
SimpleStructBuilder implements StructBuilder { @Override public T build() { T retval = struct; resetStruct(); return retval; } SimpleStructBuilder(final Class<T> clazz); @Override SimpleStructBuilder<T> set(final String field, final String value); @Override SimpleStructBuilder<T> set(final String field, final Number value); @Override SimpleStructBuilder<T> set(final String field, final byte[] value); @Override SimpleStructBuilder<T> set(final String field, final Struct value); @Override T build(); }### Answer:
@Test public final void testBuild() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { TestStruct struct = new SimpleStructBuilder<>(TestStruct.class) .set("testShort", NUMBER) .set("testByte", NUMBER) .set("testEmbeddedStruct", new SimpleStructBuilder<>(TestEmbeddedStruct.class) .set("embeddedShort", NUMBER) .set("embedded", ARRAY) .build()) .set("testVariableStruct", new SimpleStructBuilder<>(TestVariableStruct.class) .set("testArray", ARRAY) .build()) .build(); assertEquals(struct.getTestShort(), NUMBER); assertEquals(struct.getTestByte(), NUMBER); assertEquals(struct.getTestEmbeddedStruct().getEmbeddedShort(), NUMBER); assertEquals(struct.getTestEmbeddedStruct().getEmbedded(), ARRAY); assertEquals(struct.getTestEmbeddedStruct().getEmbeddedSize(), ARRAY.length); assertEquals(struct.getTestVariableStruct().getTestArray(), ARRAY); assertEquals(struct.getTestVariableStructLength(), ARRAY.length); } |
### Question:
RestfulClientProvisioner implements ClientProvisioner { void takeOwnership() { tpm.takeOwnership(); } @EventListener @SuppressFBWarnings(value = "DM_EXIT", justification = "need to exit app from spring managed class here") final void handleContextInitialized(final ContextRefreshedEvent event); @Override boolean provision(); }### Answer:
@Test public void testTakeOwnership() { provisioner.takeOwnership(); verify(mockTpm).takeOwnership(); } |
### Question:
RestfulClientProvisioner implements ClientProvisioner { RSAPublicKey getACAPublicKey() { ResponseEntity<byte[]> response = restTemplate.getForEntity(acaPublicKeyURL, byte[].class); try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(response.getBody()); return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(keySpec); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new ProvisioningException("Encountered error while create Public Key from " + "ACA response: " + e.getMessage(), e); } } @EventListener @SuppressFBWarnings(value = "DM_EXIT", justification = "need to exit app from spring managed class here") final void handleContextInitialized(final ContextRefreshedEvent event); @Override boolean provision(); }### Answer:
@Test @SuppressWarnings("unchecked") public void testGetACAPublicKey() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); ReflectionTestUtils.setField(provisioner, "acaPublicKeyURL", ACA_KEY_URL); ResponseEntity responseEntity = mock(ResponseEntity.class); when(mockRestTemplate.getForEntity(ACA_KEY_URL, byte[].class)).thenReturn(responseEntity); when(responseEntity.getBody()).thenReturn(publicKey.getEncoded()); RSAPublicKey result = provisioner.getACAPublicKey(); assertEquals(result.getPublicExponent(), publicKey.getPublicExponent()); assertEquals(result.getModulus(), publicKey.getModulus()); verify(mockRestTemplate).getForEntity(ACA_KEY_URL, byte[].class); verify(responseEntity).getBody(); } |
### Question:
RestfulClientProvisioner implements ClientProvisioner { byte[] activateCredential(final IdentityResponseEnvelope response, final String uuid) { byte[] asymmetricContents = response.getAsymmetricContents(); byte[] symmetricContents = structConverter.convert(response.getSymmetricAttestation()); return tpm.activateIdentity(asymmetricContents, symmetricContents, uuid); } @EventListener @SuppressFBWarnings(value = "DM_EXIT", justification = "need to exit app from spring managed class here") final void handleContextInitialized(final ContextRefreshedEvent event); @Override boolean provision(); }### Answer:
@Test public void testActivateCredential() { String uuid = "uuid"; byte[] asymmetricContents = new byte[]{1}; byte[] symmetricContents = new byte[]{2}; byte[] response = new byte[]{3}; IdentityResponseEnvelope envelope = mock(IdentityResponseEnvelope.class); SymmetricAttestation attestation = mock(SymmetricAttestation.class); when(envelope.getAsymmetricContents()).thenReturn(asymmetricContents); when(envelope.getSymmetricAttestation()).thenReturn(attestation); when(mockTpm.activateIdentity(asymmetricContents, symmetricContents, uuid)) .thenReturn(response); when(mockStructConverter.convert(attestation)).thenReturn(symmetricContents); provisioner.activateCredential(envelope, uuid); verify(mockTpm).activateIdentity(asymmetricContents, symmetricContents, uuid); verify(envelope).getAsymmetricContents(); verify(envelope).getSymmetricAttestation(); verify(mockStructConverter).convert(attestation); verifyNoMoreInteractions(envelope, attestation); } |
### Question:
Digest extends AbstractDigest { @Override public DigestAlgorithm getAlgorithm() { return this.algorithm; } Digest(final DigestAlgorithm algorithm, final byte[] digest); Digest(final byte[] digest); protected Digest(); @Override DigestAlgorithm getAlgorithm(); @Override byte[] getDigest(); OptionalDigest asOptionalDigest(); static Digest fromString(final String digest); static final Digest SHA1_ZERO; static final Digest SHA1_OF_NO_DATA; }### Answer:
@Test public final void testGetAlgorithm() { final Digest d = new Digest(DigestAlgorithm.SHA1, getTestDigest(20)); Assert.assertEquals(DigestAlgorithm.SHA1, d.getAlgorithm()); } |
### Question:
Digest extends AbstractDigest { @Override public byte[] getDigest() { return Arrays.copyOf(this.digest, this.digest.length); } Digest(final DigestAlgorithm algorithm, final byte[] digest); Digest(final byte[] digest); protected Digest(); @Override DigestAlgorithm getAlgorithm(); @Override byte[] getDigest(); OptionalDigest asOptionalDigest(); static Digest fromString(final String digest); static final Digest SHA1_ZERO; static final Digest SHA1_OF_NO_DATA; }### Answer:
@Test public final void testGetDigest() { final Digest d = new Digest(DigestAlgorithm.SHA1, getTestDigest(20)); final byte[] digestBytes = d.getDigest(); final byte[] testBytes = getTestDigest(20); Assert.assertTrue(Arrays.equals(testBytes, digestBytes)); digestBytes[0] = (byte) (digestBytes[0] + 1); Assert.assertTrue(Arrays.equals(testBytes, d.getDigest())); Assert.assertFalse(Arrays.equals(digestBytes, d.getDigest())); } |
### Question:
TPMMeasurementRecord extends ExaminableRecord { public TPMMeasurementRecord(final int pcrId, final Digest hash) throws IllegalArgumentException { super(); checkForValidPcrId(pcrId); if (hash == null) { LOGGER.error("null hash value"); throw new NullPointerException("hash"); } this.pcrId = pcrId; this.hash = hash; } TPMMeasurementRecord(final int pcrId, final Digest hash); TPMMeasurementRecord(final int pcrId, final String hash); TPMMeasurementRecord(final int pcrId, final byte[] hash); protected TPMMeasurementRecord(); static void checkForValidPcrId(final int pcrId); int getPcrId(); Digest getHash(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final int MIN_PCR_ID; static final int MAX_PCR_ID; static final int SHA_BYTE_LENGTH; static final int SHA_256_BYTE_LENGTH; }### Answer:
@Test public final void tpmMeasurementRecord() { TPMMeasurementRecord pcrRecord = new TPMMeasurementRecord(0, getDigest(DEFAULT_HASH)); Assert.assertNotNull(pcrRecord); } |
### Question:
TPMMeasurementRecord extends ExaminableRecord { public Digest getHash() { return hash; } TPMMeasurementRecord(final int pcrId, final Digest hash); TPMMeasurementRecord(final int pcrId, final String hash); TPMMeasurementRecord(final int pcrId, final byte[] hash); protected TPMMeasurementRecord(); static void checkForValidPcrId(final int pcrId); int getPcrId(); Digest getHash(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final int MIN_PCR_ID; static final int MAX_PCR_ID; static final int SHA_BYTE_LENGTH; static final int SHA_256_BYTE_LENGTH; }### Answer:
@Test public final void getHash() { TPMMeasurementRecord pcrRecord = new TPMMeasurementRecord(0, getDigest(DEFAULT_HASH)); Assert.assertNotNull(pcrRecord.getHash()); } |
### Question:
TPMMeasurementRecord extends ExaminableRecord { public int getPcrId() { return pcrId; } TPMMeasurementRecord(final int pcrId, final Digest hash); TPMMeasurementRecord(final int pcrId, final String hash); TPMMeasurementRecord(final int pcrId, final byte[] hash); protected TPMMeasurementRecord(); static void checkForValidPcrId(final int pcrId); int getPcrId(); Digest getHash(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final int MIN_PCR_ID; static final int MAX_PCR_ID; static final int SHA_BYTE_LENGTH; static final int SHA_256_BYTE_LENGTH; }### Answer:
@Test public final void getPcrId() { int id; TPMMeasurementRecord pcrRecord = new TPMMeasurementRecord(0, getDigest(DEFAULT_HASH)); id = pcrRecord.getPcrId(); Assert.assertNotNull(id); } |
### Question:
TPMMeasurementRecord extends ExaminableRecord { @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } TPMMeasurementRecord other = (TPMMeasurementRecord) obj; if (!hash.equals(other.hash)) { return false; } if (pcrId != other.pcrId) { return false; } return true; } TPMMeasurementRecord(final int pcrId, final Digest hash); TPMMeasurementRecord(final int pcrId, final String hash); TPMMeasurementRecord(final int pcrId, final byte[] hash); protected TPMMeasurementRecord(); static void checkForValidPcrId(final int pcrId); int getPcrId(); Digest getHash(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final int MIN_PCR_ID; static final int MAX_PCR_ID; static final int SHA_BYTE_LENGTH; static final int SHA_256_BYTE_LENGTH; }### Answer:
@Test public final void testEquals() { TPMMeasurementRecord r1 = getDefaultRecord(); TPMMeasurementRecord r2 = getDefaultRecord(); Assert.assertEquals(r1, r2); Assert.assertEquals(r2, r1); Assert.assertEquals(r1, r1); Assert.assertEquals(r2, r2); } |
### Question:
TPMMeasurementRecord extends ExaminableRecord { public static void checkForValidPcrId(final int pcrId) { if (pcrId < MIN_PCR_ID || pcrId > MAX_PCR_ID) { final String msg = String.format("invalid PCR ID: %d", pcrId); LOGGER.error(msg); throw new IllegalArgumentException(msg); } } TPMMeasurementRecord(final int pcrId, final Digest hash); TPMMeasurementRecord(final int pcrId, final String hash); TPMMeasurementRecord(final int pcrId, final byte[] hash); protected TPMMeasurementRecord(); static void checkForValidPcrId(final int pcrId); int getPcrId(); Digest getHash(); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); static final int MIN_PCR_ID; static final int MAX_PCR_ID; static final int SHA_BYTE_LENGTH; static final int SHA_256_BYTE_LENGTH; }### Answer:
@Test public final void testCheckForValidPcrId() { final int minPcrId = TPMMeasurementRecord.MIN_PCR_ID; final int maxPcrId = TPMMeasurementRecord.MAX_PCR_ID; for (int i = minPcrId; i < maxPcrId; i++) { TPMMeasurementRecord.checkForValidPcrId(i); } }
@Test(expectedExceptions = IllegalArgumentException.class) public final void testCheckForValidPcrIdNegative() { final int pcrId = -1; TPMMeasurementRecord.checkForValidPcrId(pcrId); }
@Test(expectedExceptions = IllegalArgumentException.class) public final void testCheckForValidPcrIdInvalidId() { final int pcrId = 35; TPMMeasurementRecord.checkForValidPcrId(pcrId); } |
### Question:
IntegrityReport extends Report { public IntegrityReport() { reports = new HashSet<>(); } IntegrityReport(); final void addReport(final Report report); final boolean contains(Class<? extends Report> reportType); final Set<Report> getReports(); final void removeReport(final Report report); final T extractReport(final Class<T> reportType); String getDeviceName(); @Override final String getReportType(); }### Answer:
@Test public final void integrityReport() { new IntegrityReport(); } |
### Question:
IntegrityReport extends Report { public final void addReport(final Report report) { if (report == null) { LOGGER.error("report cannot be null"); throw new NullPointerException("report"); } if (reports.add(report)) { LOGGER.debug("Report {} successfully added", report); } else { LOGGER.debug("Report {} already exists in the IntegrityReport", report); } } IntegrityReport(); final void addReport(final Report report); final boolean contains(Class<? extends Report> reportType); final Set<Report> getReports(); final void removeReport(final Report report); final T extractReport(final Class<T> reportType); String getDeviceName(); @Override final String getReportType(); }### Answer:
@Test public final void addReport() { TestReport report = new TestReport(); IntegrityReport integrityReport = new IntegrityReport(); integrityReport.addReport(report); Set<Report> reportSet = integrityReport.getReports(); Assert.assertNotNull(reportSet); Assert.assertTrue(reportSet.contains(report)); Assert.assertEquals(reportSet.size(), 1); } |
### Question:
IntegrityReport extends Report { public final <T extends Report> T extractReport(final Class<T> reportType) { final Set<Report> reports = this.getReports(); for (Report report : reports) { if (reportType.isInstance(report)) { return reportType.cast(report); } } throw new IllegalArgumentException( String.format("This %s does not contain a %s. Before calling extractReport(), " + "call contains() to make sure the reportType exists." , getClass().getName(), reportType.getName())); } IntegrityReport(); final void addReport(final Report report); final boolean contains(Class<? extends Report> reportType); final Set<Report> getReports(); final void removeReport(final Report report); final T extractReport(final Class<T> reportType); String getDeviceName(); @Override final String getReportType(); }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public final void extractNonexistentDeviceInfoReport() { IntegrityReport integrityReport = new IntegrityReport(); integrityReport.extractReport(DeviceInfoReport.class); } |
### Question:
IntegrityReport extends Report { public final void removeReport(final Report report) { if (report == null) { LOGGER.error("report cannot be null"); throw new NullPointerException("report"); } if (reports.contains(report)) { if (reports.remove(report)) { LOGGER.info("report {} successfully removed", report); } else { LOGGER.info("unable to remove report {} from IntegrityReport", report); } } else { LOGGER.info("report {} not found in IntegrityReport", report); } } IntegrityReport(); final void addReport(final Report report); final boolean contains(Class<? extends Report> reportType); final Set<Report> getReports(); final void removeReport(final Report report); final T extractReport(final Class<T> reportType); String getDeviceName(); @Override final String getReportType(); }### Answer:
@Test public final void removeReport() { TestReport report = new TestReport(); TestReport report2 = new TestReport(); IntegrityReport integrityReport = new IntegrityReport(); integrityReport.addReport(report); integrityReport.addReport(report2); Set<Report> reports = integrityReport.getReports(); Assert.assertTrue(reports.contains(report)); Assert.assertTrue(reports.contains(report2)); Assert.assertEquals(reports.size(), 2); integrityReport.removeReport(report); Assert.assertFalse(reports.contains(report)); Assert.assertTrue(reports.contains(report2)); Assert.assertEquals(reports.size(), 1); } |
### Question:
IntegrityReport extends Report { public final Set<Report> getReports() { return Collections.unmodifiableSet(reports); } IntegrityReport(); final void addReport(final Report report); final boolean contains(Class<? extends Report> reportType); final Set<Report> getReports(); final void removeReport(final Report report); final T extractReport(final Class<T> reportType); String getDeviceName(); @Override final String getReportType(); }### Answer:
@Test public final void testPersistingNoReports() { IntegrityReport integrityReport = new IntegrityReport(); IntegrityReport savedIntegrityReport = saveAndRetrieve(integrityReport); Assert.assertEquals(savedIntegrityReport, integrityReport); Assert.assertEquals( savedIntegrityReport.getReports(), integrityReport.getReports() ); } |
### Question:
SupplyChainValidationSummary extends ArchivableEntity { public Set<SupplyChainValidation> getValidations() { return Collections.unmodifiableSet(validations); } protected SupplyChainValidationSummary(); SupplyChainValidationSummary(final Device device,
final Collection<SupplyChainValidation> validations); static SupplyChainValidationSummary.Selector select(
final CrudManager<SupplyChainValidationSummary> certMan); Device getDevice(); AppraisalStatus.Status getOverallValidationResult(); String getMessage(); Set<SupplyChainValidation> getValidations(); }### Answer:
@Test public void testSaveAndGetEmpty() { DBManager<SupplyChainValidationSummary> supplyMan = new DBManager<>( SupplyChainValidationSummary.class, sessionFactory ); SupplyChainValidationSummary emptySummary = getTestSummary( 0, 0, Collections.emptyList() ); SupplyChainValidationSummary savedEmptySummary = supplyMan.save(emptySummary); SupplyChainValidationSummary retrievedEmptySummary = supplyMan.get(savedEmptySummary.getId()); Assert.assertEquals(retrievedEmptySummary, emptySummary); Assert.assertEquals(retrievedEmptySummary.getValidations().size(), 0); }
@Test public void testSaveAndGetSmall() { DBManager<SupplyChainValidationSummary> supplyMan = new DBManager<>( SupplyChainValidationSummary.class, sessionFactory ); List<ArchivableEntity> singleCert = certificates.subList(0, 1); SupplyChainValidationSummary smallSummary = getTestSummary( 1, 0, singleCert ); SupplyChainValidationSummary savedSmallSummary = supplyMan.save(smallSummary); SupplyChainValidationSummary retrievedSmallSummary = supplyMan.get(savedSmallSummary.getId()); Assert.assertEquals(retrievedSmallSummary, smallSummary); Assert.assertEquals( new ArrayList<>(retrievedSmallSummary.getValidations()) .get(0).getCertificatesUsed(), singleCert ); } |
### Question:
AlertServiceConfig { public final void enable() { enabled = true; } protected AlertServiceConfig(); AlertServiceConfig(final String serviceType); final void enable(); final void disable(); boolean isEnabled(); final String getType(); final String getServiceIdentifier(); final void setServiceIdentifier(final String id); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public final void testEnable() { boolean enable = false; AlertServiceConfig asc = new AlertServiceConfig(JsonAlertService.NAME); asc.disable(); boolean testEnable = asc.isEnabled(); Assert.assertEquals(enable, testEnable); enable = true; asc.enable(); testEnable = asc.isEnabled(); Assert.assertEquals(enable, testEnable); } |
### Question:
AlertServiceConfig { public final String getType() { return type; } protected AlertServiceConfig(); AlertServiceConfig(final String serviceType); final void enable(); final void disable(); boolean isEnabled(); final String getType(); final String getServiceIdentifier(); final void setServiceIdentifier(final String id); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public final void testGetName() { AlertServiceConfig asc = new AlertServiceConfig(JsonAlertService.NAME); Assert.assertEquals(asc.getType(), JsonAlertService.NAME); } |
### Question:
JsonAlertMonitor extends AlertMonitor { public void setUDP() { this.mode = JsonAlertMode.UDP; } JsonAlertMonitor(); JsonAlertMonitor(final String name); @Enumerated(EnumType.ORDINAL) JsonAlertMode getJsonAlertMode(); boolean isTCP(); void setTCP(); boolean isUDP(); void setUDP(); }### Answer:
@Test public void testSetUDP() { final String name = "jsontest"; final JsonAlertMonitor.JsonAlertMode mode = JsonAlertMonitor.JsonAlertMode.UDP; JsonAlertMonitor jsonMonitor = new JsonAlertMonitor(name); jsonMonitor.setUDP(); Assert.assertFalse(jsonMonitor.isTCP()); Assert.assertTrue(jsonMonitor.isUDP()); Assert.assertEquals(jsonMonitor.getJsonAlertMode(), mode); } |
### Question:
CertificateAuthorityCredential extends Certificate { public byte[] getSubjectKeyIdentifier() { if (null != subjectKeyIdentifier) { return subjectKeyIdentifier.clone(); } return null; } CertificateAuthorityCredential(final byte[] certificateBytes); CertificateAuthorityCredential(final Path certificatePath); protected CertificateAuthorityCredential(); static Selector select(final CertificateManager certMan); String getCredentialType(); byte[] getSubjectKeyIdentifier(); @Override @SuppressWarnings("checkstyle:avoidinlineconditionals") boolean equals(final Object o); @Override @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"}) int hashCode(); static final String SUBJECT_KEY_IDENTIFIER_FIELD; }### Answer:
@Test public void testGetSubjectKeyIdentifier() throws CertificateException, IOException, URISyntaxException { Path testCertPath = Paths.get( this.getClass().getResource(CertificateTest.FAKE_ROOT_CA_FILE).toURI() ); CertificateAuthorityCredential caCred = new CertificateAuthorityCredential(testCertPath); byte[] subjectKeyIdentifier = caCred.getSubjectKeyIdentifier(); Assert.assertNotNull(subjectKeyIdentifier); Assert.assertEquals( Hex.encodeHexString(subjectKeyIdentifier), CertificateTest.FAKE_ROOT_CA_SUBJECT_KEY_IDENTIFIER_HEX ); } |
### Question:
CertificateAuthorityCredential extends Certificate { public static Selector select(final CertificateManager certMan) { return new Selector(certMan); } CertificateAuthorityCredential(final byte[] certificateBytes); CertificateAuthorityCredential(final Path certificatePath); protected CertificateAuthorityCredential(); static Selector select(final CertificateManager certMan); String getCredentialType(); byte[] getSubjectKeyIdentifier(); @Override @SuppressWarnings("checkstyle:avoidinlineconditionals") boolean equals(final Object o); @Override @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:avoidinlineconditionals"}) int hashCode(); static final String SUBJECT_KEY_IDENTIFIER_FIELD; }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void testSelectByNullSubjectKeyIdentifier() { CertificateAuthorityCredential.select(CERT_MAN).bySubjectKeyIdentifier(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testSelectByEmptySubjectKeyIdentifier() { CertificateAuthorityCredential.select(CERT_MAN).bySubjectKeyIdentifier(new byte[]{}); } |
### Question:
IMADeviceState extends DeviceState { public final String getBootcycleId() { return bootcycleId; } IMADeviceState(final Device device); protected IMADeviceState(); final Long getId(); final void resetState(); final Device getDevice(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); final Date getMostRecentFullReportDate(); final void setMostRecentFullReportDate(final Date date); @Override Criterion getDeviceTrustAlertCriterion(); final byte[] getPcrState(); final void setPcrState(final byte[] pcrState); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public void testGetDefaultBootcycleId() { final Device device = new Device("Test Device"); final IMADeviceState state = new IMADeviceState(device); Assert.assertNull(state.getBootcycleId()); } |
### Question:
IMADeviceState extends DeviceState { public final void setBootcycleId(final String bootcycleId) { this.bootcycleId = bootcycleId; } IMADeviceState(final Device device); protected IMADeviceState(); final Long getId(); final void resetState(); final Device getDevice(); final String getBootcycleId(); final void setBootcycleId(final String bootcycleId); final int getIndex(); final void setIndex(final int index); final Date getMostRecentFullReportDate(); final void setMostRecentFullReportDate(final Date date); @Override Criterion getDeviceTrustAlertCriterion(); final byte[] getPcrState(); final void setPcrState(final byte[] pcrState); @Override final int hashCode(); @Override final boolean equals(final Object obj); @Override final String toString(); }### Answer:
@Test public void testSetBootcycleId() { final Device device = new Device("Test Device"); final IMADeviceState state = new IMADeviceState(device); final String bootcycleId = "Mon Apr 20 09:32"; Assert.assertNotEquals(state.getBootcycleId(), bootcycleId); state.setBootcycleId(bootcycleId); Assert.assertEquals(state.getBootcycleId(), bootcycleId); } |
### Question:
Main { void execute() { System.out.println(message); } Main(String message); static void main(String args[]); }### Answer:
@Test public void testPrintMessage() { ByteArrayOutputStream binary = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(binary, true); PrintStream defaultStream = System.out; try { System.setOut(stream); new Main("message").execute(); assertThat(binary.toString(), is("message" + System.getProperty("line.separator"))); } finally { System.setOut(defaultStream); } } |
### Question:
SampleMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { if (outputDirectory == null) { throw new MojoExecutionException("outputDirectory is required"); } getLog().info("sample plugin start!"); getLog().debug("outputDirectory is " + outputDirectory.getAbsolutePath()); } @Override void execute(); }### Answer:
@Test public void testMojoHasHelpGoal() throws Exception { File baseDir = resources.getBasedir("no-output-dir"); File pom = new File(baseDir, "pom.xml"); Mojo samplePlugin = mojo.lookupMojo("help", pom); assertNotNull(samplePlugin); samplePlugin.setLog(log); samplePlugin.execute(); }
@Test(expected = MojoExecutionException.class) public void testSampleGoalRequiresOutputDir() throws Exception { File baseDir = resources.getBasedir("no-output-dir"); File pom = new File(baseDir, "pom.xml"); Mojo samplePlugin = mojo.lookupMojo("sample", pom); samplePlugin.execute(); }
@Test public void testSampleGoalPrintsOutputDirectory() throws Exception { File baseDir = resources.getBasedir("simple"); File pom = new File(baseDir, "pom.xml"); Mojo samplePlugin = mojo.lookupMojo("sample", pom); samplePlugin.setLog(log); samplePlugin.execute(); Mockito.verify(log).debug("outputDirectory is /tmp/target"); } |
### Question:
StorageUtils { public static ImmutablePair<String, String> splitNamespacePath(String objectPath) { if (objectPath == null) { return null; } String namespace = ""; if (objectPath.contains(namespaceSeparator)) { namespace = objectPath.substring(0, objectPath.indexOf(namespaceSeparator)); objectPath = objectPath.substring(objectPath.indexOf(namespaceSeparator) + 1); } return new ImmutablePair<>(namespace, objectPath); } static ImmutablePair<String, String> splitNamespacePath(String objectPath); static final String namespaceSeparator; }### Answer:
@Test public void testSplitNamespacePath() { Assert.assertNull(StorageUtils.splitNamespacePath(null)); final Pair<String, String> pathTuple1 = StorageUtils.splitNamespacePath("local:/some/path"); Assert.assertNotNull(pathTuple1); Assert.assertEquals(pathTuple1.getLeft(), "local"); Assert.assertEquals(pathTuple1.getRight(), "/some/path"); final Pair<String, String> pathTuple2 = StorageUtils.splitNamespacePath("/some/path"); Assert.assertNotNull(pathTuple2); Assert.assertEquals(pathTuple2.getLeft(), ""); Assert.assertEquals(pathTuple2.getRight(), "/some/path"); final Pair<String, String> pathTuple3 = StorageUtils.splitNamespacePath("adls:/some/path:with:colons"); Assert.assertNotNull(pathTuple3); Assert.assertEquals(pathTuple3.getLeft(), "adls"); Assert.assertEquals(pathTuple3.getRight(), "/some/path:with:colons"); } |
### Question:
E2ERelationshipPersistence { public static E2ERelationship toData(final CdmE2ERelationship instance) { final E2ERelationship e2ERelationship = new E2ERelationship(); if (!StringUtils.isNullOrTrimEmpty(instance.getName())) { e2ERelationship.setName(instance.getName()); } e2ERelationship.setFromEntity(instance.getFromEntity()); e2ERelationship.setFromEntityAttribute(instance.getFromEntityAttribute()); e2ERelationship.setToEntity(instance.getToEntity()); e2ERelationship.setToEntityAttribute(instance.getToEntityAttribute()); return e2ERelationship; } static CdmE2ERelationship fromData(final CdmCorpusContext ctx, final E2ERelationship dataObj); static E2ERelationship toData(final CdmE2ERelationship instance); }### Answer:
@Test public void toDataTest() { CdmCorpusDefinition corpus = new CdmCorpusDefinition(); CdmE2ERelationship instance = corpus.makeObject(CdmObjectType.E2ERelationshipDef); instance.setToEntity("TO_ENTITY"); instance.setToEntityAttribute("TO_ENTITY_ATTRIBUTE"); instance.setFromEntity("FROM_ENTITY"); instance.setFromEntityAttribute("FROM_ENTITY_ATTRIBUTE"); E2ERelationship result = E2ERelationshipPersistence.toData(instance); AssertJUnit.assertEquals(result.getToEntity(), "TO_ENTITY"); AssertJUnit.assertEquals(result.getToEntityAttribute(), "TO_ENTITY_ATTRIBUTE"); AssertJUnit.assertEquals(result.getFromEntity(), "FROM_ENTITY"); AssertJUnit.assertEquals(result.getFromEntityAttribute(), "FROM_ENTITY_ATTRIBUTE"); } |
### Question:
E2ERelationshipPersistence { public static CdmE2ERelationship fromData(final CdmCorpusContext ctx, final E2ERelationship dataObj) { final CdmE2ERelationship relationship = ctx.getCorpus().makeObject(CdmObjectType.E2ERelationshipDef); if (!StringUtils.isNullOrTrimEmpty(dataObj.getName())) { relationship.setName(dataObj.getName()); } relationship.setFromEntity(dataObj.getFromEntity()); relationship.setFromEntityAttribute(dataObj.getFromEntityAttribute()); relationship.setToEntity(dataObj.getToEntity()); relationship.setToEntityAttribute(dataObj.getToEntityAttribute()); return relationship; } static CdmE2ERelationship fromData(final CdmCorpusContext ctx, final E2ERelationship dataObj); static E2ERelationship toData(final CdmE2ERelationship instance); }### Answer:
@Test public void fromDataTest() { E2ERelationship dataObj = new E2ERelationship(); dataObj.setToEntity("TO_ENTITY"); dataObj.setToEntityAttribute("TO_ENTITY_ATTRIBUTE"); dataObj.setFromEntity("FROM_ENTITY"); dataObj.setFromEntityAttribute("FROM_ENTITY_ATTRIBUTE"); CdmE2ERelationship result = E2ERelationshipPersistence.fromData(new CdmCorpusDefinition().getCtx(), dataObj); AssertJUnit.assertEquals(result.getToEntity(), "TO_ENTITY"); AssertJUnit.assertEquals(result.getToEntityAttribute(), "TO_ENTITY_ATTRIBUTE"); AssertJUnit.assertEquals(result.getFromEntity(), "FROM_ENTITY"); AssertJUnit.assertEquals(result.getFromEntityAttribute(), "FROM_ENTITY_ATTRIBUTE"); } |
### Question:
WishlistMovieToSerieDataDtoBuilder { public WishlistDataDto build(WishlistMovie wishlistMovie) { TmdbKino movie = wishlistMovie.getMovie(); return new WishlistDataDto( wishlistMovie.getWishlist_movie_id(), movie != null && movie.getMovie_id() != null ? movie.getMovie_id().intValue() : null, wishlistMovie.getTitle(), movie != null ? movie.getPoster_path() : null, movie != null ? movie.getOverview() : null, movie != null ? movie.getYear() : 0, movie != null ? movie.getRelease_date() : null, WishlistItemType.MOVIE ); } WishlistDataDto build(WishlistMovie wishlistMovie); }### Answer:
@SuppressWarnings("ResultOfMethodCallIgnored") @Test public void build() { doReturn(456L).when(wishlistMovie).getWishlist_movie_id(); doReturn("Elle").when(wishlistMovie).getTitle(); doReturn(tmdbMovie).when(wishlistMovie).getMovie(); doReturn(456456456L).when(tmdbMovie).getMovie_id(); doReturn(2015).when(tmdbMovie).getYear(); doReturn("An overview").when(tmdbMovie).getOverview(); doReturn("/poster/path").when(tmdbMovie).getPoster_path(); doReturn("a releaseDate").when(tmdbMovie).getRelease_date(); assertEquals( new WishlistDataDto( 456L, 456456456, "Elle", "/poster/path", "An overview", 2015, "a releaseDate", WishlistItemType.MOVIE ), new WishlistMovieToSerieDataDtoBuilder().build(wishlistMovie) ); } |
### Question:
WishlistCsvExportWriter extends CsvExportWriter<WishlistDataDto> { public void write(WishlistDataDto wishlistDataDto) throws IOException { csvPrinterWrapper.printRecord( wishlistDataDto.getId(), wishlistDataDto.getTmdbId(), wishlistDataDto.getTitle(), wishlistDataDto.getOverview(), wishlistDataDto.getFirstYear(), wishlistDataDto.getPosterPath(), wishlistDataDto.getReleaseDate(), wishlistDataDto.getWishlistItemType().toString() ); } WishlistCsvExportWriter(Appendable out); WishlistCsvExportWriter(CSVPrinterWrapper csvPrinterWrapper); void write(WishlistDataDto wishlistDataDto); }### Answer:
@Test public void write() throws Exception { wishlistDto = new WishlistDataDto( 24L, 25, "a title", "/path", "an overview", 2012, "20120212", WishlistItemType.MOVIE ); new WishlistCsvExportWriter(csvPrinterWrapper).write(wishlistDto); verify(csvPrinterWrapper).printRecord( 24L, 25, "a title", "an overview", 2012, "/path", "20120212", "MOVIE" ); } |
### Question:
NetworkTaskManager { public void createAndExecute(Call... call) { cancelTasks(); AsyncTask networkTask = networkTaskCreator.create(addReviewActivity); networkTask.execute(call); taskList.add(networkTask); } NetworkTaskManager(AddReviewActivity<T> addReviewActivity, NetworkTaskCreator<AsyncTask, T> networkTaskCreator); void createAndExecute(Call... call); List<AsyncTask> getTaskList(); void setTaskList(List<AsyncTask> taskList); }### Answer:
@Test public void createAndExecute() throws Exception { doReturn(networkTask).when(networkTaskCreator).create(addReviewActivity); NetworkTaskManager networkTaskManager = new NetworkTaskManager(addReviewActivity, networkTaskCreator); networkTaskManager.createAndExecute(call); verify(networkTask).execute(call); assertEquals( new ArrayList<MovieNetworkTask>() {{ add(networkTask); }}, networkTaskManager.getTaskList() ); } |
### Question:
NetworkTaskManager { void cancelTasks() { for (AsyncTask task : taskList) { task.cancel(true); } taskList.clear(); } NetworkTaskManager(AddReviewActivity<T> addReviewActivity, NetworkTaskCreator<AsyncTask, T> networkTaskCreator); void createAndExecute(Call... call); List<AsyncTask> getTaskList(); void setTaskList(List<AsyncTask> taskList); }### Answer:
@Test public void cancelTasks() throws Exception { final MovieNetworkTask anotherNetworkTask = mock(MovieNetworkTask.class); NetworkTaskManager networkTaskManager = new NetworkTaskManager(addReviewActivity, networkTaskCreator); networkTaskManager.setTaskList( new ArrayList<AsyncTask>() {{ add(networkTask); add(anotherNetworkTask); }} ); networkTaskManager.cancelTasks(); verify(networkTask).cancel(true); verify(anotherNetworkTask).cancel(true); assertEquals(emptyList(), networkTaskManager.getTaskList()); } |
### Question:
SerieSyncNetworkTask extends AsyncTask<Call<TvShow>, Void, SerieDto> { @SuppressWarnings("unchecked") @Override protected SerieDto doInBackground(Call<TvShow>... calls) { for (Call<TvShow> call : calls) { try { TvShow tvShow = call.execute().body(); return serieBuilderFromMovie.build(tvShow); } catch (IOException e) { Log.i("tmdbGetter", "Unable to execute task."); } } return null; } SerieSyncNetworkTask(SerieBuilderFromMovie serieBuilderFromMovie, SerieReview serieReview, SerieService serieService); }### Answer:
@Test public void doInBackground() throws IOException { Call<TvShow> call = mock(Call.class); Response<TvShow> response = mock(Response.class); doReturn(response).when(call).execute(); TvShow tvShow = mock(TvShow.class); doReturn(tvShow).when(response).body(); SerieDto serieDto = mock(SerieDto.class); doReturn(serieDto).when(serieBuilderFromMovie).build(tvShow); SerieReview serieReview = mock(SerieReview.class); assertEquals( serieDto, new SerieSyncNetworkTask(serieBuilderFromMovie, serieReview, serieService).doInBackground(call) ); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.