method2testcases
stringlengths 118
6.63k
|
---|
### Question:
CaseInsensitiveString implements Comparable<CaseInsensitiveString> { @Override public boolean equals(final Object obj) { if (obj instanceof CaseInsensitiveString) { final CaseInsensitiveString other = (CaseInsensitiveString) obj; return name.equals(other.name); } return false; } CaseInsensitiveString(final String name); @Override int compareTo(final CaseInsensitiveString other); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { Assert.assertFalse(CIS1.equals(STRING1)); Assert.assertTrue(CIS1.equals(new CaseInsensitiveString(STRING2))); } |
### Question:
CaseInsensitiveString implements Comparable<CaseInsensitiveString> { @Override public int hashCode() { return name.hashCode(); } CaseInsensitiveString(final String name); @Override int compareTo(final CaseInsensitiveString other); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { Assert.assertTrue(CIS1.hashCode() == CIS2.hashCode()); } |
### Question:
CaseInsensitiveString implements Comparable<CaseInsensitiveString> { @Override public String toString() { return name.toString(); } CaseInsensitiveString(final String name); @Override int compareTo(final CaseInsensitiveString other); @Override boolean equals(final Object obj); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testToString() { Assert.assertEquals(CIS1.toString(), CIS2.toString()); } |
### Question:
XmiComparison { public XmiDefinition getLhsDef() { return lhsRef; } XmiComparison(final XmiDefinition lhsRef, final XmiDefinition rhsRef, final List<XmiMapping> mappings); XmiDefinition getLhsDef(); XmiDefinition getRhsDef(); List<XmiMapping> getMappings(); }### Answer:
@Test public void testGetLhsDef() { Assert.assertEquals(LHS_XMI_DEFINITION, XMI_COMPARISON.getLhsDef()); } |
### Question:
XmiComparison { public XmiDefinition getRhsDef() { return rhsRef; } XmiComparison(final XmiDefinition lhsRef, final XmiDefinition rhsRef, final List<XmiMapping> mappings); XmiDefinition getLhsDef(); XmiDefinition getRhsDef(); List<XmiMapping> getMappings(); }### Answer:
@Test public void testGetRhsDef() { Assert.assertEquals(RHS_XMI_DEFINITION, XMI_COMPARISON.getRhsDef()); } |
### Question:
XmiComparison { public List<XmiMapping> getMappings() { return mappings; } XmiComparison(final XmiDefinition lhsRef, final XmiDefinition rhsRef, final List<XmiMapping> mappings); XmiDefinition getLhsDef(); XmiDefinition getRhsDef(); List<XmiMapping> getMappings(); }### Answer:
@Test public void testGetMappings() { Assert.assertEquals(XMI_MAPPINGS, XMI_COMPARISON.getMappings()); } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { @Override public int compareTo(final CaseInsensitiveQName other) { return QNameComparator.SINGLETON.compare(name, other.name); } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testCompare() { Assert.assertTrue(ciqn1.compareTo(ciqn2) == 0); } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { @Override public boolean equals(final Object obj) { if (obj instanceof CaseInsensitiveQName) { final CaseInsensitiveQName other = (CaseInsensitiveQName) obj; return name.equals(other.name); } return false; } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testEquals() { Assert.assertTrue(ciqn1.equals(ciqn2)); Assert.assertFalse(ciqn1.equals(new QName("type", "feature"))); } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { public String getLocalPart() { return name.getLocalPart(); } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testGetLocalPart() { Assert.assertEquals(ciqn1.getLocalPart(), ciqn2.getLocalPart()); } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { public String getNamespaceURI() { return name.getNamespaceURI(); } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testGetNamespaceUri() { Assert.assertEquals(ciqn1.getNamespaceURI(), ciqn2.getNamespaceURI()); } |
### Question:
ResourceDocumenter { protected String readFile(File generatedHtml) { String content = ""; try { content = IOUtils.toString(new FileInputStream(generatedHtml)); } catch (FileNotFoundException e) { LOG.warn(e.getMessage()); } catch (IOException e) { LOG.warn(e.getMessage()); } return content; } void addResourceMerge(File generatedHtml); static void main(String[] args); }### Answer:
@Test public void testReadFile() { URL testFile = this.getClass().getResource("/application.html"); try { String out = testResource.readFile(new File(testFile.toURI())); assertEquals("output should match", out, EXPECTED_OUTPUT); } catch (URISyntaxException e) { fail(e.getMessage()); } } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { @Override public int hashCode() { return name.hashCode(); } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { Assert.assertEquals(ciqn1.hashCode(), ciqn2.hashCode()); } |
### Question:
CaseInsensitiveQName implements Comparable<CaseInsensitiveQName> { @Override public String toString() { return name.toString(); } CaseInsensitiveQName(final String type, final String feature); @Override int compareTo(final CaseInsensitiveQName other); @Override boolean equals(final Object obj); String getLocalPart(); String getNamespaceURI(); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testToString() { Assert.assertEquals(ciqn1.toString(), ciqn2.toString()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { @Override public int compareTo(final XmiMapping other) { return 0; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testCompareTo() { Assert.assertTrue(XMI_MAPPING.compareTo(null) == 0); Assert.assertTrue(XMI_MAPPING.compareTo(XMI_MAPPING) == 0); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { public XmiFeature getLhsFeature() { return lhs; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testGetLhsFeature() { Assert.assertEquals(LHS_FEATURE, XMI_MAPPING.getLhsFeature()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { public XmiFeature getRhsFeature() { return rhs; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testGetRhsFeature() { Assert.assertEquals(RHS_FEATURE, XMI_MAPPING.getRhsFeature()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { public XmiMappingStatus getStatus() { return status; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testGetStatus() { Assert.assertEquals(XMI_MAPPING_STATUS, XMI_MAPPING.getStatus()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { public String getComment() { return comment; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testGetComment() { Assert.assertEquals(COMMENT, XMI_MAPPING.getComment()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { public String getTracking() { return tracking; } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testGetTracking() { Assert.assertEquals(TRACKING, XMI_MAPPING.getTracking()); } |
### Question:
XmiMapping implements Comparable<XmiMapping> { @Override public String toString() { return String.format("{lhs : %s, rhs : %s, status : %s, comment : %s}", lhs, rhs, status, comment); } XmiMapping(final XmiFeature lhs, final XmiFeature rhs, final XmiMappingStatus status, final String tracking, final String comment); @Override int compareTo(final XmiMapping other); @Override boolean equals(Object o); @Override int hashCode(); XmiFeature getLhsFeature(); XmiFeature getRhsFeature(); XmiMappingStatus getStatus(); String getComment(); String getTracking(); @Override String toString(); }### Answer:
@Test public void testToString() { Assert.assertNotNull(XMI_MAPPING.toString()); } |
### Question:
XmiFeature { public String getName() { return name; } XmiFeature(final String name, final boolean exists, final String className, final boolean classExists); String getName(); String getOwnerName(); boolean ownerExists(); boolean exists(); @Override String toString(); }### Answer:
@Test public void testGetName() { assertEquals(NAME, XMI_FEATURE.getName()); } |
### Question:
ResourceDocumenter { protected String createLink(String key, String value) { String link = ""; link = LINK_HTML.replace("$LINK", baseUrl + value); link = link.replace("$TYPE", key); return link; } void addResourceMerge(File generatedHtml); static void main(String[] args); }### Answer:
@Test public void testCreateLink() { testResource.readPropertiesFile(); final String expectedLink = "<a href=\"" + testResource.getBaseUrl() + "endpoint#anchor\">test</a>"; String key = "test"; String value = "endpoint#anchor"; String out = testResource.createLink(key, value); assertEquals("output should match", out, expectedLink); } |
### Question:
XmiFeature { public boolean exists() { return exists; } XmiFeature(final String name, final boolean exists, final String className, final boolean classExists); String getName(); String getOwnerName(); boolean ownerExists(); boolean exists(); @Override String toString(); }### Answer:
@Test public void testExists() { assertEquals(EXISTS, XMI_FEATURE.exists()); } |
### Question:
XmiFeature { public String getOwnerName() { return className; } XmiFeature(final String name, final boolean exists, final String className, final boolean classExists); String getName(); String getOwnerName(); boolean ownerExists(); boolean exists(); @Override String toString(); }### Answer:
@Test public void testGetOwnerName() { assertEquals(CLASS_NAME, XMI_FEATURE.getOwnerName()); } |
### Question:
XmiFeature { public boolean ownerExists() { return classExists; } XmiFeature(final String name, final boolean exists, final String className, final boolean classExists); String getName(); String getOwnerName(); boolean ownerExists(); boolean exists(); @Override String toString(); }### Answer:
@Test public void testOwnerExists() { assertEquals(CLASS_EXISTS, XMI_FEATURE.ownerExists()); } |
### Question:
XmiFeature { @Override public String toString() { return String.format("{name : %s, exists : %s, className : %s, classExists : %s}", name, exists, className, classExists); } XmiFeature(final String name, final boolean exists, final String className, final boolean classExists); String getName(); String getOwnerName(); boolean ownerExists(); boolean exists(); @Override String toString(); }### Answer:
@Test public void testToString() { assertNotNull(XMI_FEATURE.toString()); } |
### Question:
XmiDefinition { public String getName() { return name; } XmiDefinition(final String name, final String version, final String file); String getName(); String getVersion(); String getFile(); }### Answer:
@Test public void testGetName() { Assert.assertEquals(NAME, xmiDefinition.getName()); } |
### Question:
XmiDefinition { public String getVersion() { return version; } XmiDefinition(final String name, final String version, final String file); String getName(); String getVersion(); String getFile(); }### Answer:
@Test public void testGetVersion() { Assert.assertEquals(VERSION, xmiDefinition.getVersion()); } |
### Question:
XmiDefinition { public String getFile() { return file; } XmiDefinition(final String name, final String version, final String file); String getName(); String getVersion(); String getFile(); }### Answer:
@Test public void testGetFile() { Assert.assertEquals(FILE, xmiDefinition.getFile()); } |
### Question:
XmiReader { protected static final <T> T assertNotNull(final T obj) { if (obj != null) { return obj; } else { throw new AssertionError(); } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testAssertNotNullHappyPath() { Object o = new Object(); assertTrue(XmiReader.assertNotNull(o) == o); }
@Test(expected = AssertionError.class) public void testAssertNotNullSadPath() { XmiReader.assertNotNull(null); }
@Test public void testAllPublicMethods() throws XMLStreamException, IOException { String filename = "src/test/resources/SLI.xmi"; Model model1 = this.readModelByFile(filename); Model model2 = this.readModelByStream(filename); Model model4 = this.readModelByName(filename); assertNotNull(model1); assertNotNull(model2); assertNotNull(model4); assertEquals(model1, model2); assertEquals(model1, model4); } |
### Question:
XmiReader { protected static final Occurs getOccurs(final XMLStreamReader reader, final XmiAttributeName name) { final int value = Integer.valueOf(reader.getAttributeValue(GLOBAL_NAMESPACE, name.getLocalName())); switch (value) { case 0: { return Occurs.ZERO; } case 1: { return Occurs.ONE; } case -1: { return Occurs.UNBOUNDED; } default: { throw new AssertionError(value); } } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testGetOccursHappyPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ONE); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("0"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.ZERO); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("-1"); assertTrue(XmiReader.getOccurs(mockReader, sampleAttribute) == Occurs.UNBOUNDED); }
@Test(expected = AssertionError.class) public void testGetOccursSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("123"); XmiReader.getOccurs(mockReader, sampleAttribute); } |
### Question:
DocumentManipulator { protected Document parseDocument(File file) throws DocumentManipulatorException { Document doc = null; try { DocumentBuilder builder = docFactory.newDocumentBuilder(); doc = builder.parse(file); } catch (SAXException e) { throw new DocumentManipulatorException(e); } catch (IOException e) { throw new DocumentManipulatorException(e); } catch (ParserConfigurationException e) { throw new DocumentManipulatorException(e); } return doc; } DocumentManipulator(); NodeList getNodeList(Document doc, String expression); void serializeDocumentToHtml(Document document, File outputFile, File xslFile); void serializeDocumentToXml(Document document, File outputFile); String serializeDocumentToString(Document document); }### Answer:
@Test(expected = DocumentManipulatorException.class) public void testParseDocumentEmptyFile() throws DocumentManipulatorException { handler.parseDocument(new File("")); }
@Test public void testParseDocument() throws DocumentManipulatorException, URISyntaxException { URL url = this.getClass().getResource("/sample.xml"); Document doc = handler.parseDocument(new File(url.toURI())); assertNotNull("Document should not be null", doc); } |
### Question:
XmiReader { protected static final Identifier getIdRef(final XMLStreamReader reader) throws XmiMissingAttributeException { final String value = reader.getAttributeValue(GLOBAL_NAMESPACE, XmiAttributeName.IDREF.getLocalName()); if (value != null) { return Identifier.fromString(value); } else { throw new XmiMissingAttributeException(XmiAttributeName.IDREF.getLocalName()); } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testGetIdRefHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getIdRef(mockReader).toString().equals(id)); }
@Test(expected = XmiMissingAttributeException.class) public void testGetIdRefSadPath() { when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); XmiReader.getIdRef(mockReader); } |
### Question:
XmiReader { protected static final Identifier getId(final XMLStreamReader reader) { return Identifier.fromString(reader.getAttributeValue(GLOBAL_NAMESPACE, XmiAttributeName.ID.getLocalName())); } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testGetIdHappyPath() { String id = "ID1234567890"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(id); assertTrue(XmiReader.getId(mockReader).toString().equals(id)); } |
### Question:
XmiReader { protected static final boolean getBoolean(final XmiAttributeName name, final boolean defaultValue, final XMLStreamReader reader) { final String value = reader.getAttributeValue(GLOBAL_NAMESPACE, name.getLocalName()); if (value != null) { return Boolean.valueOf(value); } else { return defaultValue; } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testGetBoolean() { boolean defaultBoolean; defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("true"); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("false"); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = false; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertFalse(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); defaultBoolean = true; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertTrue(XmiReader.getBoolean(sampleAttribute, defaultBoolean, mockReader)); } |
### Question:
XmiReader { protected static final void closeQuiet(final Closeable closeable) { IOUtils.closeQuietly(closeable); } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testCloseQuiet() throws IOException { Closeable mockCloseable = mock(Closeable.class); final StringBuffer stringBuffer = new StringBuffer(); PrintStream stdErr = System.err; PrintStream myErr = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { stringBuffer.append((char) b); } }); System.setErr(myErr); XmiReader.closeQuiet(mockCloseable); assertTrue(stringBuffer.toString().equals("")); System.setErr(stdErr); } |
### Question:
XmiReader { protected static final void assertName(final QName name, final XMLStreamReader reader) { if (!match(name, reader)) { throw new AssertionError(reader.getLocalName()); } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testAssertElementNameEqualsStreamReadNameHappyPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = xmiElementName.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); }
@Test(expected = AssertionError.class) public void testAssertElementNameEqualsStreamReadNameSadPath() { XmiElementName xmiElementName = XmiElementName.ASSOCIATION; String elementName = XmiElementName.ASSOCIATION_END.getLocalName(); when(mockReader.getLocalName()).thenReturn(elementName); XmiReader.assertName(xmiElementName, mockReader); } |
### Question:
XmiReader { protected static final void skipElement(final XMLStreamReader reader, final boolean check) throws XMLStreamException { if (check) { throw new AssertionError(reader.getName()); } final String localName = reader.getLocalName(); while (reader.hasNext()) { reader.next(); switch (reader.getEventType()) { case XMLStreamConstants.START_ELEMENT: { skipElement(reader, check); break; } case XMLStreamConstants.END_ELEMENT: { if (localName.equals(reader.getLocalName())) { return; } else { throw new AssertionError(reader.getLocalName()); } } case XMLStreamConstants.CHARACTERS: { break; } default: { throw new AssertionError(reader.getEventType()); } } } throw new AssertionError(); } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testSkipElement() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); localNames.add("myLocalName1"); final List<Integer> eventTypes = new ArrayList<Integer>(); eventTypes.add(XMLStreamConstants.START_ELEMENT); eventTypes.add(XMLStreamConstants.CHARACTERS); eventTypes.add(XMLStreamConstants.END_ELEMENT); eventTypes.add(XMLStreamConstants.END_ELEMENT); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return eventTypes.remove(0); } }); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); }
@Test(expected = AssertionError.class) public void testSkipElementSadPath2NoNext() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(false); XmiReader.skipElement(mockReader, false); }
@Test(expected = AssertionError.class) public void testSkipElementSadPath3UnknownEventType() throws XMLStreamException { when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(123456789); XmiReader.skipElement(mockReader, false); }
@Test(expected = AssertionError.class) public void testSkipElementSadPath4LocalNamesDoNotMatch() throws XMLStreamException { final List<String> localNames = new ArrayList<String>(); localNames.add("myLocalName1"); localNames.add("myLocalName2"); localNames.add("myLocalName2"); when(mockReader.hasNext()).thenReturn(true); when(mockReader.getEventType()).thenReturn(XMLStreamConstants.END_ELEMENT); when(mockReader.getLocalName()).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return localNames.remove(0); } }); XmiReader.skipElement(mockReader, false); } |
### Question:
ValueMapper extends Mapper<TenantAndIdEmittableKey, BSONWritable, TenantAndIdEmittableKey, Writable> { @Override public void map(TenantAndIdEmittableKey key, BSONWritable entity, Context context) throws InterruptedException, IOException { context.write(key, getValue(entity)); } @Override void map(TenantAndIdEmittableKey key, BSONWritable entity, Context context); abstract Writable getValue(BSONWritable entity); }### Answer:
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testMap() throws Exception { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey(); ValueMapper m = new MockValueMapper(); BSONObject entry = new BasicBSONObject("found", "data"); BSONWritable entity = new BSONWritable(entry); Context context = Mockito.mock(Context.class); PowerMockito.when(context, "write", Matchers.any(EmittableKey.class), Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() { @Override public BSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); assertNotNull(args); assertEquals(args.length, 2); assertTrue(args[0] instanceof TenantAndIdEmittableKey); assertTrue(args[1] instanceof ContentSummary); TenantAndIdEmittableKey id = (TenantAndIdEmittableKey) args[0]; assertNotNull(id); ContentSummary e = (ContentSummary) args[1]; assertEquals(e.getLength(), 1); assertEquals(e.getFileCount(), 2); assertEquals(e.getDirectoryCount(), 3); return null; } }); m.map(key, entity, context); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testMapValueNotFound() throws Exception { TenantAndIdEmittableKey key = new TenantAndIdEmittableKey(); ValueMapper m = new MockValueMapper(); BSONObject entry = new BasicBSONObject("not_found", "data"); BSONWritable entity = new BSONWritable(entry); Context context = Mockito.mock(Context.class); PowerMockito.when(context, "write", Matchers.any(TenantAndIdEmittableKey.class), Matchers.any(BSONObject.class)).thenAnswer(new Answer<BSONObject>() { @Override public BSONObject answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); assertNotNull(args); assertEquals(args.length, 2); assertTrue(args[0] instanceof TenantAndIdEmittableKey); assertTrue(args[1] instanceof NullWritable); return null; } }); m.map(key, entity, context); } |
### Question:
XmiReader { protected static final String getName(final XMLStreamReader reader, final String defaultName, final XmiAttributeName attr) { final String name = reader.getAttributeValue(GLOBAL_NAMESPACE, attr.getLocalName()); if (name != null) { return name; } else { return defaultName; } } static final Model readModel(final File file); static final Model readModel(final InputStream stream); static final Model readModel(final String fileName); }### Answer:
@Test public void testGetName() { String defaultString; defaultString = "defString"; when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn("specifiedString"); assertEquals("specifiedString", XmiReader.getName(mockReader, defaultString, sampleAttribute)); when(mockReader.getAttributeValue(any(String.class), any(String.class))).thenReturn(null); assertEquals(defaultString, XmiReader.getName(mockReader, defaultString, sampleAttribute)); } |
### Question:
XmiWriter { public static final void writeDocument(final Model model, final ModelIndex mapper, final OutputStream outstream) { final XMLOutputFactory xof = XMLOutputFactory.newInstance(); try { final XMLStreamWriter xsw = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(outstream, "UTF-8")); xsw.writeStartDocument("UTF-8", "1.0"); try { XmiWriter.writeXMI(model, mapper, xsw); } finally { xsw.writeEndDocument(); } xsw.flush(); } catch (final XMLStreamException e) { throw new XmiRuntimeException(e); } } static final void writeDocument(final Model model, final ModelIndex mapper, final OutputStream outstream); static final void writeDocument(final Model model, final ModelIndex mapper, final String fileName); static final void writeDocument(final Model model, final ModelIndex mapper, final File file); }### Answer:
@Test public void testWriteDocumentOutputStream() throws Exception { OutputStream os = new ByteArrayOutputStream(); OutputStream mockOutputStream = spy(os); XmiWriter.writeDocument(model, modelIndex, mockOutputStream); String output = mockOutputStream.toString(); assertTrue(output.contains(MODEL_ID.toString())); assertTrue(output.contains(MODEL_NAME)); assertTrue(output.contains(PACKAGE_ID.toString())); assertTrue(output.contains(PACKAGE_NAME)); assertTrue(output.contains(TAGGEDVALUE_VALUE)); assertTrue(output.contains(TAGDEFINITION_ID.toString())); assertTrue(output.contains(TAGDEFINITION_NAME)); assertTrue(output.contains("lower=\"0\"")); assertTrue(output.contains("upper=\"1\"")); assertFalse(output.contains("upper=\"-1\"")); assertTrue(output.contains(DATATYPE_ID.toString())); assertTrue(output.contains(DATATYPE_NAME)); assertTrue(output.contains(ATTRIBUTE_ID.toString())); assertTrue(output.contains(ATTRIBUTE_NAME)); assertTrue(output.contains(CLASSTYPE_ID.toString())); assertTrue(output.contains(CLASSTYPE_NAME)); assertTrue(output.contains(ENUMLITERALA_ID.toString())); assertTrue(output.contains(ENUMLITERALA_NAME)); assertTrue(output.contains(ENUMTYPE_ID.toString())); assertTrue(output.contains(ENUMTYPE_NAME)); assertTrue(output.contains(ASSOCIATIONEND_PARENT_ID.toString())); assertTrue(output.contains(ASSOCIATIONEND_PARENT_NAME)); assertTrue(output.contains(GENERALIZATION_ID.toString())); assertTrue(output.contains(GENERALIZATION_NAME)); }
@Test public void testWriteDocumentFile() { File file = new File("unittest-writedocumentfile.xmi"); assertFalse(file.exists()); XmiWriter.writeDocument(model, modelIndex, file); assertTrue(file.exists()); file.deleteOnExit(); }
@Test public void testWriteDocumentString() { String filename = "unittest-writedocumentstring.xmi"; File file = new File(filename); assertFalse(file.exists()); XmiWriter.writeDocument(model, modelIndex, filename); assertTrue(file.exists()); file.deleteOnExit(); } |
### Question:
WadlWalker { public void walk(final Application application) { if (application == null) { throw new IllegalArgumentException("application"); } handler.beginApplication(application); try { final Resources resources = application.getResources(); final Stack<Resource> ancestors = new Stack<Resource>(); for (final Resource resource : resources.getResources()) { walkResource(resource, resources, application, ancestors); } } finally { handler.endApplication(application); } } WadlWalker(final WadlHandler handler); void walk(final Application application); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testWalkNullApplication() { WadlHandler mockHandler = mock(WadlHandler.class); WadlWalker ww = new WadlWalker(mockHandler); ww.walk(null); }
@Test public void testWalk() { WadlHandler wadlHandler = mock(WadlHandler.class); WadlWalker ww = new WadlWalker(wadlHandler); List<Resource> emptyResourcesList = new ArrayList<Resource>(0); Resources mockResources = mock(Resources.class); when(mockResources.getResources()).thenReturn(emptyResourcesList); Application mockApplication = mock(Application.class); when(mockApplication.getResources()).thenReturn(mockResources); ww.walk(mockApplication); verify(wadlHandler).beginApplication(mockApplication); verify(wadlHandler).endApplication(mockApplication); } |
### Question:
WadlHelper { public static List<Param> getRequestParams(final Method method) { if (method == null) { throw new IllegalArgumentException(); } final Request request = method.getRequest(); if (request != null) { return request.getParams(); } else { return Collections.emptyList(); } } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testGetRequestParams() throws Exception { Param mockParam = mock(Param.class); Request mockRequest = mock(Request.class); List<Param> mockParamList = new ArrayList<Param>(1); mockParamList.add(mockParam); when(mockRequest.getParams()).thenReturn(mockParamList); Method mockMethod = mock(Method.class); when(mockMethod.getRequest()).thenReturn(mockRequest); List<Param> paramList = WadlHelper.getRequestParams(mockMethod); assertEquals(1, paramList.size()); } |
### Question:
DocumentManipulator { public NodeList getNodeList(Document doc, String expression) throws XPathException { XPath xpath = xPathFactory.newXPath(); xpath.setNamespaceContext(new DocumentNamespaceResolver(doc)); XPathExpression exp = xpath.compile(expression); Object result = exp.evaluate(doc, XPathConstants.NODESET); return (NodeList) result; } DocumentManipulator(); NodeList getNodeList(Document doc, String expression); void serializeDocumentToHtml(Document document, File outputFile, File xslFile); void serializeDocumentToXml(Document document, File outputFile); String serializeDocumentToString(Document document); }### Answer:
@Test public void testGetNodeList() throws DocumentManipulatorException, URISyntaxException, XPathException { URL url = this.getClass().getResource("/sample.xml"); String expression = " Document doc = handler.parseDocument(new File(url.toURI())); NodeList list = handler.getNodeList(doc, expression); assertNotNull("list shoud not be null", list); } |
### Question:
WadlHelper { public static final String computeId(final Method method, final Resource resource, final Resources resources, final Application app, final Stack<Resource> ancestors) { final List<String> steps = reverse(toSteps(resource, ancestors)); final StringBuilder sb = new StringBuilder(); sb.append(method.getVerb().toLowerCase()); boolean first = true; boolean seenParam = false; String paramName = null; for (final String step : steps) { if (isTemplateParam(step)) { seenParam = true; paramName = parseTemplateParam(step); } else if (!isVersion(step)) { if (first) { first = false; } else { sb.append("For"); } sb.append(titleCase(step)); if (seenParam) { sb.append("By" + titleCase(paramName)); seenParam = false; } } } return sb.toString(); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testComputeId() throws Exception { String id = "getStudentsByIdForApi"; Method mockMethod = mock(Method.class); when(mockMethod.getVerb()).thenReturn(Method.NAME_HTTP_GET); Resource mockResource = mock(Resource.class); when(mockResource.getPath()).thenReturn("students/{id}"); Resource mockAncestorResource = mock(Resource.class); when(mockAncestorResource.getPath()).thenReturn("api/v1"); Stack<Resource> resources = new Stack<Resource>(); resources.push(mockAncestorResource); String computedId = WadlHelper.computeId(mockMethod, mockResource, null, null, resources); assertEquals(id, computedId); } |
### Question:
WadlHelper { public static final String titleCase(final String text) { return text.substring(0, 1).toUpperCase().concat(text.substring(1)); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testTitleCase() throws Exception { String camelCase = "randomName"; String titleCase = "RandomName"; assertEquals(titleCase, WadlHelper.titleCase(camelCase)); } |
### Question:
WadlHelper { public static final <T> List<T> reverse(final List<T> strings) { final LinkedList<T> result = new LinkedList<T>(); for (final T s : strings) { result.addFirst(s); } return Collections.unmodifiableList(result); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testReverse() throws Exception { @SuppressWarnings({ "serial" }) List<Integer> strList = new ArrayList<Integer>(3) { { add(1); add(2); add(3); } }; List<Integer> revList = WadlHelper.reverse(strList); assertEquals(3, revList.size()); assertEquals(3, (int) revList.get(0)); assertEquals(2, (int) revList.get(1)); assertEquals(1, (int) revList.get(2)); } |
### Question:
WadlHelper { public static final boolean isVersion(final String step) { return step.toLowerCase().equals("v1"); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testIsVersion() throws Exception { String versionString = "v1"; String versionStringUpperCase = "V1"; String nonVersionString = "blah"; assertTrue(WadlHelper.isVersion(versionString)); assertTrue(WadlHelper.isVersion(versionStringUpperCase)); assertFalse(WadlHelper.isVersion(nonVersionString)); } |
### Question:
WadlHelper { public static final String parseTemplateParam(final String step) { if (isTemplateParam(step)) { return step.substring(1, step.length() - 1); } else { throw new AssertionError(step); } } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testParseTemplateParam() throws Exception { String templateParam = "{paramName}"; assertEquals("paramName", WadlHelper.parseTemplateParam(templateParam)); } |
### Question:
WadlHelper { public static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors) { final List<String> result = new LinkedList<String>(); for (final Resource ancestor : ancestors) { result.addAll(splitBasedOnFwdSlash(ancestor.getPath())); } result.addAll(splitBasedOnFwdSlash(resource.getPath())); return Collections.unmodifiableList(result); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testToSteps() throws Exception { Resource mockResource = mock(Resource.class); when(mockResource.getPath()).thenReturn("students/{id}"); Resource mockAncestorResource = mock(Resource.class); when(mockAncestorResource.getPath()).thenReturn("api/v1"); Stack<Resource> resources = new Stack<Resource>(); resources.push(mockAncestorResource); List<String> steps = WadlHelper.toSteps(mockResource, resources); assertEquals(4, steps.size()); assertEquals("api", steps.get(0)); assertEquals("v1", steps.get(1)); assertEquals("students", steps.get(2)); assertEquals("{id}", steps.get(3)); } |
### Question:
WadlHelper { public static final boolean isTemplateParam(final String step) { return step.trim().startsWith("{") && step.endsWith("}"); } private WadlHelper(); static List<Param> getRequestParams(final Method method); static final String computeId(final Method method, final Resource resource, final Resources resources,
final Application app, final Stack<Resource> ancestors); static final String titleCase(final String text); static final List<T> reverse(final List<T> strings); static final boolean isVersion(final String step); static final String parseTemplateParam(final String step); static final List<String> toSteps(final Resource resource, final Stack<Resource> ancestors); static final boolean isTemplateParam(final String step); }### Answer:
@Test public void testIsTemplateParam() throws Exception { String templateParam = "{paramName}"; String nonTemplateParam = "blah"; assertTrue(WadlHelper.isTemplateParam(templateParam)); assertFalse(WadlHelper.isTemplateParam(nonTemplateParam)); } |
### Question:
XsdReader { public static final XmlSchema readSchema(final String fileName, final URIResolver schemaResolver) throws FileNotFoundException { final InputStream istream = new BufferedInputStream(new FileInputStream(fileName)); try { return readSchema(istream, schemaResolver); } finally { closeQuiet(istream); } } static final XmlSchema readSchema(final String fileName, final URIResolver schemaResolver); static final XmlSchema readSchema(final File file, final URIResolver schemaResolver); }### Answer:
@Test public void testReadSchemaUsingFile() throws FileNotFoundException, URISyntaxException { final URIResolver mockResolver = mock(URIResolver.class); final File testXSD = new File(getClass().getResource("/test.xsd").toURI()); final XmlSchema schema = XsdReader.readSchema(testXSD, mockResolver); testReadSchema(schema); }
@Test public void testReadSchemaUsingString() throws URISyntaxException, FileNotFoundException { final URIResolver mockResolver = mock(URIResolver.class); final String testXSD = new File(getClass().getResource("/test.xsd").toURI()).getAbsolutePath(); final XmlSchema schema = XsdReader.readSchema(testXSD, mockResolver); testReadSchema(schema); } |
### Question:
SeaCustomDataProvider { public Map<String, List<SliEntityLocator>> getIdMap(String seaGuid) { LOG.info("Attempting to pull id map from SEA custom data, will cause exception if doesn't exist"); List<Entity> list = slcInterface.read("/educationOrganizations/" + seaGuid + "/custom"); if (list.size() > 0) { Map<String, Object> rawMap = list.get(0).getData(); return toSpecificMap(rawMap); } return new HashMap<String, List<SliEntityLocator>>(); } Map<String, List<SliEntityLocator>> getIdMap(String seaGuid); void storeIdMap(String seaGuid, Map<String, List<SliEntityLocator>> idMap); }### Answer:
@Test public void testGetMap() { String seaGuid = "asladfalsd"; String url = "/educationOrganizations/" + seaGuid + "/custom"; Mockito.when(mockSlcInterface.read(url)).thenReturn(buildCustomDataList()); Map<String, List<SliEntityLocator>> result = dataProvider.getIdMap(seaGuid); Assert.assertNotNull(result); Assert.assertEquals(1, result.keySet().size()); List<SliEntityLocator> list = result.get(SIF_ID); Assert.assertNotNull(list); Assert.assertEquals(1, list.size()); SliEntityLocator locator = list.get(0); Assert.assertEquals(TYPE, locator.getType()); Assert.assertEquals(VALUE, locator.getValue()); Assert.assertEquals(FIELD, locator.getField()); } |
### Question:
ResourceDocumentation { public void addDocumentation() throws IOException, XPathException { final NodeList topLevelResources = manipulator.getNodeList(this.doc, " for (int i = 0; i < topLevelResources.getLength(); i++) { final Node node = topLevelResources.item(i); final ResourceEndPointTemplate resourceTemplate = getResourceTemplate(node); if (resourceTemplate != null) { addTag(node, "doc", resourceTemplate.getDoc()); addTag(node, "deprecatedVersion", resourceTemplate.getDeprecatedVersion()); addTag(node, "deprecatedReason", resourceTemplate.getDeprecatedReason()); addTag(node, "availableSince", resourceTemplate.getAvailableSince()); } } } ResourceDocumentation(final Document doc); ResourceDocumentation(final Document doc, final String resourceLoc); void addDocumentation(); }### Answer:
@Test public void testAddDocumentation() throws Exception { NodeList section = documentManipulator.getNodeList(testWadl, " assertEquals(1, section.getLength()); Node sectionNodeDoc = documentManipulator.getNodeList(testWadl, " assertNotNull(sectionNodeDoc); assertEquals("test /sections doc", sectionNodeDoc.getFirstChild().getNodeValue()); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public String getZoneSea(String zoneId) { synchronized (lock) { Map<String, SliEntityLocator> seaMap = zoneMapProvider.getZoneToSliIdMap(); SliEntityLocator locator = seaMap.get(zoneId); Entity seaEntity = fetchSliEntity(locator); if (seaEntity == null) { return null; } return seaEntity.getId(); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getZoneSeaShouldLookupSeaGuid() throws Exception { when(mockZoneMapProvider.getZoneToSliIdMap()).thenReturn(getDummySeaIdMap()); Entity seaEntity = Mockito.mock(Entity.class); when(seaEntity.getId()).thenReturn(SEA_ID2); List<Entity> queryResult = Arrays.asList(new Entity[] { seaEntity }); when(mockSlcInterface.read(eq(SLI_TYPE_SEA2), queryCaptor.capture())).thenReturn(queryResult); String seaId = resolver.getZoneSea(ZONE_ID2); Assert.assertEquals(1, queryCaptor.getAllValues().size()); Assert.assertEquals(SLI_VALUE_SEA2, queryCaptor.getAllValues().get(0).getParameters().get(SLI_FIELD_SEA2)); Assert.assertEquals(SEA_ID2, seaId); } |
### Question:
DeltaExtractor implements InitializingBean { public void execute(String tenant, File tenantDirectory, DateTime deltaUptoTime) { TenantContext.setTenantId(tenant); audit(securityEventUtil.createSecurityEvent(this.getClass().getName(), "Delta Extract Initiation", LogLevelType.TYPE_INFO, BEMessageCode.BE_SE_CODE_0019, DATE_TIME_FORMATTER.print(deltaUptoTime))); Map<String, Set<String>> appsPerEdOrg = appsPerEdOrg(); ExtractFile publicDeltaExtractFile = createPublicExtractFile(tenantDirectory, deltaUptoTime); deltaEntityIterator.init(tenant, deltaUptoTime); while (deltaEntityIterator.hasNext()) { DeltaRecord delta = deltaEntityIterator.next(); if (delta.getOp() == Operation.UPDATE) { extractUpdate(delta, publicDeltaExtractFile, appsPerEdOrg, tenantDirectory, deltaUptoTime); } else if (delta.getOp() == Operation.DELETE) { extractDelete(delta, publicDeltaExtractFile, appsPerEdOrg, tenantDirectory, deltaUptoTime); } else if (delta.getOp() == Operation.PURGE) { extractPurge(delta, publicDeltaExtractFile, appsPerEdOrg, tenantDirectory, deltaUptoTime); } } logEntityCounts(); audit(securityEventUtil.createSecurityEvent(this.getClass().getName(), "Delta Extract Finished", LogLevelType.TYPE_INFO, BEMessageCode.BE_SE_CODE_0021, DATE_TIME_FORMATTER.print(deltaUptoTime))); finalizeExtraction(tenant, deltaUptoTime); } @Override void afterPropertiesSet(); void execute(String tenant, File tenantDirectory, DateTime deltaUptoTime); void setSecurityEventUtil(SecurityEventUtil securityEventUtil); static final DateTimeFormatter DATE_TIME_FORMATTER; static final String DATE_FIELD; static final String TIME_FIELD; }### Answer:
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPublicAndPrivate() { when(deltaEntityIterator.hasNext()).thenReturn(true, true, true, false); when(deltaEntityIterator.next()).thenReturn(buildUpdatePublicRecord(), buildDeleteRecord(), buildUpdatePrivateRecord()); extractor.execute("Midgar", null, new DateTime()); verify(entityExtractor, times(2)).write(any(Entity.class), any(ExtractFile.class), any(EntityExtractor.CollectionWrittenRecord.class), (Predicate) Mockito.isNull()); verify(entityWriteManager, times(14)).writeDeleteFile(any(Entity.class), any(ExtractFile.class)); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testPrivateOnly() { when(deltaEntityIterator.hasNext()).thenReturn(true, true, false); when(deltaEntityIterator.next()).thenReturn(buildUpdatePrivateRecord(), buildDeleteRecord()); extractor.execute("Midgar", null, new DateTime()); verify(entityExtractor, times(1)).write(any(Entity.class), any(ExtractFile.class), any(EntityExtractor.CollectionWrittenRecord.class), (Predicate) Mockito.isNull()); verify(entityWriteManager, times(8)).writeDeleteFile(any(Entity.class), any(ExtractFile.class)); }
@Test public void testPurge() { when(deltaEntityIterator.hasNext()).thenReturn(true, false); when(deltaEntityIterator.next()).thenReturn(buildPurgeRecord()); extractor.execute("Midgar", null, new DateTime()); verify(entityWriteManager, times(3)).writeDeleteFile(any(Entity.class), any(ExtractFile.class)); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public List<Entity> getSliEntityList(String sifId, String zoneId) { synchronized (lock) { String seaId = getZoneSea(zoneId); Map<String, List<SliEntityLocator>> idMap = customDataProvider.getIdMap(seaId); List<SliEntityLocator> locators = idMap.get(sifId); if (locators == null || locators.size() == 0) { LOG.error("No sif-sli mapping found for sifId: " + sifId); return new ArrayList<Entity>(); } List<Entity> entities = new ArrayList<Entity>(); for (SliEntityLocator locator : locators) { Entity entity = fetchSliEntity(locator); entities.add(entity); } return entities; } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliEntityListShouldLookupSliEntities() throws Exception { setupCustomDataMocking(); List<Entity> expected = new ArrayList<Entity>(); Entity entity = new GenericEntity(SLI_TYPE3A, new HashMap<String, Object>()); List<Entity> queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3A), any(Query.class))).thenReturn(queryResult); expected.add(entity); entity = new GenericEntity(SLI_TYPE3B, new HashMap<String, Object>()); queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3B), any(Query.class))).thenReturn(queryResult); expected.add(entity); List<Entity> result = resolver.getSliEntityList(SIF_REF_ID3, ZONE_ID1); verify(mockSlcInterface, times(3)).read(Mockito.anyString(), any(Query.class)); verify(mockSlcInterface, times(1)).read(eq(SLI_TYPE3A), any(Query.class)); verify(mockSlcInterface, times(1)).read(eq(SLI_TYPE3B), any(Query.class)); Assert.assertEquals(expected.size(), result.size()); Assert.assertEquals(expected.get(0), result.get(0)); Assert.assertEquals(expected.get(1), result.get(1)); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId) { synchronized (lock) { return getSliEntity(sifId + "-" + sliType, zoneId); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliEntityFromOtherSifIdShouldLookupSliEntities() throws Exception { setupCustomDataMocking(); Entity expected = new GenericEntity(SLI_TYPE4, new HashMap<String, Object>()); List<Entity> queryResult = Arrays.asList(new Entity[] { expected }); when(mockSlcInterface.read(eq(SLI_TYPE4), any(Query.class))).thenReturn(queryResult); Entity result = resolver.getSliEntityFromOtherSifId(SIF_REF_ID4, SLI_TYPE4, ZONE_ID1); assertEquals(expected, result); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public String getSliGuid(String sifId, String zoneId) { synchronized (lock) { Entity entity = getSliEntity(sifId, zoneId); if (entity == null) { LOG.info("No sli id found for sifId(" + sifId + ")"); return null; } return entity.getId(); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliGuidShouldFindGuid() throws Exception { setupCustomDataMocking(); Entity expected = Mockito.mock(Entity.class); when(expected.getId()).thenReturn(SLI_ID1); List<Entity> queryResult = Arrays.asList(new Entity[] { expected }); when(mockSlcInterface.read(eq(SLI_TYPE1), any(Query.class))).thenReturn(queryResult); String result = resolver.getSliGuid(SIF_REF_ID1, ZONE_ID1); assertEquals(SLI_ID1, result); }
@Test public void getSliGuidShouldHandleNull() throws Exception { setupCustomDataMocking(); List<Entity> queryResult = Collections.emptyList(); when(mockSlcInterface.read(eq(SLI_TYPE1), any(Query.class))).thenReturn(queryResult); String result = resolver.getSliGuid(SIF_REF_ID1, ZONE_ID1); Assert.assertNull(result); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public List<String> getSliGuidList(String sifId, String zoneId) { synchronized (lock) { List<Entity> entityList = getSliEntityList(sifId, zoneId); List<String> idList = new ArrayList<String>(); for (Entity entity : entityList) { idList.add(entity.getId()); } return idList; } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliGuidListShouldLookupSliEntities() throws Exception { setupCustomDataMocking(); List<Entity> expected = new ArrayList<Entity>(); Entity entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3A); List<Entity> queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3A), any(Query.class))).thenReturn(queryResult); expected.add(entity); entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3B); queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3B), any(Query.class))).thenReturn(queryResult); expected.add(entity); List<String> result = resolver.getSliGuidList(SIF_REF_ID3, ZONE_ID1); Assert.assertEquals(expected.size(), result.size()); Assert.assertEquals(SLI_ID3A, result.get(0)); Assert.assertEquals(SLI_ID3B, result.get(1)); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId) { synchronized (lock) { return getSliEntityList(sifId + "-" + sliType, zoneId); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliEntityListByTypeShouldLookupSliEntities() throws Exception { setupCustomDataMocking(); List<Entity> expected = new ArrayList<Entity>(); Entity entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3A); List<Entity> queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3A), any(Query.class))).thenReturn(queryResult); expected.add(entity); entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3B); queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3B), any(Query.class))).thenReturn(queryResult); expected.add(entity); List<Entity> result = resolver.getSliEntityListByType(SIF_REF_ID3, SLI_TYPE3A, ZONE_ID1); verify(mockSlcInterface, times(3)).read(Mockito.anyString(), any(Query.class)); verify(mockSlcInterface, times(1)).read(eq(SLI_TYPE3A), any(Query.class)); verify(mockSlcInterface, times(1)).read(eq(SLI_TYPE3B), any(Query.class)); Assert.assertEquals(expected.size(), result.size()); Assert.assertEquals(expected.get(0), result.get(0)); Assert.assertEquals(expected.get(1), result.get(1)); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public Entity getSliEntityByType(String sifId, String sliType, String zoneId) { synchronized (lock) { return getSliEntity(sifId + "-" + sliType, zoneId); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliEntityByTypeShouldLookupSliEntities() throws Exception { setupCustomDataMocking(); Entity expected = new GenericEntity(SLI_TYPE4, new HashMap<String, Object>()); List<Entity> queryResult = Arrays.asList(new Entity[] { expected }); when(mockSlcInterface.read(eq(SLI_TYPE4), any(Query.class))).thenReturn(queryResult); Entity result = resolver.getSliEntityByType(SIF_REF_ID4, SLI_TYPE4, ZONE_ID1); assertEquals(expected, result); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public List<String> getSliGuidListByType(String sifId, String sliType, String zoneId) { synchronized (lock) { List<Entity> entityList = getSliEntityListByType(sifId, sliType, zoneId); List<String> idList = new ArrayList<String>(); for (Entity entity : entityList) { idList.add(entity.getId()); } return idList; } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliGuidListByTypeShouldLookupSliGuids() throws Exception { setupCustomDataMocking(); List<Entity> expected = new ArrayList<Entity>(); Entity entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3A); List<Entity> queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3A), any(Query.class))).thenReturn(queryResult); expected.add(entity); entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID3B); queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE3B), any(Query.class))).thenReturn(queryResult); expected.add(entity); List<String> result = resolver.getSliGuidListByType(SIF_REF_ID3, SLI_TYPE3A, ZONE_ID1); Assert.assertEquals(expected.size(), result.size()); Assert.assertEquals(SLI_ID3A, result.get(0)); Assert.assertEquals(SLI_ID3B, result.get(1)); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public String getSliGuidByType(String sifId, String sliType, String zoneId) { synchronized (lock) { Entity entity = getSliEntityFromOtherSifId(sifId, sliType, zoneId); if (entity == null) { return null; } return entity.getId(); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void getSliGuidByTypeShouldLookupSliGuid() throws Exception { setupCustomDataMocking(); Entity entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID4); List<Entity> queryResult = Arrays.asList(new Entity[] { entity }); when(mockSlcInterface.read(eq(SLI_TYPE4), any(Query.class))).thenReturn(queryResult); String result = resolver.getSliGuidByType(SIF_REF_ID4, SLI_TYPE4, ZONE_ID1); assertEquals(SLI_ID4, result); }
@Test public void getSliGuidByTypeShouldHandleNull() throws Exception { setupCustomDataMocking(); Entity entity = Mockito.mock(Entity.class); when(entity.getId()).thenReturn(SLI_ID4); List<Entity> queryResult = Arrays.asList(new Entity[] {}); when(mockSlcInterface.read(eq(SLI_TYPE4), any(Query.class))).thenReturn(queryResult); String result = resolver.getSliGuidByType(SIF_REF_ID4, SLI_TYPE4, ZONE_ID1); Assert.assertNull(result); } |
### Question:
SifIdResolverCustomData implements SifIdResolver { @Override public void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId) { synchronized (lock) { String key = sifId + "-" + sliType; putSliGuid(key, sliType, sliId, zoneId); } } @Override String getSliGuid(String sifId, String zoneId); @Override List<String> getSliGuidList(String sifId, String zoneId); @Override String getSliGuidByType(String sifId, String sliType, String zoneId); @Override List<String> getSliGuidListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntityByType(String sifId, String sliType, String zoneId); @Override List<Entity> getSliEntityListByType(String sifId, String sliType, String zoneId); @Override Entity getSliEntity(String sifId, String zoneId); @Override List<Entity> getSliEntityList(String sifId, String zoneId); @Override String getZoneSea(String zoneId); @Override void putSliGuid(String sifId, String sliType, String sliId, String zoneId); @Override Entity getSliEntityFromOtherSifId(String sifId, String sliType, String zoneId); @Override void putSliGuidForOtherSifId(String sifId, String sliType, String sliId, String zoneId); }### Answer:
@Test public void putSliGuidForOtherSifIdStoreNewId() throws Exception { Map<String, List<SliEntityLocator>> idMap = setupCustomDataMocking(); when(mockSeaCustomDataProvider.getIdMap(SEA_ID1)).thenReturn(idMap); resolver.putSliGuidForOtherSifId("newSifId", "sliType", "sliId", ZONE_ID1); List<SliEntityLocator> resultList = idMap.get("newSifId-sliType"); Assert.assertNotNull(resultList); Assert.assertEquals(1, resultList.size()); SliEntityLocator locator = resultList.get(0); Assert.assertEquals("sliType", locator.getType()); Assert.assertEquals("sliId", locator.getValue()); Assert.assertEquals(ParameterConstants.ID, locator.getField()); } |
### Question:
AgentManager { public void setup() throws Exception { System.setProperty("adk.log.file", logPath + File.separator + adkLogFile); ADK.initialize(); ADK.debug = ADK.DBG_ALL; agent.startAgent(); subscribeToZone(); } @PostConstruct void postConstruct(); void setup(); @PreDestroy void cleanup(); void setSubscribeTypeList(List<String> subscribeTypeList); List<String> getSubscribeTypeList(); void setSubscriberZoneName(String subscriberZoneName); String getSubscriberZoneName(); void setAgent(SifAgent agent); SifAgent getAgent(); String getLogPath(); void setLogPath(String logPath); String getAdkLogFile(); void setAdkLogFile(String adkLogFile); List<ElementDef> getSubscribeList(); void setSubscribeList(List<ElementDef> subscribeList); }### Answer:
@Test public void shouldStartAgentOnSetup() throws Exception { agentManager.setup(); Mockito.verify(mockAgent, Mockito.times(1)).startAgent(); }
@Test public void shouldSubscribeToZoneOnSetup() throws Exception { agentManager.setup(); Mockito.verify(mockAgent, Mockito.times(1)).startAgent(); Mockito.verify(mockZone, Mockito.times(1)).setSubscriber(Mockito.any(SifSubscriber.class), Mockito.any(ElementDef.class), Mockito.any(SubscriptionOptions.class)); SifAgent agent = new SifAgent(); Assert.assertTrue("SifAgent should extend", agent instanceof Agent); } |
### Question:
AgentManager { @PreDestroy public void cleanup() throws ADKException { agent.shutdown(ADKFlags.PROV_NONE); } @PostConstruct void postConstruct(); void setup(); @PreDestroy void cleanup(); void setSubscribeTypeList(List<String> subscribeTypeList); List<String> getSubscribeTypeList(); void setSubscriberZoneName(String subscriberZoneName); String getSubscriberZoneName(); void setAgent(SifAgent agent); SifAgent getAgent(); String getLogPath(); void setLogPath(String logPath); String getAdkLogFile(); void setAdkLogFile(String adkLogFile); List<ElementDef> getSubscribeList(); void setSubscribeList(List<ElementDef> subscribeList); }### Answer:
@Test public void shouldShutdownAgentOnCleanup() throws ADKException { agentManager.cleanup(); Mockito.verify(mockAgent, Mockito.times(1)).shutdown(Mockito.eq(ADKFlags.PROV_NONE)); } |
### Question:
SifAgent extends Agent { public void startAgent() throws Exception { super.initialize(); setProperties(); Zone[] allZones = getZoneFactory().getAllZones(); zoneConfigurator.configure(allZones); } SifAgent(); SifAgent(String id); SifAgent(String id, ZoneConfigurator zoneConfig, Properties agentProperties,
Properties httpProperties, Properties httpsProperties, String zoneId,
String zoneUrl, SIFVersion sifVersion); void startAgent(); void setConfigFilePath(String configFilePath); String getConfigFilePath(); void setZoneConfigurator(ZoneConfigurator zoneConfigurator); ZoneConfigurator getZoneConfigurator(); void setAgentProperties(Properties agentProperties); Properties getAgentProperties(); void setHttpProperties(Properties httpProperties); Properties getHttpProperties(); void setHttpsProperties(Properties httpsProperties); Properties getHttpsProperties(); void setSifVersion(SIFVersion sifVersion); SIFVersion getSifVersion(); }### Answer:
@Test public void shouldCreateAndConfigureAgent() throws Exception { ZoneConfigurator mockZoneConfigurator = Mockito.mock(ZoneConfigurator.class); SifAgent agent = createSifAgent(mockZoneConfigurator); agent.startAgent(); AgentProperties props = agent.getProperties(); Assert.assertEquals("Push", props.getProperty("adk.messaging.mode")); Assert.assertEquals("http", props.getProperty("adk.messaging.transport")); Assert.assertEquals("30000", props.getProperty("adk.messaging.pullFrequency")); Assert.assertEquals("32000", props.getProperty("adk.messaging.maxBufferSize")); Assert.assertEquals("test.publisher.agent", agent.getId()); TransportManager transportManager = agent.getTransportManager(); Transport transport = transportManager.getTransport("http"); TransportProperties transportProperties = transport.getProperties(); Assert.assertEquals("25101", transportProperties.getProperty("port")); Zone[] allZones = agent.getZoneFactory().getAllZones(); Assert.assertNotNull("Agents zones should not be null", allZones); Assert.assertEquals("Agent should be configured with one zone", 1, allZones.length); Assert.assertNotNull("Agent's zone should not be null", allZones[0]); Assert.assertEquals("Agent's zone Id should be TestZone", "TestZone", allZones[0].getZoneId()); Assert.assertEquals("Agent's zone URL should be http: "http: Mockito.verify(mockZoneConfigurator, Mockito.times(1)).configure(Mockito.any(Zone[].class)); } |
### Question:
StudentPersonalTranslationTask extends AbstractTranslationTask<StudentPersonal, StudentEntity> { private List<String> getHomeLanguages(LanguageList languageList) { Language[] languages = languageList == null ? null : languageList.getLanguages(); if (languages == null) { return null; } LanguageList homeList = new LanguageList(); for (Language language : languages) { if (language.getLanguageType() != null && LanguageType.HOME.valueEquals(language.getLanguageType())) { homeList.add(language); } } return homeList.size() == 0 ? null : languageListConverter.convert(homeList); } StudentPersonalTranslationTask(); @Override List<StudentEntity> doTranslate(StudentPersonal sifData, String zoneId); }### Answer:
@Test public void testLanguages() throws SifTranslationException { StudentPersonal info = new StudentPersonal(); Demographics demographics = new Demographics(); LanguageList languageList = new LanguageList(); languageList.addLanguage(LanguageCode.ENGLISH); languageList.addLanguage(LanguageCode.CHINESE); demographics.setLanguageList(languageList); info.setDemographics(demographics); Mockito.when(mockLanguageListConverter.convert(Mockito.any(LanguageList.class))).thenReturn(Arrays.asList("English", "Chinese")); List<StudentEntity> result = translator.translate(info, null); Assert.assertEquals(1, result.size()); StudentEntity entity = result.get(0); List<String> list = entity.getLanguages(); Assert.assertEquals(2, list.size()); Assert.assertEquals("language[0] is expected to be 'English'", "English", list.get(0)); Assert.assertEquals("language[1] is expected to be 'Chinese'", "Chinese", list.get(1)); list = entity.getHomeLanguages(); Assert.assertNull("Home Languages was not null", list); } |
### Question:
SifTranslationManager { public List<SliEntity> translate(SIFDataObject sifData, String zoneId) { List<SliEntity> entities = new ArrayList<SliEntity>(); List<TranslationTask> translationTasks = translationMap.get(sifData.getObjectType().toString()); if (translationTasks == null) { LOG.error("No TranslationTask found for sif type: " + sifData.getObjectType()); return entities; } for (TranslationTask translationTask : translationTasks) { try { entities.addAll(translationTask.translate(sifData, zoneId)); } catch (SifTranslationException e) { LOG.error("Sif translation exception: ", e); } } return entities; } void setTranslationMap(Map<String, List<TranslationTask>> translationMap); List<SliEntity> translate(SIFDataObject sifData, String zoneId); }### Answer:
@Test public void shouldCreateOneToOneTranslatedEntities() { List<SliEntity> sliEntities = sifTranslationManager.translate(sifB, "zoneId"); Assert.assertEquals("Should translate to one sli entity", 1, sliEntities.size()); Assert.assertEquals("First translated entity not of correct", sliZ, sliEntities.get(0)); }
@Test public void shouldCreateOneToManyTranslatedEntities() { List<SliEntity> sliEntities = sifTranslationManager.translate(sifA, "zoneId"); Assert.assertEquals("Should translate to two sli entities", 2, sliEntities.size()); Assert.assertEquals("First translated entity not of correct", sliX, sliEntities.get(0)); Assert.assertEquals("First translated entity not of correct", sliY, sliEntities.get(1)); }
@Test public void shouldHandleSifTranslationExceptions() throws SifTranslationException { Mockito.when(mockTranslationBtoZ.translate(Mockito.eq(sifB), Mockito.anyString())).thenThrow( new SifTranslationException("test throw")); sifTranslationManager.translate(sifA, "zoneId"); } |
### Question:
PublishZoneConfigurator implements ZoneConfigurator { @Override public void configure(Zone[] allZones) { for (Zone zone : allZones) { try { LOG.info("- Connecting to zone \"" + zone.getZoneId() + "\" at " + zone.getZoneUrl()); zone.connect(ADKFlags.PROV_REGISTER | ADKFlags.PROV_PROVIDE); } catch (ADKException ex) { LOG.error(" " + ex.getMessage(), ex); } } } @Override void configure(Zone[] allZones); }### Answer:
@Test public void testConfigure() throws ADKException { Zone[] zones = {zone1, zone2, zone3}; publishZoneConfigurator.configure(zones); Mockito.verify(zone1, Mockito.times(1)).connect(Mockito.anyInt()); Mockito.verify(zone2, Mockito.times(1)).connect(Mockito.anyInt()); Mockito.verify(zone3, Mockito.times(1)).connect(Mockito.anyInt()); Assert.assertTrue(publishZoneConfigurator instanceof ZoneConfigurator); } |
### Question:
SubscribeZoneConfigurator implements ZoneConfigurator { @Override public void configure(Zone[] allZones) { for (Zone zone : allZones) { try { LOG.info("- Connecting to zone \"" + zone.getZoneId() + "\" at " + zone.getZoneUrl()); zone.connect(ADKFlags.PROV_REGISTER | ADKFlags.PROV_SUBSCRIBE); } catch (ADKException ex) { LOG.error(" " + ex.getMessage(), ex); } } } @Override void configure(Zone[] allZones); }### Answer:
@Test public void testConfigure() throws ADKException { Zone[] zones = {zone1, zone2, zone3}; subscribeZoneConfigurator.configure(zones); Mockito.verify(zone1, Mockito.times(1)).connect(Mockito.anyInt()); Mockito.verify(zone2, Mockito.times(1)).connect(Mockito.anyInt()); Mockito.verify(zone3, Mockito.times(1)).connect(Mockito.anyInt()); Assert.assertTrue(subscribeZoneConfigurator instanceof ZoneConfigurator); } |
### Question:
SliEntity { public Map<String, Object> createBody() { Map<String, Object> body = null; try { body = MAPPER. readValue(this.json(), new TypeReference<Map<String, Object>>() { }); clearNullValueKeys(body); } catch (JsonParseException e) { LOG.error("Entity map conversion error: ", e); } catch (JsonMappingException e) { LOG.error("Entity map conversion error: ", e); } catch (IOException e) { LOG.error("Entity map conversion error: ", e); } return body; } SliEntity(); abstract String entityType(); GenericEntity createGenericEntity(); Map<String, Object> createBody(); JsonNode json(); @JsonIgnore boolean isCreatedByOthers(); @JsonIgnore String getCreatorRefId(); @JsonIgnore void setCreatorRefId(String creatorRefId); @JsonIgnore String getZoneId(); @JsonIgnore void setZoneId(String zoneId); @JsonIgnore String getOtherSifRefId(); @JsonIgnore void setOtherSifRefId(String otherSifRefId); @JsonIgnore boolean hasOtherSifRefId(); @Override String toString(); }### Answer:
@Test public void shouldTransformConcreteBodyToMap() { testSliEntity = new TestSliEntity(); Map<String, Object> body = testSliEntity.createBody(); Assert.assertEquals("Body should contain 2 elements", 2, body.size()); Assert.assertEquals("Incorrect map element", "1", body.get("fieldOne")); @SuppressWarnings("unchecked") Map<String, Object> subObjectMap = (Map<String, Object>) body.get("testSubObject"); Assert.assertNotNull("SubObject map null", subObjectMap); Assert.assertEquals("subObject should contain 2 elements", 2, subObjectMap.size()); Assert.assertEquals("Incorrect map element", "A", subObjectMap.get("subFieldA")); Assert.assertEquals("Incorrect map element", "B", subObjectMap.get("subFieldB")); } |
### Question:
SliEntity { public GenericEntity createGenericEntity() { GenericEntity entity = new GenericEntity(entityType(), createBody()); return entity; } SliEntity(); abstract String entityType(); GenericEntity createGenericEntity(); Map<String, Object> createBody(); JsonNode json(); @JsonIgnore boolean isCreatedByOthers(); @JsonIgnore String getCreatorRefId(); @JsonIgnore void setCreatorRefId(String creatorRefId); @JsonIgnore String getZoneId(); @JsonIgnore void setZoneId(String zoneId); @JsonIgnore String getOtherSifRefId(); @JsonIgnore void setOtherSifRefId(String otherSifRefId); @JsonIgnore boolean hasOtherSifRefId(); @Override String toString(); }### Answer:
@Test public void shouldCreateGenericEntity() { testSliEntity = new TestSliEntity(); GenericEntity entity = testSliEntity.createGenericEntity(); Assert.assertNotNull("GenericEntity null", entity); Assert.assertNotNull("Entity body null", entity.getData()); Assert.assertEquals("Incorrect entity type", "TestEntity", entity.getEntityType()); } |
### Question:
YesNoUnknownConverter { public Boolean convert(String value) { return value == null ? null : BOOLEAN_MAP.get(value); } Boolean convert(String value); }### Answer:
@Test public void testNullObject() { Boolean result = converter.convert(null); Assert.assertNull("Race list should be null", result); }
@Test public void testYes() { Boolean result = converter.convert("Yes"); Assert.assertEquals(Boolean.TRUE, result); }
@Test public void testNo() { Boolean result = converter.convert("No"); Assert.assertEquals(Boolean.FALSE, result); }
@Test public void testUnknown() { Boolean result = converter.convert("Unknown"); Assert.assertNull(result); } |
### Question:
YesNoConverter { public Boolean convert(YesNo value) { return value == null ? null : BOOLEAN_MAP.get(value); } Boolean convert(YesNo value); }### Answer:
@Test public void testNullObject() { Boolean result = converter.convert(null); Assert.assertNull("Result should be null", result); }
@Test public void testYes() { Boolean result = converter.convert(YesNo.YES); Assert.assertEquals(Boolean.TRUE, result); }
@Test public void testNo() { Boolean result = converter.convert(YesNo.NO); Assert.assertEquals(Boolean.FALSE, result); }
@Test public void testUnknown() { Boolean result = converter.convert(YesNo.wrap("Unknown")); Assert.assertNull(result); } |
### Question:
EntityExtractor { public void extractEntities(ExtractFile archiveFile, String collectionName, Predicate<Entity> filter) { audit(securityEventUtil.createSecurityEvent(this.getClass().getName(), " Entity extraction", LogLevelType.TYPE_INFO, BEMessageCode.BE_SE_CODE_0024, collectionName)); if (extractionQuery == null) { extractionQuery = new NeutralQuery(); } Iterator<Entity> cursor = entityRepository.findEach(collectionName, extractionQuery); if (cursor.hasNext()) { LOG.info("Extracting from " + collectionName); CollectionWrittenRecord collectionRecord = new CollectionWrittenRecord(collectionName); while (cursor.hasNext()) { Entity entity = cursor.next(); write(entity, archiveFile, collectionRecord, filter); } LOG.info("Finished extracting " + collectionRecord.toString()); } } void extractEntities(ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void extractEntity(Entity entity, ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void extractEntity(Entity entity, ExtractFile archiveFile, String collectionName); void extractEmbeddedEntities(Entity entity, ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void write(Entity entity, ExtractFile archiveFile, CollectionWrittenRecord collectionRecord, Predicate<Entity> filter); void setEntityRepository(Repository<Entity> entityRepository); void setExtractionQuery(NeutralQuery extractionQuery); void setWriter(EntityWriterManager writer); }### Answer:
@SuppressWarnings("unchecked") @Test public void testExtractEntities() throws IOException { String testTenant = "Midgar"; String testEntity = "student"; Iterator<Entity> cursor = Mockito.mock(Iterator.class); List<Entity> students = TestUtils.createStudents(); Mockito.when(cursor.hasNext()).thenReturn(true, true, true, false); Mockito.when(cursor.next()).thenReturn(students.get(0), students.get(1)); Mockito.when(mongoEntityRepository.findEach(Matchers.eq(testEntity), Matchers.any(NeutralQuery.class))).thenReturn(cursor); extractor.extractEntities(archiveFile, testEntity, null); Mockito.verify(mongoEntityRepository, Mockito.times(1)).findEach("student", new NeutralQuery()); Mockito.verify(writer, Mockito.times(2)).write(Mockito.any(Entity.class), Mockito.any(ExtractFile.class)); } |
### Question:
DateConverter { public String convert(Calendar date) { if (date == null) { return null; } return dateFormat.format(date.getTime()); } String convert(Calendar date); }### Answer:
@Test public void shouldConvertWithCorrectFormat() { Calendar date = new GregorianCalendar(2004, Calendar.FEBRUARY, 29); String result = converter.convert(date); Assert.assertEquals("2004-02-29", result); }
@Test public void shouldHandleNullDate() { String result = converter.convert(null); Assert.assertNull(result); } |
### Question:
ElectronicIdListConverter { public List<StaffIdentificationCode> convert(ElectronicIdList electronicIdList) { if (electronicIdList == null) { return null; } return toSliStaffIdentificationCodeList(electronicIdList.getElectronicIds()); } List<StaffIdentificationCode> convert(ElectronicIdList electronicIdList); }### Answer:
@Test public void testNullObject() { List<StaffIdentificationCode> result = converter.convert((ElectronicIdList) null); Assert.assertNull("StaffIdentificationCode list should be null", result); result = converter.convert((ElectronicIdList) null); Assert.assertNull("StaffIdentificationCode list should be null", result); }
@Test public void testEmptyElectronicIdList() { ElectronicIdList list = new ElectronicIdList(); list.setElectronicIds(new ElectronicId[0]); List<StaffIdentificationCode> result = converter.convert(list); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyElectronicId4ElectronicIdList() { ElectronicIdList list = new ElectronicIdList(); ElectronicId original = new ElectronicId(); list.add(original); List<StaffIdentificationCode> result = converter.convert(list); Assert.assertEquals(1, result.size()); StaffIdentificationCode it = result.get(0); Assert.assertEquals(original.getValue(), it.getID()); Assert.assertEquals("Other", it.getIdentificationSystem()); }
@Test public void testMappings() { map.clear(); map.put(ElectronicIdType.BARCODE, "Other"); map.put(ElectronicIdType.MAGSTRIPE, "Other"); map.put(ElectronicIdType.PIN, "PIN"); map.put(ElectronicIdType.RFID, "Other"); ElectronicIdList list = getElectronicIdList(); List<StaffIdentificationCode> results = converter.convert(list); Assert.assertEquals(list.size(), results.size()); int newCounter = 0; for (StaffIdentificationCode it : results) { Assert.assertNotNull(it); ElectronicId original = list.get(newCounter++); testMapping(original, it); } ElectronicIdList list2 = getElectronicIdList(); List<StaffIdentificationCode> results2 = converter.convert(list2); Assert.assertEquals(list2.size(), results2.size()); newCounter = 0; for (StaffIdentificationCode it : results2) { Assert.assertNotNull(it); ElectronicId original = list2.get(newCounter++); testMapping(original, it); } } |
### Question:
SchoolFocusConverter { public String convert(SchoolFocusList schoolFocusList) { if (schoolFocusList == null || schoolFocusList.getSchoolFocuses().length == 0) { return null; } SchoolFocus[] schoolFocus = schoolFocusList.getSchoolFocuses(); String result = SCHOOL_FOCUS_MAP.get(schoolFocus[0].getValue()); if (result != null) { return result; } return NOT_SUPPORTED; } String convert(SchoolFocusList schoolFocusList); }### Answer:
@Test public void testNullList() { String result = converter.convert(null); Assert.assertNull("school type should be null", result); }
@Test public void testEmptyList() { SchoolFocusList list = new SchoolFocusList(); String result = converter.convert(list); Assert.assertNull("school type should be null", result); }
@Test public void testEmptySchoolFocus() { SchoolFocusList list = new SchoolFocusList(new SchoolFocus()); String result = converter.convert(list); Assert.assertEquals("Not Supported", result); } |
### Question:
EntityExtractor { public void extractEntity(Entity entity, ExtractFile archiveFile, String collectionName, Predicate<Entity> filter) { if (archiveFile != null) { write(entity, archiveFile, new CollectionWrittenRecord(collectionName), filter); } } void extractEntities(ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void extractEntity(Entity entity, ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void extractEntity(Entity entity, ExtractFile archiveFile, String collectionName); void extractEmbeddedEntities(Entity entity, ExtractFile archiveFile, String collectionName, Predicate<Entity> filter); void write(Entity entity, ExtractFile archiveFile, CollectionWrittenRecord collectionRecord, Predicate<Entity> filter); void setEntityRepository(Repository<Entity> entityRepository); void setExtractionQuery(NeutralQuery extractionQuery); void setWriter(EntityWriterManager writer); }### Answer:
@Test public void testExtractEntity() throws IOException { extractor.extractEntity(Mockito.mock(Entity.class), Mockito.mock(ExtractFile.class), "BLOOP"); Mockito.verify(writer, Mockito.times(1)).write(Mockito.any(Entity.class), Mockito.any(ExtractFile.class)); } |
### Question:
JobClassificationConverter { public String convert(JobClassification jobClassification) { if (jobClassification == null) { return null; } return toSliEntryType(JobClassificationCode.wrap(jobClassification.getCode())); } String convert(JobClassification jobClassification); }### Answer:
@Test public void testNullObject() { String result = converter.convert(null); Assert.assertNull("Entry Type should be null", result); }
@Test public void testMappings() { Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.ATHLETIC_TRAINER)), "Athletic Trainer"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.INTERPRETER)), "Certified Interpreter"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.COUNSELOR)), "Counselor"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.TEACHING_CLASSROOM_AIDE)), "Instructional Aide"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.LIBRARIAN_MEDIA_CONSULTANT)), "Librarians/Media Specialists"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.PRINCIPAL_HEADMASTER_HEADMISTRESS)), "Principal"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.PHYSICAL_THERAPIST)), "Physical Therapist"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.RESPIRATORY_THERAPIST)), "Physical Therapist"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.TEACHER)), "Teacher"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.SUPERINTENDENT_COMMISSIONER)), "Superintendent"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.NURSE_PRACTITIONER)), "School Nurse"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.LICENSED_PRACTICAL_NURSE)), "School Nurse"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.REGISTERED_NURSE)), "School Nurse"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.OFFICIAL_ADMINISTRATIVE)), "School Administrator"); Assert.assertEquals(converter.convert(getJobClassification(JobClassificationCode.OFFICE_CLERICAL_ADMINISTRATIVE)), "School Administrative Support Staff"); } |
### Question:
EmailListConverter { public List<ElectronicMail> convert(EmailList list) { if (list == null) { return null; } List<ElectronicMail> result = new ArrayList<ElectronicMail>(); for (Email sifEmail : list) { ElectronicMail sliEmail = new ElectronicMail(); sliEmail.setEmailAddress(sifEmail.getValue()); result.add(sliEmail); } return result; } List<ElectronicMail> convert(EmailList list); }### Answer:
@Test public void testNullObject() { List<ElectronicMail> result = converter.convert(null); Assert.assertNull("Address list should be null", result); }
@Test public void testEmptyList() { EmailList list = new EmailList(); List<ElectronicMail> result = converter.convert(list); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyEmail() { EmailList list = new EmailList(); list.add(new Email()); List<ElectronicMail> result = converter.convert(list); Assert.assertEquals(1, result.size()); ElectronicMail sliEmail = result.get(0); Assert.assertNull(sliEmail.getEmailAddressType()); Assert.assertNull(sliEmail.getEmailAddress()); }
@Test public void testMappings() { EmailList emails = createEmailList(); List<ElectronicMail> result = converter.convert(emails); Assert.assertEquals("Should map 5 emails", 5, result.size()); for (int i = 0; i < 5; i++) { Assert.assertNotNull(result.get(i)); Assert.assertEquals(result.get(i).getEmailAddress(), "email" + i); Assert.assertEquals(result.get(i).getEmailAddressType(), null); } } |
### Question:
TreatmentApplicator implements Treatment { @Override public Entity apply(Entity entity) { Entity treated = entity; for (Treatment treatment : treatments) { treated = treatment.apply(treated); } return treated; } @Override Entity apply(Entity entity); List<Treatment> getTreatments(); void setTreatments(List<Treatment> treatments); }### Answer:
@Test public void testApplyAll() { Entity student = Mockito.mock(Entity.class); applicator.apply(student); Mockito.verify(treatment1,Mockito.atLeast(1)).apply(Mockito.any(Entity.class)); Mockito.verify(treatment2,Mockito.atLeast(1)).apply(Mockito.any(Entity.class)); } |
### Question:
DemographicsToBirthDataConverter { public BirthData convert(Demographics sifDemographics) { if (sifDemographics == null) { return null; } BirthData sliBirthData = new BirthData(); sliBirthData.setCountryOfBirthCode(sifDemographics.getCountryOfBirth()); sliBirthData.setCityOfBirth(sifDemographics.getPlaceOfBirth()); if (SLI_STATE_CODES.contains(sifDemographics.getStateOfBirth())) { sliBirthData.setStateOfBirthAbbreviation(sifDemographics.getStateOfBirth()); } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (sifDemographics.getBirthDate() != null) { sliBirthData.setBirthDate(dateFormat.format(sifDemographics.getBirthDate().getTime())); } if (sifDemographics.getCountryArrivalDate() != null) { sliBirthData.setDateEnteredUS(dateFormat.format(sifDemographics.getCountryArrivalDate().getTime())); } return sliBirthData; } BirthData convert(Demographics sifDemographics); }### Answer:
@Test public void nullNameShouldReturnNull() { openadk.library.common.Demographics sifDemographics = null; BirthData sliName = converter.convert(sifDemographics); Assert.assertNull(sliName); }
@Test public void emptySifDemographicShouldMapToNullBirthDataValues() { openadk.library.common.Demographics sifDemographics = new openadk.library.common.Demographics(); BirthData sliBirthData = converter.convert(sifDemographics); Assert.assertNotNull(sliBirthData); Assert.assertNull(sliBirthData.getCityOfBirth()); Assert.assertNull(sliBirthData.getCountryOfBirthCode()); Assert.assertNull(sliBirthData.getStateOfBirthAbbreviation()); Assert.assertNull(sliBirthData.getBirthDate()); Assert.assertNull(sliBirthData.getDateEnteredUS()); }
@Test public void shouldMapSifDemographicToSliBirthData() { for (String state : SLI_STATE_CODES) { BirthData sliBirthData = converter.convert(createSifDemographics(state)); Assert.assertNotNull(sliBirthData); Assert.assertEquals(placeOfBirth, sliBirthData.getCityOfBirth()); Assert.assertEquals(countryOfBirth, sliBirthData.getCountryOfBirthCode()); Assert.assertEquals(state, sliBirthData.getStateOfBirthAbbreviation()); Assert.assertEquals(DATE_FORMAT.format(birthDate.getTime()), sliBirthData.getBirthDate()); Assert.assertEquals(DATE_FORMAT.format(countryArrivalDate.getTime()), sliBirthData.getDateEnteredUS()); } BirthData sliBirthData = converter.convert(createSifDemographics("invlaid_state")); Assert.assertNotNull(sliBirthData); Assert.assertNull(sliBirthData.getStateOfBirthAbbreviation()); } |
### Question:
EntryTypeConverter { public String convert(EntryType entryType) { if (entryType == null) { return null; } return toSliEntryType(EntryTypeCode.wrap(entryType.getCode())); } String convert(EntryType entryType); }### Answer:
@Test public void testNullObject() { String result = converter.convert(null); Assert.assertNull("Entry Type should be null", result); }
@Test public void testMappings() { Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1821)), "Transfer from a public school in the same local education agency"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1822)), "Transfer from a public school in a different local education agency in the same state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1823)), "Transfer from a public school in a different state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1824)), "Transfer from a private, non-religiously-affiliated school in the same local education agency"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1825)), "Transfer from a private, non-religiously-affiliated school in a different local education agency in the same state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1826)), "Transfer from a private, non-religiously-affiliated school in a different state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1827)), "Transfer from a private, religiously-affiliated school in the same local education agency"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1828)), "Transfer from a private, religiously-affiliated school in a different local education agency in the same state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1829)), "Transfer from a private, religiously-affiliated school in a different state"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1830)), "Transfer from a school outside of the country"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1831)), "Transfer from an institution"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1832)), "Transfer from a charter school"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1833)), "Transfer from home schooling"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1835)), "Re-entry from the same school with no interruption of schooling"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1836)), "Re-entry after a voluntary withdrawal"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1837)), "Re-entry after an involuntary withdrawal"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1838)), "Original entry into a United States school"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1839)), "Original entry into a United States school from a foreign country with no interruption in schooling"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_1840)), "Original entry into a United States school from a foreign country with an interruption in schooling"); Assert.assertEquals(converter.convert(getEntryType(EntryTypeCode._0619_9999)), "Other"); } |
### Question:
AddressListConverter { public List<Address> convert(AddressList addressList) { if (addressList == null) { return null; } return toSliAddressList(addressList.getAddresses()); } List<Address> convert(AddressList addressList); List<Address> convert(StudentAddressList addressList); }### Answer:
@Test public void testNullObject() { List<Address> result = converter.convert((AddressList) null); Assert.assertNull("Address list should be null", result); }
@Test public void testEmptyList() { AddressList list = new AddressList(); List<Address> result = converter.convert(list); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyAddress() { AddressList list = new AddressList(); openadk.library.common.Address original = new openadk.library.common.Address(); list.add(original); List<Address> result = converter.convert(list); Assert.assertEquals(1, result.size()); Address address = result.get(0); Assert.assertEquals("Other", address.getAddressType()); Assert.assertNull(address.getCity()); Assert.assertNull(address.getCountryCode()); Assert.assertNull(address.getPostalCode()); Assert.assertNull(address.getStateAbbreviation()); Assert.assertNull(address.getStreetNumberName()); }
@Test public void testConversion() { map.clear(); map.put(AddressType._0369_CAMPUS, "Other"); map.put(AddressType._0369_EMPLOYER, "Other"); map.put(AddressType._0369_EMPLOYMENT, "Work"); map.put(AddressType._0369_MAILING, "Mailing"); map.put(AddressType._0369_ORGANIZATION, "Other"); map.put(AddressType._0369_OTHER, "Other"); map.put(AddressType._0369_PERMANENT, "Other"); map.put(AddressType.EMPLOYERS, "Other"); map.put(AddressType.EMPLOYMENT, "Work"); map.put(AddressType.MAILING, "Mailing"); map.put(AddressType.OTHER_HOME, "Home"); map.put(AddressType.OTHER_ORGANIZATION, "Other"); map.put(AddressType.PHYSICAL_LOCATION, "Physical"); map.put(AddressType.SHIPPING, "Other"); map.put(AddressType.SIF15_CAMPUS, "Other"); map.put(AddressType.SIF15_EMPLOYER, "Other"); map.put(AddressType.SIF15_EMPLOYMENT, "Work"); map.put(AddressType.SIF15_MAILING, "Mailing"); map.put(AddressType.SIF15_ORGANIZATION, "Other"); map.put(AddressType.SIF15_OTHER, "Other"); map.put(AddressType.SIF15_PERMANENT, "Other"); map.put(AddressType.wrap("something else"), "Other"); addressTypes.addAll(map.keySet()); AddressList originalList = new AddressList(); for (int i = 0; i < addressTypes.size(); i++) { openadk.library.common.Address address = getAddress(i); originalList.add(address); } List<Address> convertedList = converter.convert(originalList); Assert.assertEquals(originalList.size(), convertedList.size()); int i = 0; for (Address converted : convertedList) { openadk.library.common.Address original = originalList.get(i++); testMapping(original, converted); } } |
### Question:
AttendanceTreatment implements Treatment { @Override public Entity apply(Entity entity) { if (entity.getBody().containsKey("schoolYearAttendance")) { LOG.debug("Treatment has already been applied to attendance entity: {}", new Object[] { entity.getEntityId() }); return entity; } Map<String,Object> treated = AttendanceStrategyHelper.wrap(entity.getBody()); entity.getBody().clear(); entity.getBody().putAll(treated); return entity; } @Override Entity apply(Entity entity); }### Answer:
@Test public void testApply() { Map<String, Object> body = new HashMap<String, Object>(); body.put("schoolYear", "schoolYear"); List<Map<String,Object>> attendanceEvent = new ArrayList<Map<String,Object>>(); body.put("attendanceEvent", attendanceEvent); Entity entity = new BulkExtractEntity(body, "student"); Entity treated = treat.apply(entity); Assert.assertNotNull(treated.getBody().get("schoolYearAttendance")); List<Map<String, Object>> attendances = new ArrayList<Map<String, Object>>(); Map<String, Object> schoolYearAttendance = new HashMap<String, Object>(); attendances = (List<Map<String, Object>>) treated.getBody().get("schoolYearAttendance"); schoolYearAttendance = attendances.get(0); Assert.assertNotNull(schoolYearAttendance.get("schoolYear")); Assert.assertNotNull(schoolYearAttendance.get("attendanceEvent")); Assert.assertEquals("schoolYear", schoolYearAttendance.get("schoolYear")); Assert.assertNotNull(schoolYearAttendance.get("attendanceEvent")); }
@Test public void testDuplicateApplication() { Map<String, Object> body = new HashMap<String, Object>(); body.put("schoolYearAttendance", new Object()); Entity entity = new BulkExtractEntity(body, "student"); Entity treated = treat.apply(entity); Assert.assertEquals(entity, treated); } |
### Question:
PhoneNumberListConverter { public List<InstitutionTelephone> convertInstitutionTelephone(PhoneNumberList phoneNumberList) { if (phoneNumberList == null) { return null; } return toSliInstitutionTelephoneList(phoneNumberList.getPhoneNumbers()); } List<InstitutionTelephone> convertInstitutionTelephone(PhoneNumberList phoneNumberList); List<PersonalTelephone> convertPersonalTelephone(PhoneNumberList phoneNumberList); }### Answer:
@Test public void testNullObject() { List<InstitutionTelephone> result = converter.convertInstitutionTelephone(null); Assert.assertNull("Telephone list should be null", result); }
@Test public void testEmptyList() { PhoneNumberList list = new PhoneNumberList(); list.setPhoneNumbers(new PhoneNumber[0]); List<InstitutionTelephone> result = converter.convertInstitutionTelephone(list); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyPhoneNumber() { PhoneNumberList list = new PhoneNumberList(); PhoneNumber original = new PhoneNumber(); list.add(original); List<InstitutionTelephone> result = converter.convertInstitutionTelephone(list); Assert.assertEquals(1, result.size()); InstitutionTelephone it = result.get(0); Assert.assertEquals(original.getNumber(), it.getTelephoneNumber()); Assert.assertEquals("Other", it.getInstitutionTelephoneNumberType()); }
@Test public void testMappings() { map.clear(); map.put(PhoneNumberType.ALT, "Other"); map.put(PhoneNumberType.ANSWERING_SERVICE, "Other"); map.put(PhoneNumberType.APPOINTMENT, "Other"); map.put(PhoneNumberType.BEEPER, "Other"); map.put(PhoneNumberType.FAX, "Fax"); map.put(PhoneNumberType.INSTANT_MESSAGING, "Other"); map.put(PhoneNumberType.MEDIA_CONFERENCE, "Other"); map.put(PhoneNumberType.PRIMARY, "Main"); map.put(PhoneNumberType.SIF1x_ALT, "Other"); map.put(PhoneNumberType.SIF1x_ANSWERING_SERVICE, "Other"); map.put(PhoneNumberType.SIF1x_APPT_NUMBER, "Other"); map.put(PhoneNumberType.SIF1x_BEEPER, "Other"); map.put(PhoneNumberType.SIF1x_EXT, "Other"); map.put(PhoneNumberType.SIF1x_HOME_FAX, "Fax"); map.put(PhoneNumberType.SIF1x_HOME_PHONE, "Other"); map.put(PhoneNumberType.SIF1x_NIGHT_PHONE, "Other"); map.put(PhoneNumberType.SIF1x_OTHER_RES_FAX, "Other"); map.put(PhoneNumberType.SIF1x_OTHER_RES_PHONE, "Other"); map.put(PhoneNumberType.SIF1x_PERSONAL_CELL, "Other"); map.put(PhoneNumberType.SIF1x_PERSONAL_PHONE, "Other"); map.put(PhoneNumberType.SIF1x_TELEMAIL, "Other"); map.put(PhoneNumberType.SIF1x_TELEX, "Other"); map.put(PhoneNumberType.SIF1x_VOICEMAIL, "Other"); map.put(PhoneNumberType.SIF1x_WORK_CELL, "Other"); map.put(PhoneNumberType.SIF1x_WORK_FAX, "Other"); map.put(PhoneNumberType.SIF1x_WORK_PHONE, "Other"); map.put(PhoneNumberType.TELEMAIL, "Other"); map.put(PhoneNumberType.TELEX, "Other"); map.put(PhoneNumberType.VOICE_MAIL, "Other"); PhoneNumberList list = getPhoneNumberList(); List<InstitutionTelephone> results = converter.convertInstitutionTelephone(list); Assert.assertEquals(list.size(), results.size()); int newCounter = 0; for (InstitutionTelephone it : results) { Assert.assertNotNull(it); PhoneNumber original = list.get(newCounter++); testMapping(original, it); } } |
### Question:
RaceListConverter { public List<String> convert(RaceList raceList) { if (raceList == null) { return null; } return toSliRaceList(raceList.getRaces()); } List<String> convert(RaceList raceList); }### Answer:
@Test public void testNullObject() { List<String> result = converter.convert(null); Assert.assertNull("Race list should be null", result); }
@Test public void testEmptyList() { RaceList list = new RaceList(); List<String> result = converter.convert(list); Assert.assertEquals(0, result.size()); }
@Test public void testConversion() { for (RaceType rt : map.keySet()) { RaceList rl = new RaceList(); Race r = new Race(); r.setCode(rt); rl.add(r); List<String> convertedList = converter.convert(rl); Assert.assertEquals(1, convertedList.size()); Assert.assertEquals(map.get(rt), convertedList.get(0)); } }
@Test public void testListConversion() { RaceList rl = new RaceList(); for (RaceType rt : map.keySet()) { Race r = new Race(); r.setCode(rt); rl.add(r); } List<String> convertedList = converter.convert(rl); List<String> expectedList = new ArrayList<String>(); expectedList.addAll(map.values()); Collections.sort(convertedList); Collections.sort(expectedList); Assert.assertEquals(expectedList.size(), convertedList.size()); for (int i = 0; i < expectedList.size(); i++) { Assert.assertEquals(expectedList.get(i), convertedList.get(i)); } } |
### Question:
GradeLevelsConverter { public List<String> convert(GradeLevels source) { if (source == null) { return null; } return toSliGradeList(source.getGradeLevels()); } List<String> convert(GradeLevels source); String convert(GradeLevel source); }### Answer:
@Test public void testNullObject() { List<String> result = converter.convert((GradeLevels) null); Assert.assertNull("Grade levels list should be null", result); }
@Test public void testEmptyList() { GradeLevels list = new GradeLevels(); list.setGradeLevels(new GradeLevel[0]); List<String> result = converter.convert(list); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyGradeLevel() { GradeLevels list = new GradeLevels(); GradeLevel original = new GradeLevel(); list.add(original); List<String> result = converter.convert(list); Assert.assertEquals(1, result.size()); String gradeLevel = result.get(0); Assert.assertEquals("Not Available", gradeLevel); }
@Test public void testMappings() { map.clear(); map.put(GradeLevelCode._01, "First grade"); map.put(GradeLevelCode._02, "Second grade"); map.put(GradeLevelCode._03, "Third grade"); map.put(GradeLevelCode._04, "Fourth grade"); map.put(GradeLevelCode._05, "Fifth grade"); map.put(GradeLevelCode._06, "Sixth grade"); map.put(GradeLevelCode._07, "Seventh grade"); map.put(GradeLevelCode._08, "Eighth grade"); map.put(GradeLevelCode._09, "Ninth grade"); map.put(GradeLevelCode._10, "Tenth grade"); map.put(GradeLevelCode._11, "Eleventh grade"); map.put(GradeLevelCode._12, "Twelfth grade"); map.put(GradeLevelCode.KG, "Kindergarten"); map.put(GradeLevelCode.OTHER, "Other"); map.put(GradeLevelCode.PG, "Postsecondary"); map.put(GradeLevelCode.PK, "Preschool/Prekindergarten"); map.put(GradeLevelCode.UN, "Ungraded"); map.put(GradeLevelCode.UNKNOWN, "Not Available"); GradeLevels list = getGradeLevels(); List<String> results = converter.convert(list); Assert.assertEquals(list.size(), results.size()); int newCounter = 0; for (String gradeLevel : results) { Assert.assertNotNull(gradeLevel); GradeLevel original = list.get(newCounter++); testMapping(original.getCode(), gradeLevel); } } |
### Question:
OtherNamesConverter { public List<OtherName> convert(OtherNames sifOtherNames) { if (sifOtherNames == null) { return null; } List<OtherName> sliNames = new ArrayList<OtherName>(); for (openadk.library.common.Name sifName : sifOtherNames) { OtherName sliName = new OtherName(); nameConverter.mapSifNameIntoSliName(sifName, sliName); sliName.setOtherNameType(NAME_TYPE_MAP.get(sifName.getType())); sliNames.add(sliName); } return sliNames; } List<OtherName> convert(OtherNames sifOtherNames); void setNameConverter(NameConverter nameConverter); }### Answer:
@Test public void testNullObject() { OtherNames sifOtherNames = null; List<OtherName> result = converter.convert(sifOtherNames); Assert.assertNull("OtherName list should be null", result); }
@Test public void testEmptyList() { OtherNames sifOtherNames = new OtherNames(); List<OtherName> result = converter.convert(sifOtherNames); Assert.assertEquals(0, result.size()); }
@Test public void testEmptyEmail() { OtherNames sifOtherNames = new OtherNames(); sifOtherNames.add(new Name()); List<OtherName> result = converter.convert(sifOtherNames); Assert.assertEquals(1, result.size()); OtherName sliOtherName = result.get(0); Assert.assertNull(sliOtherName.getOtherNameType()); Assert.assertNotNull(sliOtherName.getFirstName()); Assert.assertEquals(defaultName, sliOtherName.getFirstName()); Assert.assertNotNull(sliOtherName.getLastSurname()); Assert.assertEquals(defaultName, sliOtherName.getLastSurname()); Assert.assertNull(sliOtherName.getMiddleName()); Assert.assertNull(sliOtherName.getPersonalTitlePrefix()); Assert.assertNull(sliOtherName.getGenerationCodeSuffix()); }
@Test public void testMappings() { OtherNames otherNames = createOtherNames(); List<OtherName> result = converter.convert(otherNames); Assert.assertEquals("Should map 6 othernames", 6, result.size()); Iterator<OtherName> resIt = result.iterator(); for (String sliNameType : nameTypeMap.values()) { OtherName sliName = resIt.next(); Assert.assertNotNull(sliName); Assert.assertEquals(sliNameType, sliName.getOtherNameType()); Assert.assertEquals(firstName, sliName.getFirstName()); Assert.assertEquals(lastName, sliName.getLastSurname()); Assert.assertEquals(middleName, sliName.getMiddleName()); Assert.assertEquals(suffix, sliName.getGenerationCodeSuffix()); Assert.assertEquals(prefix, sliName.getPersonalTitlePrefix()); } } |
### Question:
EnglishProficiencyConverter { public String convert(EnglishProficiency ep) { if (ep == null) { return null; } EnglishProficiencyCode code = EnglishProficiencyCode.wrap(ep.getCode()); return ENGLISH_PROFICIENCY_MAP.get(code); } String convert(EnglishProficiency ep); }### Answer:
@Test public void testNullObject() { String result = converter.convert(null); Assert.assertNull("English Proficiency should be null", result); }
@Test public void testNativeEnglish() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.NATIVE_ENGLISH); String result = converter.convert(ep); Assert.assertEquals("NotLimited", result); }
@Test public void testFluentEnglish() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.FLUENT_ENGLISH); String result = converter.convert(ep); Assert.assertEquals("NotLimited", result); }
@Test public void testNonEnglishSpeaking() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.NON_ENGLISH_SPEAKING); String result = converter.convert(ep); Assert.assertEquals("Limited", result); }
@Test public void testRedesignatedAsFluent() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.REDESIGNATED_AS_FLUENT); String result = converter.convert(ep); Assert.assertEquals("NotLimited", result); }
@Test public void testLimitedEnglish() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.LIMITED_ENGLISH); String result = converter.convert(ep); Assert.assertEquals("Limited", result); }
@Test public void testUnknown() { EnglishProficiency ep = new EnglishProficiency(); ep.setCode(EnglishProficiencyCode.STATUS_UNKNOWN); String result = converter.convert(ep); Assert.assertNull(result); } |
### Question:
SimpleExtractVerifier implements ExtractVerifier { @Override public boolean shouldExtract(Entity entity, DateTime upToDate) { String entityDate = EntityDateHelper.retrieveDate(entity); return EntityDateHelper.isPastOrCurrentDate(entityDate, upToDate, entity.getType()); } @Override boolean shouldExtract(Entity entity, DateTime upToDate); }### Answer:
@Test public void testShouldExtract() { Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.BEGIN_DATE, "01-01-01"); Entity studentProgramAssociation = new MongoEntity(EntityNames.STUDENT_PROGRAM_ASSOCIATION, body); Assert.assertTrue( "01-01-01",simpleExtractVerifier.shouldExtract(studentProgramAssociation, DateTime.parse("2000-01-01", DateHelper.getDateTimeFormat()))); Assert.assertTrue( "01-01-01",simpleExtractVerifier.shouldExtract(studentProgramAssociation, DateTime.parse("1999-01-01", DateHelper.getDateTimeFormat()))); }
@Test public void testshouldExtractSchoolYear() { Map<String, Object> gradeBody = new HashMap<String, Object>(); gradeBody.put(ParameterConstants.SCHOOL_YEAR, "2009-2010"); Entity grade = new MongoEntity(EntityNames.GRADE, gradeBody); Assert.assertTrue(simpleExtractVerifier.shouldExtract(grade, DateTime.parse("2011-05-23", DateHelper.getDateTimeFormat()))); Assert.assertTrue(simpleExtractVerifier.shouldExtract(grade, DateTime.parse("2010-05-23", DateHelper.getDateTimeFormat()))); Assert.assertTrue(simpleExtractVerifier.shouldExtract(grade, null)); Assert.assertFalse(simpleExtractVerifier.shouldExtract(grade, DateTime.parse("2009-05-24", DateHelper.getDateTimeFormat()))); Assert.assertFalse(simpleExtractVerifier.shouldExtract(grade, DateTime.parse("2008-05-24", DateHelper.getDateTimeFormat()))); }
@Test public void testshouldExtractBeginDate() { Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.BEGIN_DATE, "2001-01-01"); Entity studentProgramAssociation = new MongoEntity(EntityNames.STUDENT_PROGRAM_ASSOCIATION, body); Assert.assertEquals(true, simpleExtractVerifier.shouldExtract(studentProgramAssociation, DateTime.parse("2001-01-01", DateHelper.getDateTimeFormat()))); Assert.assertEquals(true, simpleExtractVerifier.shouldExtract(studentProgramAssociation, null)); Assert.assertEquals(false, simpleExtractVerifier.shouldExtract(studentProgramAssociation, DateTime.parse("2000-01-01", DateHelper.getDateTimeFormat()))); } |
### Question:
SchoolYearConverter { public String convert(Integer schoolYear) { if (schoolYear == null) { return null; } Integer priorSchoolYear = schoolYear - 1; return priorSchoolYear.toString() + "-" + schoolYear.toString(); } String convert(Integer schoolYear); }### Answer:
@Test public void testNullList() { String result = converter.convert(null); Assert.assertNull("school year should be null", result); }
@Test public void test() { Assert.assertEquals(converter.convert(2011), "2010-2011"); Assert.assertEquals(converter.convert(2013), "2012-2013"); } |
### Question:
NameConverter { public Name convert(openadk.library.common.Name sifName) { if (sifName == null) { return null; } Name sliName = new Name(); mapSifNameIntoSliName(sifName, sliName); return sliName; } Name convert(openadk.library.common.Name sifName); void mapSifNameIntoSliName(openadk.library.common.Name sifName, Name sliName); }### Answer:
@Test public void nullNameShouldReturnNull() { openadk.library.common.Name sifName = null; Name sliName = converter.convert(sifName); Assert.assertNull(sliName); }
@Test public void emptySifNameShouldMapToNullAndDefaultValues() { openadk.library.common.Name sifName = new openadk.library.common.Name(); Name sliName = converter.convert(sifName); Assert.assertNotNull(sliName); Assert.assertEquals("Missing first name should map to Unknown", defaultName, sliName.getFirstName()); Assert.assertEquals("Missing last name should map to Unknown", defaultName, sliName.getLastSurname()); Assert.assertNull("Missing optional fields should map to null", sliName.getGenerationCodeSuffix()); Assert.assertNull("Missing optional fields should map to null", sliName.getMiddleName()); Assert.assertNull("Missing optional fields should map to null", sliName.getPersonalTitlePrefix()); }
@Test public void shouldMapSifNameToSliName() { Name sliName = converter.convert(createSifName(prefixes.get(0), suffixes.get(0))); Assert.assertNotNull(sliName); Assert.assertEquals("Incorrect prefix mapping", prefixes.get(0), sliName.getPersonalTitlePrefix()); Assert.assertEquals("Incorrect firstName mapping", firstName, sliName.getFirstName()); Assert.assertEquals("Incorrect lastName mapping", lastName, sliName.getLastSurname()); Assert.assertEquals("Incorrect middleName mapping", middleName, sliName.getMiddleName()); Assert.assertEquals("Incorrect suffix", suffixes.get(0), sliName.getGenerationCodeSuffix()); for (String prefix : prefixes) { sliName = converter.convert(createSifName(prefix, suffixes.get(0))); Assert.assertNotNull(sliName); Assert.assertEquals("Incorrect prefix mapping", prefix, sliName.getPersonalTitlePrefix()); } for (String suffix : suffixes) { sliName = converter.convert(createSifName(prefixes.get(0), suffix)); Assert.assertNotNull(sliName); Assert.assertEquals("Incorrect suffix", suffix, sliName.getGenerationCodeSuffix()); } sliName = converter.convert(createSifName("unsupported", suffixes.get(0))); Assert.assertNotNull(sliName); Assert.assertNull("Unsupported prefix should map to null", sliName.getPersonalTitlePrefix()); sliName = converter.convert(createSifName(prefixes.get(0), "unsupported")); Assert.assertNotNull(sliName); Assert.assertNull("Unsupported suffix should map to null", sliName.getGenerationCodeSuffix()); } |
### Question:
GenderConverter { public String convert(String gender) { return GENDER_TYPE_MAP.get(gender); } String convert(String gender); }### Answer:
@Test public void testNullObject() { String result = converter.convert(null); Assert.assertNull("Race list should be null", result); }
@Test public void testMale() { String result = converter.convert("M"); Assert.assertEquals("Male", result); }
@Test public void testFemale() { String result = converter.convert("F"); Assert.assertEquals("Female", result); }
@Test public void testUnknown() { String result = converter.convert("U"); Assert.assertNull(result); } |
### Question:
OperationalStatusConverter { public String convert(OperationalStatus operationalStatus) { if (operationalStatus == null || operationalStatus.getValue() == null || operationalStatus.getValue().isEmpty()) { return null; } return OPERATIONAL_STATUS_MAP.get(operationalStatus); } String convert(OperationalStatus operationalStatus); }### Answer:
@Test public void testNull() { String result = converter.convert(null); Assert.assertNull("Operational status should be null", result); }
@Test public void testEmpty() { OperationalStatus status = OperationalStatus.wrap(""); String result = converter.convert(status); Assert.assertNull("Operational status should be null", result); }
@Test public void testMappings() { map.clear(); map.put(OperationalStatus.AGENCY_CHANGED, "Changed Agency"); map.put(OperationalStatus.AGENCY_CLOSED, "Closed"); map.put(OperationalStatus.AGENCY_FUTURE, "Future"); map.put(OperationalStatus.AGENCY_INACTIVE, "Inactive"); map.put(OperationalStatus.AGENCY_NEW, "New"); map.put(OperationalStatus.AGENCY_OPEN, "Active"); map.put(OperationalStatus.CHANGED_BOUNDARY, null); map.put(OperationalStatus.SCHOOL_CLOSED, "Closed"); map.put(OperationalStatus.SCHOOL_FUTURE, "Future"); map.put(OperationalStatus.SCHOOL_INACTIVE, "Inactive"); map.put(OperationalStatus.SCHOOL_NEW, "New"); map.put(OperationalStatus.SCHOOL_OPEN, "Active"); for (OperationalStatus status : map.keySet()) { String expected = map.get(status); String result = converter.convert(status); Assert.assertEquals(expected, result); } String result = converter.convert(OperationalStatus.wrap("something else")); Assert.assertNull(result); } |
### Question:
SchoolLevelTypeConverter { public String convert(SchoolLevelType schoolLevelType) { if (schoolLevelType == null) { return null; } return SCHOOL_LEVEL_TYPE_MAP.get(schoolLevelType); } String convert(SchoolLevelType schoolLevelType); List<String> convertAsList(SchoolLevelType schoolLevelType); }### Answer:
@Test public void testNull() { String result = converter.convert(null); Assert.assertNull("School category should be null", result); }
@Test public void testEmpty() { SchoolLevelType type = SchoolLevelType.wrap(""); String result = converter.convert(type); Assert.assertNull(result); } |
### Question:
SchoolLevelTypeConverter { public List<String> convertAsList(SchoolLevelType schoolLevelType) { if (schoolLevelType == null) { return null; } ArrayList<String> list = new ArrayList<String>(); String category = SCHOOL_LEVEL_TYPE_MAP.get(schoolLevelType); if (category != null) { list.add(category); } return list; } String convert(SchoolLevelType schoolLevelType); List<String> convertAsList(SchoolLevelType schoolLevelType); }### Answer:
@Test public void testListNull() { List<String> result = converter.convertAsList(null); Assert.assertNull("School category should be null", result); }
@Test public void testListEmpty() { SchoolLevelType type = SchoolLevelType.wrap(""); List<String> result = converter.convertAsList(type); Assert.assertEquals(0, result.size()); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.