method2testcases
stringlengths
118
6.63k
### Question: RegexUtil { public static Pattern getRegex(String input) { Matcher matcher = pattern.matcher(input); if (!matcher.find()) { return null; } try { return Pattern.compile(input); } catch (PatternSyntaxException e) { return null; } } static Pattern getRegex(String input); static Pattern env(); static boolean isClassName(String consumerId); }### Answer: @Test public void getRegex() throws Exception { Pattern simple = RegexUtil.getRegex("simple"); Assert.assertNull(simple); Pattern star = RegexUtil.getRegex("dev.*"); Assert.assertNotNull(star); }
### Question: JavaMethod { public static SyncFilter build(String consumerId, SyncerFilterMeta filterMeta, String method) { String source = "import com.github.zzt93.syncer.data.*;\n" + "import com.github.zzt93.syncer.data.util.*;\n" + "import java.util.*;\n" + "import java.math.BigDecimal;\n" + "import java.sql.Timestamp;\n" + "import org.slf4j.Logger;\n" + "import org.slf4j.LoggerFactory;\n" + "\n" + "public class MethodFilterTemplate implements SyncFilter<SyncData> {\n" + "\n" + " private final Logger logger = LoggerFactory.getLogger(getClass());\n" + "\n" + addNewline(method) + "\n" + "}\n"; String className = "Filter" + consumerId; source = source.replaceFirst("MethodFilterTemplate", className); Path path = Paths.get(filterMeta.getSrc(), className + ".java"); try { Files.write(path, source.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { logger.error("No permission", e); } compile(path.toString()); Class<?> cls; try { URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{path.getParent().toUri().toURL()}, JavaMethod.class.getClassLoader()); cls = Class.forName(className, true, classLoader); return (SyncFilter) cls.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | MalformedURLException e) { ShutDownCenter.initShutDown(e); return null; } } static SyncFilter build(String consumerId, SyncerFilterMeta filterMeta, String method); }### Answer: @Test public void build() { SyncFilter searcher = JavaMethod.build("searcher", new SyncerFilterMeta(), " public void filter(List<SyncData> list) {\n" + " for (SyncData d : list) {\n" + " assert d.getEventId().equals(\"123/1\");\n" + " }\n" + " }\n"); searcher.filter(Lists.newArrayList(data)); }
### Question: FileBasedMap { public boolean flush() { T toFlush = getToFlush(); if (toFlush == null) { return false; } byte[] bytes = toFlush.toString().getBytes(StandardCharsets.UTF_8); putBytes(file, bytes); file.force(); return true; } FileBasedMap(Path path); static byte[] readData(Path path); boolean append(T data, int count); boolean remove(T data, int count); boolean flush(); }### Answer: @Test public void flush() throws Exception { BinlogDataId _115 = getFromString("mysql-bin.000115/1234360405/139/0"); map.append(_115, 2); map.flush(); BinlogDataId s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.remove(_115, 1); BinlogDataId _116 = getFromString("mysql-bin.000116/1305/139/0"); map.append(_116, 1); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.remove(_115, 1); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _115); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _116); map.remove(_116, 1); BinlogDataId _117 = getFromString("mysql-bin.000117/1305/13/0"); map.append(_117, 1); map.flush(); s = getFromString(new String(FileBasedMap.readData(PATH))); Assert.assertEquals(s, _117); }
### Question: SyncKafkaSerializer implements Serializer<SyncResult> { @Override public byte[] serialize(String topic, SyncResult data) { return gson.toJson(data).getBytes(); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] serialize(String topic, SyncResult data); @Override void close(); }### Answer: @Test public void serialize() { SyncData write = SyncDataTestUtil.write("serial", "serial"); String key = "key"; long value = ((long) Math.pow(2, 53)) + 1; assertNotEquals(value, (double)value); write.addField(key, value); byte[] serialize = serializer.serialize("", write.getResult()); assertEquals("{\"fields\":{\"key\":\"9007199254740993\"},\"eventType\":0,\"repo\":\"serial\",\"entity\":\"serial\",\"id\":\"1234\",\"primaryKeyName\":\"id\"}" , new String(serialize)); }
### Question: MongoV4MasterConnector extends MongoConnectorBase { static Map getUpdatedFields(Document fullDocument, BsonDocument updatedFields, boolean bsonConversion) { if (bsonConversion) { if (fullDocument == null) { return (Map) MongoTypeUtil.convertBson(updatedFields); } HashMap<String, Object> res = new HashMap<>(); for (String key : updatedFields.keySet()) { res.put(key, fullDocument.get(key)); } return res; } return updatedFields; } MongoV4MasterConnector(MongoConnection connection, ConsumerRegistry registry, ProducerMaster.MongoV4Option mongoV4Option); @Override void configCursor(); @Override void closeCursor(); @Override void eventLoop(); }### Answer: @Test public void types() { long v = ((long) Math.pow(2, 53)) + 1; long v1 = ((long) Math.pow(2, 53)) + 3; long v2 = ((long) Math.pow(2, 53)) + 5; long v4 = System.currentTimeMillis(); double v3 = Math.pow(2, 53) + 5; String time = "time"; String id = "id"; String deep = "criteriaAuditRecords.0.auditRoleIds.0"; String str = "str"; String dou = "double"; String date = "date"; String bool = "bool"; String obj = "obj"; BsonDocument updateDoc = new BsonDocument(time, new BsonInt64(v)); Map map = getUpdatedFields(null, updateDoc, true); assertEquals(1, map.size()); assertEquals(v, map.get(time)); updateDoc.append(id, new BsonInt64(v1)); map = getUpdatedFields(null, updateDoc, true); assertEquals(2, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); updateDoc.append(deep, new BsonInt64(v2)); map = getUpdatedFields(null, updateDoc, true); assertEquals(3, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); assertEquals(v2, map.get(deep)); updateDoc.append(str, new BsonString(str)); updateDoc.append(dou, new BsonDouble(v3)); updateDoc.append(date, new BsonDateTime(v4)); updateDoc.append(bool, new BsonBoolean(true)); updateDoc.append(obj, new BsonDocument(str, new BsonString(str)).append(id, new BsonInt64(v1))); map = getUpdatedFields(null, updateDoc, true); assertEquals(8, map.size()); assertEquals(v, map.get(time)); assertEquals(v1, map.get(id)); assertEquals(v2, map.get(deep)); assertEquals(str, map.get(str)); assertEquals(v3, map.get(dou)); assertTrue(map.get(date) instanceof Date); assertEquals(v4, ((Date) map.get(date)).getTime()); assertEquals(true, map.get(bool)); assertTrue(map.get(obj) instanceof Map); assertEquals(v1, ((Map) map.get(obj)).get(id)); }
### Question: DocTimestamp implements SyncInitMeta<DocTimestamp> { @Override public int compareTo(DocTimestamp o) { if (o == this) { return 0; } if (this == earliest) { return -1; } else if (o == earliest) { return 1; } return timestamp.compareTo(o.timestamp); } DocTimestamp(BsonTimestamp data); @Override int compareTo(DocTimestamp o); @Override String toString(); static final DocTimestamp earliest; static final DocTimestamp latest; }### Answer: @Test public void compareTo() { DocTimestamp b_e = DocTimestamp.earliest; DocTimestamp b_l = DocTimestamp.latest; DocTimestamp b__l = DocTimestamp.latest; DocTimestamp b0 = new DocTimestamp( new BsonTimestamp(0)); DocTimestamp b1 = new DocTimestamp( new BsonTimestamp(1)); DocTimestamp b2 = new DocTimestamp( new BsonTimestamp(2)); DocTimestamp b_b = new DocTimestamp( new BsonTimestamp((int) (System.currentTimeMillis() / 1000) - 1, 0)); DocTimestamp bc = new DocTimestamp( new BsonTimestamp((int) (System.currentTimeMillis() / 1000) + 1, 0)); assertEquals(b_e.compareTo(b0), -1); assertEquals(b_l.compareTo(b_b), 1); assertEquals(b_l.compareTo(bc), -1); assertEquals(b_e.compareTo(b_l), -1); assertEquals(b_l.compareTo(b__l), 0); assertEquals(b0.compareTo(b2), -1); assertEquals(b1.compareTo(b2), -1); assertEquals(b2.compareTo(b0), 1); assertEquals(b2.compareTo(bc), -1); }
### Question: BinlogInfo implements SyncInitMeta<BinlogInfo> { @Override public int compareTo(BinlogInfo o) { if (o == this) { return 0; } if (this == latest || o == earliest) { return 1; } else if (this == earliest || o == latest) { return -1; } int seq = Integer.parseInt(binlogFilename.split("\\.")[1]); int oSeq = Integer.parseInt(o.binlogFilename.split("\\.")[1]); int compare = Integer.compare(seq, oSeq); return compare != 0 ? compare : Long.compare(binlogPosition, o.binlogPosition); } BinlogInfo(String binlogFilename, long binlogPosition); static BinlogInfo withFilenameCheck(String binlogFilename, long binlogPosition); String getBinlogFilename(); long getBinlogPosition(); @Override int compareTo(BinlogInfo o); @Override String toString(); static final BinlogInfo latest; static final BinlogInfo earliest; }### Answer: @Test public void compareTo() throws Exception { BinlogInfo b_e = BinlogInfo.earliest; BinlogInfo b_l = BinlogInfo.latest; BinlogInfo b__l = BinlogInfo.latest; BinlogInfo b1 = new BinlogInfo("mysql-bin.00001", 0); BinlogInfo b2 = new BinlogInfo("mysql-bin.00002", 0); BinlogInfo b2_1 = new BinlogInfo("mysql-bin.00002", 1); BinlogInfo b2_2 = new BinlogInfo("mysql-bin.00002", 2); BinlogInfo b20_2 = new BinlogInfo("mysql-bin.00020", 2); BinlogInfo b200_2 = new BinlogInfo("mysql-bin.200", 2); BinlogInfo b1200_2 = new BinlogInfo("mysql-bin.1200", 2); assertEquals(b_e.compareTo(b1), -1); assertEquals(b_l.compareTo(b1), 1); assertEquals(b_e.compareTo(b_l), -1); assertEquals(b_l.compareTo(b__l), 0); assertEquals(b1.compareTo(b2), -1); assertEquals(b2.compareTo(b2_1), -1); assertEquals(b2_1.compareTo(b2_2), -1); assertEquals(b2_2.compareTo(b20_2), -1); assertEquals(b20_2.compareTo(b200_2), -1); assertEquals(b200_2.compareTo(b1200_2), -1); }
### Question: BinlogInfo implements SyncInitMeta<BinlogInfo> { static int checkFilename(String binlogFilename) { try { return Integer.parseInt(binlogFilename.split("\\.")[1]); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { throw new InvalidBinlogException(e, binlogFilename, 0); } } BinlogInfo(String binlogFilename, long binlogPosition); static BinlogInfo withFilenameCheck(String binlogFilename, long binlogPosition); String getBinlogFilename(); long getBinlogPosition(); @Override int compareTo(BinlogInfo o); @Override String toString(); static final BinlogInfo latest; static final BinlogInfo earliest; }### Answer: @Test(expected = InvalidBinlogException.class) public void filenameCheck() throws Exception { BinlogInfo.checkFilename("mysql-bin1"); } @Test(expected = InvalidBinlogException.class) public void filenameCheck2() throws Exception { BinlogInfo.checkFilename("mysql-bin.00001bak"); }
### Question: WadlZipper { public void saveTo(String zipPathName) throws IOException, URISyntaxException { saveTo(new File(zipPathName)); } WadlZipper(String wadlUri); void saveTo(String zipPathName); void saveTo(File zipFile); }### Answer: @Test public void givenAWadlUri_whenSaveToFile_thenCreateZipWithWadlAndAllGrammars() throws Exception { doReturn(WADL_WITH_INCLUDE_GRAMMARS).when(httpClientMock).getAsString(new URI(WADL_URI)); wadlZipper.saveTo(httpClientMock, zipMock); final ArgumentCaptor<URI> uriArgument = ArgumentCaptor.forClass(URI.class); verify(httpClientMock, times(3)).getAsStream(uriArgument.capture()); assertThat(uriArgument.getAllValues(), contains(URI.create(REST_URI + '/' + RELATIVE_URI), URI.create(HOST_URI + ABSOLUTE_URI_WITHOUT_HOST), URI.create(ABSOLUTE_URI_WITH_HOST))); final ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class); verify(zipMock, times(4)).add(nameArgument.capture(), any(InputStream.class)); assertThat(nameArgument.getAllValues(), contains(DEFAULT_WADL_FILENAME, RELATIVE_URI + DEFAULT_SCHEMA_EXTENSION, ABSOLUTE_URI_WITHOUT_HOST.substring(1) + DEFAULT_SCHEMA_EXTENSION, ABSOLUTE_URI_WITH_HOST.substring(ABSOLUTE_URI_WITH_HOST.indexOf(" }
### Question: SingleType extends ClassType { @Override public String toSchema() { try { return tryBuildSchemaFromJaxbAnnotatedClass(); } catch (Exception e) { logger.warn("Cannot generate schema from JAXB annotations for class: " + clazz.getName() + ". Preparing generic Schema.\n" + e, e); return schemaForNonAnnotatedClass(); } } SingleType(Class<?> classType, QName qName); @Override String toSchema(); }### Answer: @Test public void givenClassWhichAttributeIsAnInterface_whenBuild_thenReturnSchemaWithTheInterface() { assertThat(new SingleType(ContactWhichAttributeIsAnInterface.class, IGNORED_Q_NAME).toSchema(), is(ContactWhichAttributeIsAnInterface.EXPECTED_SCHEMA)); } @Test public void givenNameOfNonAnnotatedJaxbClass_whenBuild_thenReturnGenericSchema() { assertThat(new SingleType(Contact.class, IGNORED_Q_NAME).toSchema(), is(Contact.EXPECTED_SCHEMA)); } @Test public void givenNameOfAnnotatedJaxbClass_whenBuild_thenReturnSchemaGeneratedByJaxb() { assertThat(new SingleType(ContactAnnotated.class, IGNORED_Q_NAME).toSchema(), is(ContactAnnotated.EXPECTED_SCHEMA)); } @Test public void givenNameOfAnnotatedJaxbClassWithSpecificTypeName_whenBuild_thenReturnSchemaGeneratedByJaxbWithSpecificName() { assertThat(new SingleType(ContactAnnotatedWithDifferentName.class, IGNORED_Q_NAME).toSchema(), is(ContactAnnotatedWithDifferentName.EXPECTED_SCHEMA)); }
### Question: ClassUtils { public static boolean isArrayOrCollection(Class<?> clazz) { return clazz.isArray() || Collection.class.isAssignableFrom(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }### Answer: @Test public void givenSingleType_whenAskIsArrayOrCollection_thenReturnFalse() { assertThat(isArrayOrCollection(String.class), is(false)); assertThat(isArrayOrCollection(Integer.class), is(false)); assertThat(isArrayOrCollection(Contact.class), is(false)); } @Test public void givenArray_whenAskIsArrayOrCollection_thenReturnTrue() { assertThat(isArrayOrCollection(String[].class), is(true)); assertThat(isArrayOrCollection(Integer[].class), is(true)); assertThat(isArrayOrCollection(Contact[].class), is(true)); } @Test public void givenCollection_whenAskIsArrayOrCollection_thenReturnTrue() { final List<String> stringsList = new ArrayList<String>(); final Set<Integer> integersSet = new HashSet<Integer>(); final Collection<Contact> contactsCollection = new ArrayList<Contact>(); assertThat(isArrayOrCollection(stringsList.getClass()), is(true)); assertThat(isArrayOrCollection(integersSet.getClass()), is(true)); assertThat(isArrayOrCollection(contactsCollection.getClass()), is(true)); }
### Question: ClassUtils { public static boolean isVoid(Class<?> clazz) { return Void.class.equals(clazz) || void.class.equals(clazz); } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }### Answer: @Test public void givenNormalClass_whenAskIsVoid_thenReturnFalse() { assertThat(isVoid(String.class), is(false)); assertThat(isVoid(Integer.class), is(false)); assertThat(isVoid(Contact[].class), is(false)); } @Test public void givenVoidClass_whenAskIsVoid_thenReturnTrue() { assertThat(isVoid(Void.class), is(true)); assertThat(isVoid(void.class), is(true)); }
### Question: ClassUtils { public static Class<?> getElementsClassOf(Class<?> clazz) { if (clazz.isArray()) { return clazz.getComponentType(); } if (Collection.class.isAssignableFrom(clazz)) { logger.warn("In Java its not possible to discover de Generic type of a collection like: {}", clazz); return Object.class; } return clazz; } private ClassUtils(); static boolean isArrayOrCollection(Class<?> clazz); static Class<?> getElementsClassOf(Class<?> clazz); static boolean isVoid(Class<?> clazz); }### Answer: @Test public void givenArray_whenGetElementsClassOf_thenReturnTheClassOfElements() { assertThat(getElementsClassOf(String[].class), is(typeCompatibleWith(String.class))); assertThat(getElementsClassOf(Integer[].class), is(typeCompatibleWith(Integer.class))); assertThat(getElementsClassOf(Contact[].class), is(typeCompatibleWith(Contact.class))); }
### Question: RepresentationBuilder { Collection<Representation> build(MethodContext ctx) { final Collection<Representation> representations = new ArrayList<Representation>(); final Method javaMethod = ctx.getJavaMethod(); final GrammarsDiscoverer grammarsDiscoverer = ctx.getParentContext().getGrammarsDiscoverer(); for (MediaType mediaType : ctx.getMediaTypes()) { final Class<?> returnType = javaMethod.getReturnType(); if (isVoid(returnType)) { continue; } final QName qName = grammarsDiscoverer.discoverQNameFor(new ClassMetadataFromReturnType(javaMethod)); representations.add(new Representation().withMediaType(mediaType.toString()).withElement(qName)); } return representations; } }### Answer: @Test public void givenVoidAsMethodReturnType_whenBuildRepresentation_thenDoNotAddAnything() throws NoSuchMethodException { final ApplicationContext appCtx = new ApplicationContext(IGNORED_METHOD_CONTEXT_ITERATOR, new GrammarsDiscoverer(new ClassTypeDiscoverer(new QNameBuilderFactory().getBuilder()))); final MethodContext methodCtxMock = mock(MethodContext.class); doReturn(appCtx).when(methodCtxMock).getParentContext(); doReturn(new HashSet<MediaType>() {{ add(MediaType.APPLICATION_JSON); }}).when(methodCtxMock).getMediaTypes(); doReturn(JavaMethod.WITHOUT_PARAMETERS).when(methodCtxMock).getJavaMethod(); final Collection<Representation> representations = representationBuilder.build(methodCtxMock); assertThat(representations, Matchers.is(Matchers.empty())); }
### Question: GrammarsDiscoverer { public List<String> getSchemaUrlsForComplexTypes() { final List<String> urls = new ArrayList<String>(); for (String localPart : classTypeDiscoverer.getAllByLocalPart().keySet()) { urls.add("schema/" + localPart); } return urls; } GrammarsDiscoverer(ClassTypeDiscoverer classTypeDiscoverer); QName discoverQNameFor(ClassMetadata classMetadata); List<String> getSchemaUrlsForComplexTypes(); }### Answer: @Test public void givenSeveralClasses_whenGetURLSchemas_thenReturnURLsBasedOnLocalParts() { doReturn(new HashMap<String, ClassType>() {{ put("a", DUMMY_CLASS_TYPE); put("b", DUMMY_CLASS_TYPE); put("c", DUMMY_CLASS_TYPE); }}).when(classTypeDiscovererMock).getAllByLocalPart(); final List<String> schemaUrlsForComplexTypes = grammarsDiscoverer.getSchemaUrlsForComplexTypes(); assertThat(schemaUrlsForComplexTypes, containsInAnyOrder("schema/a", "schema/b", "schema/c")); }
### Question: IncludeBuilder { Collection<Include> build() { final List<Include> includes = new ArrayList<Include>(); for (String schemaUrl : grammarsDiscoverer.getSchemaUrlsForComplexTypes()) { includes.add(new Include().withHref(schemaUrl)); } return includes; } IncludeBuilder(GrammarsDiscoverer grammarsDiscoverer); }### Answer: @Test public void name() { doReturn(new ArrayList<String>(Arrays.asList(DUMMY_URLS))).when(grammarsDiscovererMock).getSchemaUrlsForComplexTypes(); final Collection<Include> expectedIncludes = new ArrayList<Include>(); for (String dummyUrl : DUMMY_URLS) { expectedIncludes.add(new Include().withHref(dummyUrl)); } assertThat(builder.build(), containsInAnyOrder(expectedIncludes.toArray())); }
### Question: GrammarsUrisExtractor { List<String> extractFrom(String wadl) { final List<String> uris = new ArrayList<String>(); final String[] includeElements = BY_INCLUDE.split(extractGrammarsElement(wadl)); for (int i = 1; i < includeElements.length; i++) { uris.add(extractIncludeUriFrom(includeElements[i])); } return uris; } }### Answer: @Test public void givenWadlWithSeveralGrammars_whenExtract_thenReturnListOfURIs() { assertThat(grammarsUrisExtractor.extractFrom(WADL_WITH_INCLUDE_GRAMMARS), contains(RELATIVE_URI, ABSOLUTE_URI_WITHOUT_HOST, ABSOLUTE_URI_WITH_HOST)); } @Test public void givenWadlWithoutGrammars_whenExtract_thenReturnEmptyListOfURIs() { assertThat(grammarsUrisExtractor.extractFrom(WADL_WITHOUT_INCLUDE_GRAMMARS), is(empty())); }
### Question: CollectionType extends ClassType { @Override public String toSchema() { return COLLECTION_COMPLEX_TYPE_SCHEMA .replace("???type???", elementsQName.getLocalPart()) .replace("???name???", elementsQName.getLocalPart()) .replace("???collectionType???", qName.getLocalPart()) .replace("???collectionName???", qName.getLocalPart()); } CollectionType(Class<?> collectionClass, QName collectionQName, QName elementsQName); @Override String toSchema(); QName getElementsQName(); }### Answer: @Test public void givenNameOfComplexTypeCollection_whenBuild_thenReturnSchemaWithTheCollection() { assertThat(new CollectionType(ContactAnnotated[].class, new QName("contactAnnotatedCollection"), new QName("contactAnnotated")).toSchema(), is(ContactAnnotated.EXPECTED_COLLECTION_SCHEMA)); }
### Question: ClassTypeDiscoverer { public ClassType getBy(String localPart) { final ClassType classType = classTypeStore.findBy(localPart); if (classType == null) { throw new ClassTypeNotFoundException("Cannot find class type for localPart: " + localPart); } return classType; } ClassTypeDiscoverer(QNameBuilder qNameBuilder); ClassType discoverFor(ClassMetadata classMetadata); ClassType getBy(String localPart); Map<String, ClassType> getAllByLocalPart(); }### Answer: @Test(expected = ClassTypeNotFoundException.class) public void givenNonExistingLocalPart_whenFind_thenThrowException() { classTypeDiscoverer.getBy("nonExistingLocalPart"); }
### Question: SchemaBuilder { public String buildFor(final String localPart) { return classTypeDiscoverer.getBy(localPart).toSchema(); } SchemaBuilder(ClassTypeDiscoverer classTypeDiscoverer); String buildFor(final String localPart); }### Answer: @Test public void givenExistingLocalPart_whenBuildSchema_thenReturnSchema() { final ClassType classTypeDummy = mock(ClassType.class); doReturn("dummy schema").when(classTypeDummy).toSchema(); doReturn(classTypeDummy).when(classTypeDiscovererMock).getBy("dummyLocalPart"); assertThat(schemaBuilder.buildFor("dummyLocalPart"), Matchers.is("dummy schema")); } @Test(expected = ClassTypeNotFoundException.class) public void givenNonExistingLocalPart_whenBuildSchema_thenThrowException() { doThrow(new ClassTypeNotFoundException()).when(classTypeDiscovererMock).getBy("nonExistingLocalPart"); schemaBuilder.buildFor("nonExistingLocalPart"); }
### Question: UpperCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("UCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; if (QueryEvaluationUtil.isStringLiteral(literal)) { String lexicalValue = literal.getLabel().toUpperCase(); Optional<String> language = literal.getLanguage(); if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); } else if (XMLSchema.STRING.equals(literal.getDatatype())) { return valueFactory.createLiteral(lexicalValue, XMLSchema.STRING); } else { return valueFactory.createLiteral(lexicalValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate1() { Literal pattern = f.createLiteral("foobar"); try { Literal result = ucaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("FOOBAR")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal pattern = f.createLiteral("FooBar"); try { Literal result = ucaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("FOOBAR")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal pattern = f.createLiteral("FooBar"); Literal startIndex = f.createLiteral(4); try { ucaseFunc.evaluate(f, pattern, startIndex); fail("illegal number of parameters"); } catch (ValueExprEvaluationException e) { } }
### Question: LowerCase implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("LCASE requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; if (QueryEvaluationUtil.isStringLiteral(literal)) { String lexicalValue = literal.getLabel().toLowerCase(); Optional<String> language = literal.getLanguage(); if (language.isPresent()) { return valueFactory.createLiteral(lexicalValue, language.get()); } else if (XMLSchema.STRING.equals(literal.getDatatype())) { return valueFactory.createLiteral(lexicalValue, XMLSchema.STRING); } else { return valueFactory.createLiteral(lexicalValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate1() { Literal pattern = f.createLiteral("foobar"); try { Literal result = lcaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("foobar")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate2() { Literal pattern = f.createLiteral("FooBar"); try { Literal result = lcaseFunc.evaluate(f, pattern); assertTrue(result.getLabel().equals("foobar")); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } } @Test public void testEvaluate3() { Literal pattern = f.createLiteral("FooBar"); Literal startIndex = f.createLiteral(4); try { lcaseFunc.evaluate(f, pattern, startIndex); fail("illegal number of parameters"); } catch (ValueExprEvaluationException e) { } }
### Question: HashFunction implements Function { @Override public abstract Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException; @Override abstract Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash())); assertNotNull(hash); assertEquals(XMLSchema.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash(), XMLSchema.STRING)); assertNotNull(hash); assertEquals(XMLSchema.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { getHashFunction().evaluate(f, f.createLiteral("4", XMLSchema.INTEGER)); fail("incompatible operand should have resulted in type error."); } catch (ValueExprEvaluationException e) { } } @Test public void testEvaluate() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash())); assertNotNull(hash); assertEquals(XSD.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal hash = getHashFunction().evaluate(f, f.createLiteral(getToHash(), XSD.STRING)); assertNotNull(hash); assertEquals(XSD.STRING, hash.getDatatype()); assertEquals(hash.getLabel(), getExpectedDigest()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { getHashFunction().evaluate(f, f.createLiteral("4", XSD.INTEGER)); fail("incompatible operand should have resulted in type error."); } catch (ValueExprEvaluationException e) { } }
### Question: QueryModelNormalizer extends AbstractQueryModelVisitor<RuntimeException> implements QueryOptimizer { @Override public void meet(Join join) { super.meet(join); TupleExpr leftArg = join.getLeftArg(); TupleExpr rightArg = join.getRightArg(); if (leftArg instanceof EmptySet || rightArg instanceof EmptySet) { join.replaceWith(new EmptySet()); } else if (leftArg instanceof SingletonSet) { join.replaceWith(rightArg); } else if (rightArg instanceof SingletonSet) { join.replaceWith(leftArg); } else if (leftArg instanceof Union) { Union union = (Union) leftArg; Join leftJoin = new Join(union.getLeftArg(), rightArg.clone()); Join rightJoin = new Join(union.getRightArg(), rightArg.clone()); Union newUnion = new Union(leftJoin, rightJoin); join.replaceWith(newUnion); newUnion.visit(this); } else if (rightArg instanceof Union) { Union union = (Union) rightArg; Join leftJoin = new Join(leftArg.clone(), union.getLeftArg()); Join rightJoin = new Join(leftArg.clone(), union.getRightArg()); Union newUnion = new Union(leftJoin, rightJoin); join.replaceWith(newUnion); newUnion.visit(this); } else if (leftArg instanceof LeftJoin && isWellDesigned(((LeftJoin) leftArg))) { LeftJoin leftJoin = (LeftJoin) leftArg; join.replaceWith(leftJoin); join.setLeftArg(leftJoin.getLeftArg()); leftJoin.setLeftArg(join); leftJoin.visit(this); } else if (rightArg instanceof LeftJoin && isWellDesigned(((LeftJoin) rightArg))) { LeftJoin leftJoin = (LeftJoin) rightArg; join.replaceWith(leftJoin); join.setRightArg(leftJoin.getLeftArg()); leftJoin.setLeftArg(join); leftJoin.visit(this); } } QueryModelNormalizer(); @Override void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings); @Override void meet(Join join); @Override void meet(LeftJoin leftJoin); @Override void meet(Union union); @Override void meet(Difference difference); @Override void meet(Intersection intersection); @Override void meet(Filter node); @Override void meet(Or or); @Override void meet(And and); }### Answer: @Test public void testNormalizeUnionWithEmptyLeft() { Projection p = new Projection(); Union union = new Union(); SingletonSet s = new SingletonSet(); union.setLeftArg(new EmptySet()); union.setRightArg(s); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(s); } @Test public void testNormalizeUnionWithEmptyRight() { Projection p = new Projection(); Union union = new Union(); SingletonSet s = new SingletonSet(); union.setRightArg(new EmptySet()); union.setLeftArg(s); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(s); } @Test public void testNormalizeUnionWithTwoSingletons() { Projection p = new Projection(); Union union = new Union(); union.setRightArg(new SingletonSet()); union.setLeftArg(new SingletonSet()); p.setArg(union); subject.meet(union); assertThat(p.getArg()).isEqualTo(union); }
### Question: ShaclSailFactory implements SailFactory { @Override public String getSailType() { return SAIL_TYPE; } @Override String getSailType(); @Override SailImplConfig getConfig(); @Override Sail getSail(SailImplConfig config); static final String SAIL_TYPE; }### Answer: @Test public void getSailTypeReturnsCorrectValue() { assertThat(subject.getSailType()).isEqualTo(ShaclSailFactory.SAIL_TYPE); } @Test public void getSailTypeReturnsCorrectValue() { ShaclSailFactory subject = new ShaclSailFactory(); assertThat(subject.getSailType()).isEqualTo(ShaclSailFactory.SAIL_TYPE); }
### Question: ShaclSailFactory implements SailFactory { @Override public Sail getSail(SailImplConfig config) throws SailConfigException { if (!SAIL_TYPE.equals(config.getType())) { throw new SailConfigException("Invalid Sail type: " + config.getType()); } ShaclSail sail = new ShaclSail(); if (config instanceof ShaclSailConfig) { ShaclSailConfig shaclSailConfig = (ShaclSailConfig) config; if (shaclSailConfig.isValidationEnabled()) { sail.enableValidation(); } else { sail.disableValidation(); } sail.setCacheSelectNodes(shaclSailConfig.isCacheSelectNodes()); sail.setUndefinedTargetValidatesAllSubjects(shaclSailConfig.isUndefinedTargetValidatesAllSubjects()); sail.setIgnoreNoShapesLoadedException(shaclSailConfig.isIgnoreNoShapesLoadedException()); sail.setLogValidationPlans(shaclSailConfig.isLogValidationPlans()); sail.setLogValidationViolations(shaclSailConfig.isLogValidationViolations()); sail.setParallelValidation(shaclSailConfig.isParallelValidation()); sail.setGlobalLogValidationExecution(shaclSailConfig.isGlobalLogValidationExecution()); sail.setPerformanceLogging(shaclSailConfig.isPerformanceLogging()); sail.setSerializableValidation(shaclSailConfig.isSerializableValidation()); sail.setRdfsSubClassReasoning(shaclSailConfig.isRdfsSubClassReasoning()); } return sail; } @Override String getSailType(); @Override SailImplConfig getConfig(); @Override Sail getSail(SailImplConfig config); static final String SAIL_TYPE; }### Answer: @Test public void getSailWithDefaultConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSailConfig(); ShaclSail sail = (ShaclSail) subject.getSail(config); assertMatchesConfig(sail, config); } @Test public void getSailWithCustomConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSailConfig(); config.setCacheSelectNodes(!config.isCacheSelectNodes()); config.setGlobalLogValidationExecution(!config.isGlobalLogValidationExecution()); config.setIgnoreNoShapesLoadedException(!config.isIgnoreNoShapesLoadedException()); config.setLogValidationPlans(!config.isLogValidationPlans()); config.setLogValidationViolations(!config.isLogValidationViolations()); config.setParallelValidation(!config.isParallelValidation()); config.setUndefinedTargetValidatesAllSubjects(!config.isUndefinedTargetValidatesAllSubjects()); config.setValidationEnabled(!config.isValidationEnabled()); config.setPerformanceLogging(!config.isPerformanceLogging()); config.setSerializableValidation(!config.isSerializableValidation()); config.setRdfsSubClassReasoning(!config.isRdfsSubClassReasoning()); ShaclSail sail = (ShaclSail) subject.getSail(config); assertMatchesConfig(sail, config); }
### Question: Buffer implements Function { @Override public Value evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 3) { throw new ValueExprEvaluationException(getURI() + " requires exactly 3 arguments, got " + args.length); } SpatialContext geoContext = SpatialSupport.getSpatialContext(); Shape geom = FunctionArguments.getShape(this, args[0], geoContext); double radiusUom = FunctionArguments.getDouble(this, args[1]); IRI units = FunctionArguments.getUnits(this, args[2]); double radiusDegs = FunctionArguments.convertToDegrees(radiusUom, units); Shape buffered = SpatialSupport.getSpatialAlgebra().buffer(geom, radiusDegs); String wkt; try { wkt = SpatialSupport.getWktWriter().toWkt(buffered); } catch (IOException ioe) { throw new ValueExprEvaluationException(ioe); } return valueFactory.createLiteral(wkt, GEO.WKT_LITERAL); } @Override String getURI(); @Override Value evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluateWithDecimalRadius() { Value result = buffer.evaluate(f, point, f.createLiteral("1.0", XMLSchema.DECIMAL), unit); assertNotNull(result); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidRadius() { buffer.evaluate(f, point, f.createLiteral("foobar", XMLSchema.DECIMAL), unit); } @Test public void testEvaluateWithIntRadius() { Value result = buffer.evaluate(f, point, f.createLiteral(1), unit); assertNotNull(result); } @Test public void testEvaluateWithDoubleRadius() { Value result = buffer.evaluate(f, point, f.createLiteral(1.0), unit); assertNotNull(result); } @Test public void testEvaluateWithDecimalRadius() { Value result = buffer.evaluate(f, point, f.createLiteral("1.0", XSD.DECIMAL), unit); assertNotNull(result); } @Test public void resultIsPolygonWKT() { Literal result = (Literal) buffer.evaluate(f, point, f.createLiteral(1), unit); assertNotNull(result); assertThat(result.getDatatype()).isEqualTo(GEO.WKT_LITERAL); assertThat(result.getLabel()).startsWith("POLYGON ((23.708505"); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidRadius() { buffer.evaluate(f, point, f.createLiteral("foobar", XSD.DECIMAL), unit); } @Test(expected = ValueExprEvaluationException.class) public void testEvaluateWithInvalidUnit() { buffer.evaluate(f, point, f.createLiteral(1.0), FOAF.PERSON); }
### Question: ProxyRepository extends AbstractRepository implements RepositoryResolverClient { @Override public RepositoryConnection getConnection() throws RepositoryException { return getProxiedRepository().getConnection(); } ProxyRepository(); ProxyRepository(String proxiedIdentity); ProxyRepository(RepositoryResolver resolver, String proxiedIdentity); final void setProxiedIdentity(String value); String getProxiedIdentity(); @Override final void setRepositoryResolver(RepositoryResolver resolver); @Override void setDataDir(File dataDir); @Override File getDataDir(); @Override boolean isWritable(); @Override RepositoryConnection getConnection(); @Override ValueFactory getValueFactory(); }### Answer: @Test public final void addDataToProxiedAndCompareToProxy() throws RepositoryException, RDFParseException, IOException { proxied.initialize(); RepositoryConnection connection = proxied.getConnection(); long count; try { connection.add(Thread.currentThread().getContextClassLoader().getResourceAsStream("proxy.ttl"), "http: count = connection.size(); assertThat(count).isNotEqualTo(0L); } finally { connection.close(); } connection = repository.getConnection(); try { assertThat(connection.size()).isEqualTo(count); } finally { connection.close(); } }
### Question: SPARQLUpdateDataBlockParser extends TriGParser { @Override protected void parseGraph() throws RDFParseException, RDFHandlerException, IOException { super.parseGraph(); skipOptionalPeriod(); } SPARQLUpdateDataBlockParser(); SPARQLUpdateDataBlockParser(ValueFactory valueFactory); @Override RDFFormat getRDFFormat(); boolean isAllowBlankNodes(); void setAllowBlankNodes(boolean allowBlankNodes); void setLineNumberOffset(int lineNumberOffset); }### Answer: @Test public void testParseGraph() throws RDFParseException, RDFHandlerException, IOException { SPARQLUpdateDataBlockParser parser = new SPARQLUpdateDataBlockParser(); String blocksToCheck[] = new String[] { "graph <u:g1> {<u:1> <p:1> 1 } . <u:2> <p:2> 2.", "graph <u:g1> {<u:1> <p:1> 1 .} . <u:2> <p:2> 2." }; for (String block : blocksToCheck) { parser.parse(new StringReader(block), "http: } }
### Question: ProxyRepositoryFactory implements RepositoryFactory { @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { ProxyRepository result = null; if (config instanceof ProxyRepositoryConfig) { result = new ProxyRepository(((ProxyRepositoryConfig) config).getProxiedRepositoryID()); } else { throw new RepositoryConfigException("Invalid configuration class: " + config.getClass()); } return result; } @Override String getRepositoryType(); @Override RepositoryImplConfig getConfig(); @Override Repository getRepository(RepositoryImplConfig config); static final String REPOSITORY_TYPE; }### Answer: @Test public final void testGetRepository() throws RDF4JException, IOException { Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE, RDFFormat.TURTLE); RepositoryConfig config = RepositoryConfig.create(graph, Models.subject(graph.filter(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) .orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config"))); config.validate(); assertThat(config.getID()).isEqualTo("proxy"); assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'"); RepositoryImplConfig implConfig = config.getRepositoryImplConfig(); assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository"); assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class); assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory"); ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig); repository.setRepositoryResolver(mock(RepositoryResolver.class)); assertThat(repository).isInstanceOf(ProxyRepository.class); } @Test public final void testGetRepository() throws RDF4JException, IOException { Model graph = Rio.parse(this.getClass().getResourceAsStream("/proxy.ttl"), RepositoryConfigSchema.NAMESPACE, RDFFormat.TURTLE); RepositoryConfig config = RepositoryConfig.create(graph, Models.subject(graph.getStatements(null, RDF.TYPE, RepositoryConfigSchema.REPOSITORY)) .orElseThrow(() -> new RepositoryConfigException("missing Repository instance in config"))); config.validate(); assertThat(config.getID()).isEqualTo("proxy"); assertThat(config.getTitle()).isEqualTo("Test Proxy for 'memory'"); RepositoryImplConfig implConfig = config.getRepositoryImplConfig(); assertThat(implConfig.getType()).isEqualTo("openrdf:ProxyRepository"); assertThat(implConfig).isInstanceOf(ProxyRepositoryConfig.class); assertThat(((ProxyRepositoryConfig) implConfig).getProxiedRepositoryID()).isEqualTo("memory"); ProxyRepository repository = (ProxyRepository) factory.getRepository(implConfig); repository.setRepositoryResolver(mock(RepositoryResolver.class)); assertThat(repository).isInstanceOf(ProxyRepository.class); }
### Question: ValueComparator implements Comparator<Value> { @Override public int compare(Value o1, Value o2) { if (ObjectUtil.nullEquals(o1, o2)) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } boolean b1 = o1 instanceof BNode; boolean b2 = o2 instanceof BNode; if (b1 && b2) { return compareBNodes((BNode) o1, (BNode) o2); } if (b1) { return -1; } if (b2) { return 1; } boolean u1 = o1 instanceof IRI; boolean u2 = o2 instanceof IRI; if (u1 && u2) { return compareURIs((IRI) o1, (IRI) o2); } if (u1) { return -1; } if (u2) { return 1; } return compareLiterals((Literal) o1, (Literal) o2); } @Override int compare(Value o1, Value o2); }### Answer: @Test public void testBothNull() throws Exception { assertTrue(cmp.compare(null, null) == 0); } @Test public void testLeftNull() throws Exception { assertTrue(cmp.compare(null, typed1) < 0); } @Test public void testRightNull() throws Exception { assertTrue(cmp.compare(typed1, null) > 0); } @Test public void testBothBnode() throws Exception { assertTrue(cmp.compare(bnode1, bnode1) == 0); assertTrue(cmp.compare(bnode2, bnode2) == 0); assertTrue(cmp.compare(bnode1, bnode2) != cmp.compare(bnode2, bnode1)); assertTrue(cmp.compare(bnode1, bnode2) == -1 * cmp.compare(bnode2, bnode1)); } @Test public void testLeftBnode() throws Exception { assertTrue(cmp.compare(bnode1, typed1) < 0); } @Test public void testRightBnode() throws Exception { assertTrue(cmp.compare(typed1, bnode1) > 0); } @Test public void testBothURI() throws Exception { assertTrue(cmp.compare(uri1, uri1) == 0); assertTrue(cmp.compare(uri1, uri2) < 0); assertTrue(cmp.compare(uri1, uri3) < 0); assertTrue(cmp.compare(uri2, uri1) > 0); assertTrue(cmp.compare(uri2, uri2) == 0); assertTrue(cmp.compare(uri2, uri3) < 0); assertTrue(cmp.compare(uri3, uri1) > 0); assertTrue(cmp.compare(uri3, uri2) > 0); assertTrue(cmp.compare(uri3, uri3) == 0); } @Test public void testLeftURI() throws Exception { assertTrue(cmp.compare(uri1, typed1) < 0); } @Test public void testRightURI() throws Exception { assertTrue(cmp.compare(typed1, uri1) > 0); }
### Question: Rand implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 0) { throw new ValueExprEvaluationException("RAND requires 0 arguments, got " + args.length); } Random randomGenerator = new Random(); double randomValue = randomGenerator.nextDouble(); return valueFactory.createLiteral(randomValue); } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate() { try { Literal random = rand.evaluate(f); assertNotNull(random); assertEquals(XMLSchema.DOUBLE, random.getDatatype()); double randomValue = random.doubleValue(); assertTrue(randomValue >= 0.0d); assertTrue(randomValue < 1.0d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate() { try { Literal random = rand.evaluate(f); assertNotNull(random); assertEquals(XSD.DOUBLE, random.getDatatype()); double randomValue = random.doubleValue(); assertTrue(randomValue >= 0.0d); assertTrue(randomValue < 1.0d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
### Question: Round implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("ROUND requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) { Literal literal = (Literal) args[0]; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isNumericDatatype(datatype)) { if (XMLDatatypeUtil.isIntegerDatatype(datatype)) { return literal; } else if (XMLDatatypeUtil.isDecimalDatatype(datatype)) { BigDecimal rounded = literal.decimalValue().setScale(0, RoundingMode.HALF_UP); return valueFactory.createLiteral(rounded.toPlainString(), datatype); } else if (XMLDatatypeUtil.isFloatingPointDatatype(datatype)) { double ceilingValue = Math.round(literal.doubleValue()); return valueFactory.createLiteral(Double.toString(ceilingValue), datatype); } else { throw new ValueExprEvaluationException("unexpected datatype for function operand: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluateBigDecimal() { try { BigDecimal bd = new BigDecimal(1234567.567); Literal rounded = round.evaluate(f, f.createLiteral(bd.toPlainString(), XMLSchema.DECIMAL)); BigDecimal roundValue = rounded.decimalValue(); assertEquals(new BigDecimal(1234568.0), roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateDouble() { try { double dVal = 1.6; Literal rounded = round.evaluate(f, f.createLiteral(dVal)); double roundValue = rounded.doubleValue(); assertEquals((double) 2.0, roundValue, 0.001d); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateInt() { try { int iVal = 1; Literal rounded = round.evaluate(f, f.createLiteral(iVal)); int roundValue = rounded.intValue(); assertEquals(iVal, roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluateBigDecimal() { try { BigDecimal bd = new BigDecimal(1234567.567); Literal rounded = round.evaluate(f, f.createLiteral(bd.toPlainString(), XSD.DECIMAL)); BigDecimal roundValue = rounded.decimalValue(); assertEquals(new BigDecimal(1234568.0), roundValue); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
### Question: Tz implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TZ requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { String lexValue = literal.getLabel(); Pattern pattern = Pattern.compile("Z|[+-]\\d\\d:\\d\\d"); Matcher m = pattern.matcher(lexValue); String timeZone = ""; if (m.find()) { timeZone = m.group(); } return valueFactory.createLiteral(timeZone); } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate1() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("-05:00", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("Z", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate1() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("-05:00", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("Z", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { Literal result = tz.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XSD.DATETIME)); assertNotNull(result); assertEquals(XSD.STRING, result.getDatatype()); assertEquals("", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
### Question: Timezone implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException("TIMEZONE requires 1 argument, got " + args.length); } Value argValue = args[0]; if (argValue instanceof Literal) { Literal literal = (Literal) argValue; IRI datatype = literal.getDatatype(); if (datatype != null && XMLDatatypeUtil.isCalendarDatatype(datatype)) { try { XMLGregorianCalendar calValue = literal.calendarValue(); int timezoneOffset = calValue.getTimezone(); if (DatatypeConstants.FIELD_UNDEFINED != timezoneOffset) { int minutes = Math.abs(timezoneOffset); int hours = minutes / 60; minutes = minutes - (hours * 60); StringBuilder tzDuration = new StringBuilder(); if (timezoneOffset < 0) { tzDuration.append("-"); } tzDuration.append("PT"); if (hours > 0) { tzDuration.append(hours + "H"); } if (minutes > 0) { tzDuration.append(minutes + "M"); } if (timezoneOffset == 0) { tzDuration.append("0S"); } return valueFactory.createLiteral(tzDuration.toString(), XMLSchema.DAYTIMEDURATION); } else { throw new ValueExprEvaluationException("can not determine timezone from value: " + argValue); } } catch (IllegalArgumentException e) { throw new ValueExprEvaluationException("illegal calendar value: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + argValue); } } else { throw new ValueExprEvaluationException("unexpected input value for function: " + args[0]); } } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void testEvaluate1() { try { Literal result = timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815-05:00", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.DAYTIMEDURATION, result.getDatatype()); assertEquals("-PT5H", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate2() { try { Literal result = timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815Z", XMLSchema.DATETIME)); assertNotNull(result); assertEquals(XMLSchema.DAYTIMEDURATION, result.getDatatype()); assertEquals("PT0S", result.getLabel()); } catch (ValueExprEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testEvaluate3() { try { timezone.evaluate(f, f.createLiteral("2011-01-10T14:45:13.815", XMLSchema.DATETIME)); fail("should have resulted in a type error"); } catch (ValueExprEvaluationException e) { } }
### Question: SpinParser { public SpinParser() { this(Input.TEXT_FIRST); } SpinParser(); SpinParser(Input input); SpinParser(Input input, Function<IRI, String> wellKnownVarsMapper, Function<IRI, String> wellKnownFuncMapper); List<FunctionParser> getFunctionParsers(); void setFunctionParsers(List<FunctionParser> functionParsers); List<TupleFunctionParser> getTupleFunctionParsers(); void setTupleFunctionParsers(List<TupleFunctionParser> tupleFunctionParsers); boolean isStrictFunctionChecking(); void setStrictFunctionChecking(boolean strictFunctionChecking); Map<IRI, RuleProperty> parseRuleProperties(TripleSource store); boolean isThisUnbound(Resource subj, TripleSource store); ConstraintViolation parseConstraintViolation(Resource subj, TripleSource store); ParsedOperation parse(Resource queryResource, TripleSource store); ParsedQuery parseQuery(Resource queryResource, TripleSource store); ParsedGraphQuery parseConstructQuery(Resource queryResource, TripleSource store); ParsedTupleQuery parseSelectQuery(Resource queryResource, TripleSource store); ParsedBooleanQuery parseAskQuery(Resource queryResource, TripleSource store); ParsedDescribeQuery parseDescribeQuery(Resource queryResource, TripleSource store); ParsedUpdate parseUpdate(Resource queryResource, TripleSource store); org.eclipse.rdf4j.query.algebra.evaluation.function.Function parseFunction(IRI funcUri, TripleSource store); TupleFunction parseMagicProperty(IRI propUri, TripleSource store); Map<IRI, Argument> parseArguments(final IRI moduleUri, final TripleSource store); ValueExpr parseExpression(Value expr, TripleSource store); void reset(IRI... uris); static List<IRI> orderArguments(Set<IRI> args); }### Answer: @Test public void testSpinParser() throws IOException, RDF4JException { StatementCollector expected = new StatementCollector(); RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(expected); try (InputStream rdfStream = testURL.openStream()) { parser.parse(rdfStream, testURL.toString()); } Resource queryResource = null; for (Statement stmt : expected.getStatements()) { if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) { queryResource = stmt.getSubject(); break; } } assertNotNull(queryResource); TripleSource store = new ModelTripleSource(new TreeModel(expected.getStatements())); ParsedOperation textParsedOp = textParser.parse(queryResource, store); ParsedOperation rdfParsedOp = rdfParser.parse(queryResource, store); if (textParsedOp instanceof ParsedQuery) { assertEquals(((ParsedQuery) textParsedOp).getTupleExpr(), ((ParsedQuery) rdfParsedOp).getTupleExpr()); } else { assertEquals(((ParsedUpdate) textParsedOp).getUpdateExprs(), ((ParsedUpdate) rdfParsedOp).getUpdateExprs()); } } @Test public void testSpinParser() throws IOException, RDF4JException { StatementCollector expected = new StatementCollector(); RDFParser parser = Rio.createParser(RDFFormat.TURTLE); parser.setRDFHandler(expected); try (InputStream rdfStream = testURL.openStream()) { parser.parse(rdfStream, testURL.toString()); } Resource queryResource = null; for (Statement stmt : expected.getStatements()) { if (SP.TEXT_PROPERTY.equals(stmt.getPredicate())) { queryResource = stmt.getSubject(); break; } } assertNotNull(queryResource); TripleSource store = new ModelTripleSource(new TreeModel(expected.getStatements())); ParsedOperation textParsedOp = textParser.parse(queryResource, store); ParsedOperation rdfParsedOp = rdfParser.parse(queryResource, store); if (textParsedOp instanceof ParsedQuery) { assertEquals(((ParsedQuery) textParsedOp).getTupleExpr(), ((ParsedQuery) rdfParsedOp).getTupleExpr()); } else { List<UpdateExpr> textUpdates = ((ParsedUpdate) textParsedOp).getUpdateExprs(); List<UpdateExpr> rdfUpdates = ((ParsedUpdate) rdfParsedOp).getUpdateExprs(); assertThat(textUpdates).isEqualTo(rdfUpdates); } }
### Question: Concat implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length == 0) { throw new ValueExprEvaluationException("CONCAT requires at least 1 argument, got " + args.length); } StringBuilder concatBuilder = new StringBuilder(); String commonLanguageTag = null; boolean useLanguageTag = true; for (Value arg : args) { if (arg instanceof Literal) { Literal lit = (Literal) arg; if (!QueryEvaluationUtil.isStringLiteral(lit)) { throw new ValueExprEvaluationException("unexpected datatype for CONCAT operand: " + lit); } if (useLanguageTag && Literals.isLanguageLiteral(lit)) { if (commonLanguageTag == null) { commonLanguageTag = lit.getLanguage().get(); } else if (!commonLanguageTag.equals(lit.getLanguage().orElse(null))) { commonLanguageTag = null; useLanguageTag = false; } } else { useLanguageTag = false; } concatBuilder.append(lit.getLabel()); } else { throw new ValueExprEvaluationException("unexpected argument type for CONCAT operator: " + arg); } } Literal result = null; if (useLanguageTag) { result = valueFactory.createLiteral(concatBuilder.toString(), commonLanguageTag); } else { result = valueFactory.createLiteral(concatBuilder.toString()); } return result; } @Override String getURI(); @Override Literal evaluate(ValueFactory valueFactory, Value... args); }### Answer: @Test public void stringLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_nl, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XMLSchema.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void stringLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void commonLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_en, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(RDF.LANGSTRING); assertThat(result.getLanguage().get()).isEqualTo("en"); } @Test public void mixedLanguageLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo_nl, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void mixedLiteralHandling() { Literal result = concatFunc.evaluate(vf, foo, bar_en); assertThat(result.stringValue()).isEqualTo("foobar"); assertThat(result.getDatatype()).isEqualTo(XSD.STRING); assertThat(result.getLanguage().isPresent()).isFalse(); } @Test public void nonStringLiteralHandling() { try { concatFunc.evaluate(vf, RDF.TYPE, BooleanLiteral.TRUE); fail("CONCAT expected to fail on non-stringliteral argument"); } catch (ValueExprEvaluationException e) { } } @Test public void nonLiteralHandling() { try { concatFunc.evaluate(vf, RDF.TYPE, bar_en); fail("CONCAT expected to fail on non-literal argument"); } catch (ValueExprEvaluationException e) { } }
### Question: Util { public static Resource[] getContexts(String[] tokens, int pos, Repository repository) throws IllegalArgumentException { Resource[] contexts = new Resource[] {}; if (tokens.length > pos) { contexts = new Resource[tokens.length - pos]; for (int i = pos; i < tokens.length; i++) { contexts[i - pos] = getContext(repository, tokens[i]); } } return contexts; } static Resource getContext(Repository repository, String ctxID); static Resource[] getContexts(String[] tokens, int pos, Repository repository); static Path getPath(String file); static String getPrefixedValue(Value value, Map<String, String> namespaces); @Deprecated static String formatToWidth(int width, String padding, String str, String separator); }### Answer: @Test public final void testContextsTwo() { String ONE = "http: String TWO = "_:two"; ValueFactory f = repo.getValueFactory(); Resource[] check = new Resource[] { f.createIRI(ONE), f.createBNode(TWO.substring(2)) }; String[] tokens = { "command", ONE, TWO }; Resource[] ctxs = Util.getContexts(tokens, 1, repo); assertTrue("Not equal", Arrays.equals(check, ctxs)); } @Test public final void testContextsNull() { String[] tokens = { "command", "command2", "NULL" }; Resource[] ctxs = Util.getContexts(tokens, 2, repo); assertTrue("Not null", ctxs[0] == null); } @Test public final void testContextsInvalid() { String[] tokens = { "command", "invalid" }; try { Resource[] ctxs = Util.getContexts(tokens, 1, repo); fail("No exception generated"); } catch (IllegalArgumentException expected) { } }
### Question: Verify extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length != 2 && tokens.length != 4) { consoleIO.writeln(getHelpLong()); return; } String dataPath = parseDataPath(tokens[1]); verify(dataPath); if (tokens.length == 4) { String shaclPath = parseDataPath(tokens[2]); String reportFile = tokens[3]; shacl(dataPath, shaclPath, reportFile); } } Verify(ConsoleIO consoleIO); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public final void testVerifyMissingType() throws IOException { cmd.execute("verify", copyFromRes("missing_type.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifySpaceIRI() throws IOException { cmd.execute("verify", copyFromRes("space_iri.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifyWrongLang() throws IOException { cmd.execute("verify", copyFromRes("wrong_lang.ttl")); assertTrue(io.wasErrorWritten()); } @Test public final void testShaclInvalid() throws IOException { File report = LOCATION.newFile(); cmd.execute("verify", copyFromRes("ok.ttl"), copyFromRes("shacl_invalid.ttl"), report.toString()); assertTrue(io.wasErrorWritten()); assertTrue(Files.size(report.toPath()) > 0); } @Test public final void testShaclValid() throws IOException { File report = LOCATION.newFile(); cmd.execute("verify", copyFromRes("ok.ttl"), copyFromRes("shacl_valid.ttl"), report.toString()); assertFalse(Files.size(report.toPath()) > 0); assertFalse(io.wasErrorWritten()); } @Test public final void testVerifyWrongFormat() { cmd.execute("verify", "does-not-exist.docx"); assertTrue(io.wasErrorWritten()); } @Test public final void testVerifyOK() throws IOException { cmd.execute("verify", copyFromRes("ok.ttl")); assertFalse(io.wasErrorWritten()); } @Test public final void testVerifyBrokenFile() throws IOException { cmd.execute("verify", copyFromRes("broken.ttl")); assertTrue(io.wasErrorWritten()); }
### Question: Export extends ConsoleCommand { @Override public void execute(String... tokens) { Repository repository = state.getRepository(); if (repository == null) { consoleIO.writeUnopenedError(); return; } if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); return; } String fileName = tokens[1]; Resource[] contexts; try { contexts = Util.getContexts(tokens, 2, repository); } catch (IllegalArgumentException ioe) { consoleIO.writeError(ioe.getMessage()); return; } export(repository, fileName, contexts); } Export(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public final void testExportAll() throws RepositoryException, IOException { File nq = LOCATION.newFile("all.nq"); export.execute("export", nq.toString()); Model exp = Rio.parse(Files.newReader(nq, StandardCharsets.UTF_8), "http: assertTrue("File is empty", nq.length() > 0); assertEquals("Number of contexts incorrect", 3, exp.contexts().size()); nq.delete(); } @Test public final void testExportContexts() throws RepositoryException, IOException { File nq = LOCATION.newFile("default.nq"); export.execute("export", nq.toString(), "null", "http: Model exp = Rio.parse(Files.newReader(nq, StandardCharsets.UTF_8), "http: assertTrue("File is empty", nq.length() > 0); assertEquals("Number of contexts incorrect", 2, exp.contexts().size()); assertEquals("Number of triples incorrect", 4, exp.size()); nq.delete(); }
### Question: Convert extends ConsoleCommand { private void convert(String fileFrom, String fileTo) { Path pathFrom = Util.getPath(fileFrom); if (pathFrom == null) { consoleIO.writeError("Invalid file name (from) " + fileFrom); return; } if (Files.notExists(pathFrom)) { consoleIO.writeError("File not found (from) " + fileFrom); return; } Optional<RDFFormat> fmtFrom = Rio.getParserFormatForFileName(fileFrom); if (!fmtFrom.isPresent()) { consoleIO.writeError("No RDF parser for " + fileFrom); return; } Path pathTo = Util.getPath(fileTo); if (pathTo == null) { consoleIO.writeError("Invalid file name (to) " + pathTo); return; } Optional<RDFFormat> fmtTo = Rio.getWriterFormatForFileName(fileTo); if (!fmtTo.isPresent()) { consoleIO.writeError("No RDF writer for " + fileTo); return; } if (Files.exists(pathTo)) { try { boolean overwrite = consoleIO.askProceed("File exists, continue ?", false); if (!overwrite) { consoleIO.writeln("Conversion aborted"); return; } } catch (IOException ioe) { consoleIO.writeError("I/O error " + ioe.getMessage()); } } RDFParser parser = Rio.createParser(fmtFrom.get()); String baseURI = pathFrom.toUri().toString(); try (BufferedInputStream r = new BufferedInputStream(Files.newInputStream(pathFrom)); BufferedWriter w = Files.newBufferedWriter(pathTo)) { RDFWriter writer = Rio.createWriter(fmtTo.get(), w); parser.setRDFHandler(writer); long startTime = System.nanoTime(); consoleIO.writeln("Converting file ..."); parser.parse(r, baseURI); long diff = (System.nanoTime() - startTime) / 1_000_000; consoleIO.writeln("Data has been written to file (" + diff + " ms)"); } catch (IOException | RDFParseException | RDFHandlerException e) { consoleIO.writeError("Failed to convert data: " + e.getMessage()); } } Convert(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public final void testConvert() throws IOException { File json = LOCATION.newFile("alien.jsonld"); convert.execute("convert", from.toString(), json.toString()); assertTrue("File is empty", json.length() > 0); Object o = null; try { o = JsonUtils.fromInputStream(Files.newInputStream(json.toPath())); } catch (IOException ioe) { } assertTrue("Invalid JSON", o != null); }
### Question: Convert extends ConsoleCommand { @Override public void execute(String... tokens) { if (tokens.length < 3) { consoleIO.writeln(getHelpLong()); return; } convert(tokens[1], tokens[2]); } Convert(ConsoleIO consoleIO, ConsoleState state); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public final void testConvertParseError() throws IOException { File wrong = LOCATION.newFile("wrong.nt"); Files.write(wrong.toPath(), "error".getBytes()); File json = LOCATION.newFile("empty.jsonld"); convert.execute("convert", wrong.toString(), json.toString()); verify(mockConsoleIO).writeError(anyString()); } @Test public final void testConvertInvalidFormat() throws IOException { File qyx = LOCATION.newFile("alien.qyx"); convert.execute("convert", from.toString(), qyx.toString()); verify(mockConsoleIO).writeError("No RDF writer for " + qyx.toString()); }
### Question: SetParameters extends ConsoleCommand { @Override public void execute(String... tokens) { switch (tokens.length) { case 0: consoleIO.writeln(getHelpLong()); break; case 1: for (String setting : settings.keySet()) { showSetting(setting); } break; default: String param = tokens[1]; int eqIdx = param.indexOf('='); if (eqIdx < 0) { showSetting(param); } else { String key = param.substring(0, eqIdx); String values = String.join(" ", tokens); eqIdx = values.indexOf('='); setParameter(key, values.substring(eqIdx + 1)); } } } SetParameters(ConsoleIO consoleIO, ConsoleState state, Map<String, ConsoleSetting> settings); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public void testUnknownParametersAreErrors() { setParameters.execute("set", "unknown"); verify(mockConsoleIO).writeError("Unknown parameter: unknown"); verifyNoMoreInteractions(mockConsoleIO); }
### Question: ValueDecoder { protected Value decodeValue(String string) throws BadRequestException { Value result = null; try { if (string != null) { String value = string.trim(); if (!value.isEmpty() && !"null".equals(value)) { if (value.startsWith("_:")) { String label = value.substring("_:".length()); result = factory.createBNode(label); } else { if (value.charAt(0) == '<' && value.endsWith(">")) { result = factory.createIRI(value.substring(1, value.length() - 1)); } else { if (value.charAt(0) == '"') { result = parseLiteral(value); } else { result = parseURI(value); } } } } } } catch (Exception exc) { LOGGER.warn(exc.toString(), exc); throw new BadRequestException("Malformed value: " + string, exc); } return result; } protected ValueDecoder(Repository repository, ValueFactory factory); }### Answer: @Test public final void testLiteralWithURIType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^<" + XMLSchema.INT + ">"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testQnamePropertyValue() throws BadRequestException { Value value = decoder.decodeValue("rdfs:label"); assertThat(value).isInstanceOf(IRI.class); assertThat((IRI) value).isEqualTo(RDFS.LABEL); } @Test public final void testPlainStringLiteral() throws BadRequestException { Value value = decoder.decodeValue("\"plain string\""); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral("plain string")); } @Test public final void testUnexpectedLiteralAttribute() throws BadRequestException { try { decoder.decodeValue("\"datatype oops\"^rdfs:label"); fail("Expected BadRequestException."); } catch (BadRequestException bre) { Throwable rootCause = bre.getRootCause(); assertThat(rootCause).isInstanceOf(BadRequestException.class); assertThat(rootCause).hasMessageStartingWith("Malformed language tag or datatype: "); } } @Test public final void testLiteralWithQNameType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^xsd:int"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testLiteralWithURIType() throws BadRequestException { Value value = decoder.decodeValue("\"1\"^^<" + XSD.INT + ">"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral(1)); } @Test public final void testLanguageLiteral() throws BadRequestException { Value value = decoder.decodeValue("\"color\"@en-US"); assertThat(value).isInstanceOf(Literal.class); assertThat((Literal) value).isEqualTo(factory.createLiteral("color", "en-US")); }
### Question: Util { @Deprecated public static String formatToWidth(int width, String padding, String str, String separator) { if (str.isEmpty()) { return ""; } int padLen = padding.length(); int strLen = str.length(); int sepLen = separator.length(); if (strLen + padLen <= width) { return padding + str; } String[] values = str.split(separator); StringBuilder builder = new StringBuilder(strLen + 4 * padLen + 8 * sepLen); int colpos = width; for (String value : values) { int len = value.length(); if (colpos + sepLen + len <= width) { builder.append(separator); } else { builder.append("\n").append(padding); colpos = padLen; } builder.append(value); colpos += len; } return builder.substring(1); } static Resource getContext(Repository repository, String ctxID); static Resource[] getContexts(String[] tokens, int pos, Repository repository); static Path getPath(String file); static String getPrefixedValue(Value value, Map<String, String> namespaces); @Deprecated static String formatToWidth(int width, String padding, String str, String separator); }### Answer: @Test public final void testFormatToWidth() { String str = "one, two, three, four, five, six, seven, eight"; String expect = " one, two\n" + " three\n" + " four\n" + " five, six\n" + " seven\n" + " eight"; String fmt = Util.formatToWidth(10, " ", str, ", "); System.err.println(fmt); assertTrue("Format not OK", expect.equals(fmt)); }
### Question: Drop extends ConsoleCommand { @Override public void execute(String... tokens) throws IOException { if (tokens.length < 2) { consoleIO.writeln(getHelpLong()); } else { final String repoID = tokens[1]; try { dropRepository(repoID); } catch (RepositoryConfigException e) { consoleIO.writeError("Unable to drop repository '" + repoID + "': " + e.getMessage()); LOGGER.warn("Unable to drop repository '" + repoID + "'", e); } catch (RepositoryReadOnlyException e) { try { if (LockRemover.tryToRemoveLock(state.getManager().getSystemRepository(), consoleIO)) { execute(tokens); } else { consoleIO.writeError("Failed to drop repository"); LOGGER.error("Failed to drop repository", e); } } catch (RepositoryException e2) { consoleIO.writeError("Failed to restart system: " + e2.getMessage()); LOGGER.error("Failed to restart system", e2); } } catch (RepositoryException e) { consoleIO.writeError("Failed to update configuration in system repository: " + e.getMessage()); LOGGER.warn("Failed to update configuration in system repository", e); } } } Drop(ConsoleIO consoleIO, ConsoleState state, Close close); @Override String getName(); @Override String getHelpShort(); @Override String getHelpLong(); @Override void execute(String... tokens); }### Answer: @Test public final void testSafeDrop() throws RepositoryException, IOException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(PROXY_ID)).isTrue(); drop.execute("drop", PROXY_ID); verify(mockConsoleIO).writeln("Dropped repository '" + PROXY_ID + "'"); assertThat(manager.isSafeToRemove(MEMORY_MEMBER_ID1)).isTrue(); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO).writeln("Dropped repository '" + MEMORY_MEMBER_ID1 + "'"); } @Test public final void testUnsafeDropCancel() throws RepositoryException, IOException { setUserDropConfirm(true); assertThat(manager.isSafeToRemove(MEMORY_MEMBER_ID1)).isFalse(); when(mockConsoleIO.askProceed(startsWith("WARNING: dropping this repository may break"), anyBoolean())) .thenReturn(false); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO).writeln("Drop aborted"); } @Test public final void testUserAbortedUnsafeDropBeforeWarning() throws IOException { setUserDropConfirm(false); drop.execute("drop", MEMORY_MEMBER_ID1); verify(mockConsoleIO, never()).askProceed(startsWith("WARNING: dropping this repository may break"), anyBoolean()); verify(mockConsoleIO).writeln("Drop aborted"); }
### Question: InfoServlet extends TransformationServlet { @Override protected void service(WorkbenchRequest req, HttpServletResponse resp, String xslPath) throws Exception { String id = info.getId(); if (null != id && !manager.hasRepositoryConfig(id)) { throw new RepositoryConfigException(id + " does not exist."); } TupleResultBuilder builder = getTupleResultBuilder(req, resp, resp.getOutputStream()); builder.start("id", "description", "location", "server", "readable", "writeable", "default-limit", "default-queryLn", "default-infer", "default-Accept", "default-Content-Type", "upload-format", "query-format", "graph-download-format", "tuple-download-format", "boolean-download-format"); String desc = info.getDescription(); URL loc = info.getLocation(); URL server = getServer(); builder.result(id, desc, loc, server, info.isReadable(), info.isWritable()); builder.namedResult("default-limit", req.getParameter("limit")); builder.namedResult("default-queryLn", req.getParameter("queryLn")); builder.namedResult("default-infer", req.getParameter("infer")); builder.namedResult("default-Accept", req.getParameter("Accept")); builder.namedResult("default-Content-Type", req.getParameter("Content-Type")); for (RDFParserFactory parser : RDFParserRegistry.getInstance().getAll()) { String mimeType = parser.getRDFFormat().getDefaultMIMEType(); String name = parser.getRDFFormat().getName(); builder.namedResult("upload-format", mimeType + " " + name); } for (QueryParserFactory factory : getInstance().getAll()) { String name = factory.getQueryLanguage().getName(); builder.namedResult("query-format", name + " " + name); } for (RDFWriterFactory writer : RDFWriterRegistry.getInstance().getAll()) { String mimeType = writer.getRDFFormat().getDefaultMIMEType(); String name = writer.getRDFFormat().getName(); builder.namedResult("graph-download-format", mimeType + " " + name); } for (TupleQueryResultWriterFactory writer : TupleQueryResultWriterRegistry.getInstance().getAll()) { String mimeType = writer.getTupleQueryResultFormat().getDefaultMIMEType(); String name = writer.getTupleQueryResultFormat().getName(); builder.namedResult("tuple-download-format", mimeType + " " + name); } for (BooleanQueryResultWriterFactory writer : BooleanQueryResultWriterRegistry.getInstance().getAll()) { String mimeType = writer.getBooleanQueryResultFormat().getDefaultMIMEType(); String name = writer.getBooleanQueryResultFormat().getName(); builder.namedResult("boolean-download-format", mimeType + " " + name); } builder.end(); } @Override String[] getCookieNames(); }### Answer: @Test public final void testSES1770regression() throws Exception { when(manager.hasRepositoryConfig(null)).thenThrow(new NullPointerException()); WorkbenchRequest req = mock(WorkbenchRequest.class); when(req.getParameter(anyString())).thenReturn(SESAME.NIL.toString()); HttpServletResponse resp = mock(HttpServletResponse.class); when(resp.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); servlet.service(req, resp, ""); } @Test public final void testSES1770regression() throws Exception { when(manager.hasRepositoryConfig(null)).thenThrow(new NullPointerException()); WorkbenchRequest req = mock(WorkbenchRequest.class); when(req.getParameter(anyString())).thenReturn(RDF4J.NIL.toString()); HttpServletResponse resp = mock(HttpServletResponse.class); when(resp.getOutputStream()).thenReturn(mock(ServletOutputStream.class)); servlet.service(req, resp, ""); }
### Question: DBDecryptor implements Decryptor { public void decryptDB(File input, File output) throws IOException, GeneralSecurityException { if (input == null) throw new IllegalArgumentException("input cannot be null"); if (output == null) throw new IllegalArgumentException("output cannot be null"); decryptStream(new FileInputStream(input), new FileOutputStream(output)); } void decryptDB(File input, File output); static void main(String[] args); }### Answer: @Test public void shouldDecryptDatabase() throws Exception { File out = File.createTempFile("db-test", ".sql"); dbDecryptor.decryptDB(Fixtures.TEST_DB_1, out); verifyDB(out); } @Test(expected = IllegalArgumentException.class) public void shouldThrowWithNullInput() throws Exception { dbDecryptor.decryptDB(null, new File(("/out"))); } @Test(expected = IllegalArgumentException.class) public void shouldThrowWithNullOutput() throws Exception { dbDecryptor.decryptDB(new File(("/in")), null); }
### Question: Whassup { public long getMostRecentTimestamp(boolean ignoreGroups) throws IOException { File currentDB = dbProvider.getDBFile(); if (currentDB == null) { return DEFAULT_MOST_RECENT; } else { SQLiteDatabase db = getSqLiteDatabase(decryptDB(currentDB)); Cursor cursor = null; try { String query = "SELECT MAX(" + TIMESTAMP + ") FROM " + WhatsAppMessage.TABLE; if (ignoreGroups) { query += " WHERE " + KEY_REMOTE_JID + " NOT LIKE ?"; } cursor = db.rawQuery( query, ignoreGroups ? new String[]{ "%@" + WhatsAppMessage.GROUP } : null ); if (cursor != null && cursor.moveToNext()) { return cursor.getLong(0); } else { return DEFAULT_MOST_RECENT; } } catch (SQLiteException e) { Log.w(TAG, e); return DEFAULT_MOST_RECENT; } finally { if (cursor != null) cursor.close(); } } } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }### Answer: @Test public void shouldGetMostRecentTimestamp() throws Exception { assertThat(whassup.getMostRecentTimestamp(true)).isEqualTo(1369589322298L); assertThat(whassup.getMostRecentTimestamp(false)).isEqualTo(1369589322298L); }
### Question: Whassup { public List<WhatsAppMessage> getMessages(long timestamp, int max) throws IOException { Cursor cursor = queryMessages(timestamp, max); try { if (cursor != null) { List<WhatsAppMessage> messages = new ArrayList<WhatsAppMessage>(cursor.getCount()); while (cursor.moveToNext()) { messages.add(new WhatsAppMessage(cursor)); } return messages; } else { return Collections.emptyList(); } } finally { if (cursor != null) { cursor.close(); } } } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }### Answer: @Test public void shouldGetMedia() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); WhatsAppMessage msg = null; for (WhatsAppMessage message : messages) { if (message.getId() == 82) { msg = message; break; } } assertThat(msg).isNotNull(); assertThat(msg.getMedia()).isNotNull(); Media mediaData = msg.getMedia(); assertThat(mediaData).isNotNull(); assertThat(mediaData.getFileSize()).isEqualTo(67731L); assertThat(mediaData.getFile().getAbsolutePath()).isEqualTo("/storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20130526-WA0000.jpg"); } @Test public void shouldReturnMessagesInAscendingTimestampOrder() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); assertThat(messages).isSortedAccordingTo(WhatsAppMessage.TimestampComparator.INSTANCE); WhatsAppMessage first = messages.get(0); WhatsAppMessage last = messages.get(messages.size() - 1); assertThat(first.getTimestamp()).isBefore(last.getTimestamp()); } @Test public void shouldGetAllMessages() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(82); } @Test public void shouldGetMessagesSinceASpecificTimestamp() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, -1); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(15); } @Test public void shouldGetMessagesSinceASpecificTimestampAndLimit() throws Exception { List<WhatsAppMessage> messages = whassup.getMessages(1367349391104L, 3); assertThat(messages).isNotEmpty(); assertThat(messages).hasSize(3); }
### Question: Whassup { public boolean hasBackupDB() { return dbProvider.getDBFile() != null; } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }### Answer: @Test public void shouldCheckIfDbIsAvailable() throws Exception { when(dbProvider.getDBFile()).thenReturn(null); assertThat(whassup.hasBackupDB()).isFalse(); when(dbProvider.getDBFile()).thenReturn(Fixtures.TEST_DB_1); assertThat(whassup.hasBackupDB()).isTrue(); }
### Question: Whassup { public Cursor queryMessages() throws IOException { return queryMessages(0, -1); } Whassup(Context context); Whassup(DecryptorFactory decryptorFactory, DBProvider dbProvider, DBOpener dbOpener); Cursor queryMessages(); Cursor queryMessages(long timestamp, int max); long getMostRecentTimestamp(boolean ignoreGroups); List<WhatsAppMessage> getMessages(long timestamp, int max); List<WhatsAppMessage> getMessages(); boolean hasBackupDB(); }### Answer: @Test(expected = IOException.class) public void shouldCatchSQLiteExceptionWhenOpeningDatabase() throws Exception { DBOpener dbOpener = mock(DBOpener.class); when(dbOpener.openDatabase(any(File.class))).thenThrow(new SQLiteException("failz")); new Whassup(decryptorFactory, dbProvider, dbOpener).queryMessages(); } @Test public void shouldQueryMessages() throws Exception { Cursor cursor = whassup.queryMessages(); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(82); cursor.close(); } @Test public void shouldQueryMessagesSinceASpecificTimestamp() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, -1); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(15); } @Test public void shouldQueryMessagesSinceASpecificTimestampAndLimit() throws Exception { Cursor cursor = whassup.queryMessages(1367349391104L, 3); assertThat(cursor).isNotNull(); assertThat(cursor.getCount()).isEqualTo(3); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public Date getTimestamp() { return new Date(timestamp); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldParseTimestamp() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.timestamp = 1358086780000L; assertThat(m.getTimestamp().getTime()).isEqualTo(1358086780000L); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public String getNumber() { if (TextUtils.isEmpty(key_remote_jid)) return null; String[] components = key_remote_jid.split("@", 2); if (components.length > 1) { if (!isGroupMessage()) { return components[0]; } else { return components[0].split("-")[0]; } } else { return null; } } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldParseNumber() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } @Test public void shouldParseNumberFromGroupMessage() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "[email protected]"; assertThat(m.getNumber()).isEqualTo("4915773981234"); } @Test public void shouldParseNumberWithInvalidSpec() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.getNumber()).isNull(); m.key_remote_jid = "foobaz"; assertThat(m.getNumber()).isNull(); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { @Override public int compareTo(WhatsAppMessage another) { return TimestampComparator.INSTANCE.compare(this, another); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldImplementComparableBasedOnTimestamp() throws Exception { WhatsAppMessage m1 = new WhatsAppMessage(); WhatsAppMessage m2 = new WhatsAppMessage(); m1.timestamp = 1; m2.timestamp = 2; assertThat(m1.compareTo(m2)).isLessThan(0); assertThat(m2.compareTo(m1)).isGreaterThan(0); assertThat(m2.compareTo(m2)).isEqualTo(0); assertThat(m1.compareTo(m1)).isEqualTo(0); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean hasText() { return !TextUtils.isEmpty(data); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldHaveTextIfNonEmptyString() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.hasText()).isFalse(); m.data = ""; assertThat(m.hasText()).isFalse(); m.data = "some text"; assertThat(m.hasText()).isTrue(); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { public boolean isReceived() { return key_from_me == 0; } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldCheckIfReceived() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.isReceived()).isTrue(); m.key_from_me = 1; assertThat(m.isReceived()).isFalse(); }
### Question: WhatsAppMessage implements Comparable<WhatsAppMessage> { static String filterPrivateBlock(String s) { if (s == null) return null; final StringBuilder sb = new StringBuilder(); for (int i=0; i<s.length(); ) { int codepoint = s.codePointAt(i); Character.UnicodeBlock block = Character.UnicodeBlock.of(codepoint); if (block != Character.UnicodeBlock.PRIVATE_USE_AREA) { sb.append(Character.toChars(codepoint)); } i += Character.charCount(codepoint); } return sb.toString(); } WhatsAppMessage(); WhatsAppMessage(Cursor c); long getId(); boolean isReceived(); Date getTimestamp(); String getText(); String getFilteredText(); int getStatus(); double getLongitude(); double getLatitude(); int getRecipientCount(); String getNumber(); Media getMedia(); Receipt getReceipt(); boolean hasMediaAttached(); boolean hasText(); @Override String toString(); @Override int compareTo(WhatsAppMessage another); boolean isDirectMessage(); boolean isGroupMessage(); static final String TABLE; static final String GROUP; static final String DIRECT; }### Answer: @Test public void shouldFilterPrivateUnicodeCharacters() throws Exception { byte[] b = new byte[] { (byte) 0xee, (byte) 0x90, (byte) 0x87, (byte) 0xf0, (byte) 0x9f, (byte) 0x98, (byte) 0xa4, (byte) 0xee, (byte) 0x84, (byte) 0x87 }; String s = new String(b, Charset.forName("UTF-8")); assertThat(s.length()).isEqualTo(4); String filtered = WhatsAppMessage.filterPrivateBlock(s); assertThat(filtered).isEqualTo("\uD83D\uDE24"); assertThat(filtered.length()).isEqualTo(2); } @Test public void shouldFilterPrivateUnicodeCharactersNull() throws Exception { assertThat(WhatsAppMessage.filterPrivateBlock(null)).isNull(); }
### Question: Media { public File getFile() { MediaData md = getMediaData(); return md == null ? null : md.getFile(); } Media(); Media(Cursor c); byte[] getRawData(); String getMimeType(); String getUrl(); int getSize(); File getFile(); long getFileSize(); @Override String toString(); }### Answer: @Test public void shouldHandleSerializedDataOfWrongType() throws Exception { Media media = new Media(); media.thumb_image = fileToBytes(Fixtures.VECTOR_SERIALIZED); assertThat(media.getFile()).isNull(); } @Test public void shouldHandleInvalidSerializedData() throws Exception { Media media = new Media(); media.thumb_image = new byte[] {(byte) 0xde, (byte) 0xad, (byte) 0xbe, (byte) 0xef}; assertThat(media.getFile()).isNull(); }
### Question: DBDecryptor implements Decryptor { protected void decryptStream(InputStream in, OutputStream out) throws GeneralSecurityException, IOException { Cipher cipher = getCipher(Cipher.DECRYPT_MODE); CipherInputStream cis = null; try { cis = new CipherInputStream(in, cipher); byte[] buffer = new byte[8192]; int n; while ((n = cis.read(buffer)) != -1) { out.write(buffer, 0, n); } } finally { try { if (cis != null) cis.close(); out.close(); } catch (IOException ignored) {} } } void decryptDB(File input, File output); static void main(String[] args); }### Answer: @Test public void shouldDecryptStream() throws Exception { File out = File.createTempFile("db-test", ".sql"); FileOutputStream fos = new FileOutputStream(out); dbDecryptor.decryptStream(new FileInputStream(Fixtures.TEST_DB_1), fos); verifyDB(out); }
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); return personRepository.findPersonsForPage(searchTerm, pageIndex); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void search() { personService.search(SEARCH_TERM, PAGE_INDEX); verify(personRepositoryMock, times(1)).findPersonsForPage(SEARCH_TERM, PAGE_INDEX); verifyNoMoreInteractions(personRepositoryMock); }
### Question: PersonSpecifications { public static Specification<Person> lastNameIsLike(final String searchTerm) { return new Specification<Person>() { @Override public Predicate toPredicate(Root<Person> personRoot, CriteriaQuery<?> query, CriteriaBuilder cb) { String likePattern = getLikePattern(searchTerm); return cb.like(cb.lower(personRoot.<String>get(Person_.lastName)), likePattern); } private String getLikePattern(final String searchTerm) { StringBuilder pattern = new StringBuilder(); pattern.append(searchTerm.toLowerCase()); pattern.append("%"); return pattern.toString(); } }; } static Specification<Person> lastNameIsLike(final String searchTerm); }### Answer: @Test public void lastNameIsLike() { Path lastNamePathMock = mock(Path.class); when(personRootMock.get(Person_.lastName)).thenReturn(lastNamePathMock); Expression lastNameToLowerExpressionMock = mock(Expression.class); when(criteriaBuilderMock.lower(lastNamePathMock)).thenReturn(lastNameToLowerExpressionMock); Predicate lastNameIsLikePredicateMock = mock(Predicate.class); when(criteriaBuilderMock.like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN)).thenReturn(lastNameIsLikePredicateMock); Specification<Person> actual = PersonSpecifications.lastNameIsLike(SEARCH_TERM); Predicate actualPredicate = actual.toPredicate(personRootMock, criteriaQueryMock, criteriaBuilderMock); verify(personRootMock, times(1)).get(Person_.lastName); verifyNoMoreInteractions(personRootMock); verify(criteriaBuilderMock, times(1)).lower(lastNamePathMock); verify(criteriaBuilderMock, times(1)).like(lastNameToLowerExpressionMock, SEARCH_TERM_LIKE_PATTERN); verifyNoMoreInteractions(criteriaBuilderMock); verifyZeroInteractions(criteriaQueryMock, lastNamePathMock, lastNameIsLikePredicateMock); assertEquals(lastNameIsLikePredicateMock, actualPredicate); }
### Question: RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person update(PersonDTO updated) throws PersonNotFoundException { LOGGER.debug("Updating person with information: " + updated); Person person = personRepository.findOne(updated.getId()); if (person == null) { LOGGER.debug("No person found with id: " + updated.getId()); throw new PersonNotFoundException(); } person.update(updated.getFirstName(), updated.getLastName()); return person; } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void update() throws PersonNotFoundException { PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(updated.getId())).thenReturn(person); Person returned = personService.update(updated); verify(personRepositoryMock, times(1)).findOne(updated.getId()); verifyNoMoreInteractions(personRepositoryMock); assertPerson(updated, returned); } @Test(expected = PersonNotFoundException.class) public void updateWhenPersonIsNotFound() throws PersonNotFoundException { PersonDTO updated = PersonTestUtil.createDTO(PERSON_ID, FIRST_NAME_UPDATED, LAST_NAME_UPDATED); when(personRepositoryMock.findOne(updated.getId())).thenReturn(null); personService.update(updated); verify(personRepositoryMock, times(1)).findOne(updated.getId()); verifyNoMoreInteractions(personRepositoryMock); }
### Question: PersonController extends AbstractController { @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody public Long count(@RequestBody SearchDTO searchCriteria) { String searchTerm = searchCriteria.getSearchTerm(); LOGGER.debug("Finding person count for search term: " + searchTerm); return personService.count(searchTerm); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void count() { SearchDTO searchCriteria = createSearchDTO(); when(personServiceMock.count(searchCriteria.getSearchTerm())).thenReturn(PERSON_COUNT); long personCount = controller.count(searchCriteria); verify(personServiceMock, times(1)).count(searchCriteria.getSearchTerm()); verifyNoMoreInteractions(personServiceMock); assertEquals(PERSON_COUNT, personCount); }
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) public String delete(@PathVariable("id") Long id, RedirectAttributes attributes) { LOGGER.debug("Deleting person with id: " + id); try { Person deleted = personService.delete(id); addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_PERSON_DELETED, deleted.getName()); } catch (PersonNotFoundException e) { LOGGER.debug("No person found with id: " + id); addErrorMessage(attributes, ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); } return createRedirectViewPath(REQUEST_MAPPING_LIST); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void delete() throws PersonNotFoundException { Person deleted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personServiceMock.delete(PERSON_ID)).thenReturn(deleted); initMessageSourceForFeedbackMessage(PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.delete(PERSON_ID, attributes); verify(personServiceMock, times(1)).delete(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertFeedbackMessage(attributes, PersonController.FEEDBACK_MESSAGE_KEY_PERSON_DELETED); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); } @Test public void deleteWhenPersonIsNotFound() throws PersonNotFoundException { when(personServiceMock.delete(PERSON_ID)).thenThrow(new PersonNotFoundException()); initMessageSourceForErrorMessage(PersonController.ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.delete(PERSON_ID, attributes); verify(personServiceMock, times(1)).delete(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertErrorMessage(attributes, PersonController.ERROR_MESSAGE_KEY_DELETED_PERSON_WAS_NOT_FOUND); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); }
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody public List<PersonDTO> search(@RequestBody SearchDTO searchCriteria) { LOGGER.debug("Searching persons with search criteria: " + searchCriteria); String searchTerm = searchCriteria.getSearchTerm(); List<Person> persons = personService.search(searchTerm, searchCriteria.getPageIndex()); LOGGER.debug("Found " + persons.size() + " persons"); return constructDTOs(persons); } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void searchWhenNoPersonsIsFound() { SearchDTO searchCriteria = createSearchDTO(); List<Person> expected = new ArrayList<Person>(); when(personServiceMock.search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex())).thenReturn(expected); List<PersonDTO> actual = controller.search(searchCriteria); verify(personServiceMock, times(1)).search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex()); verifyNoMoreInteractions(personServiceMock); assertDtos(expected, actual); } @Test public void search() { SearchDTO searchCriteria = createSearchDTO(); List<Person> expected = createModels(); when(personServiceMock.search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex())).thenReturn(expected); List<PersonDTO> actual = controller.search(searchCriteria); verify(personServiceMock, times(1)).search(searchCriteria.getSearchTerm(), searchCriteria.getPageIndex()); verifyNoMoreInteractions(personServiceMock); assertDtos(expected, actual); }
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/create", method = RequestMethod.GET) public String showCreatePersonForm(Model model) { LOGGER.debug("Rendering create person form"); model.addAttribute(MODEL_ATTIRUTE_PERSON, new PersonDTO()); return PERSON_ADD_FORM_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void showCreatePersonForm() { Model model = new BindingAwareModelMap(); String view = controller.showCreatePersonForm(model); verifyZeroInteractions(personServiceMock); assertEquals(PersonController.PERSON_ADD_FORM_VIEW, view); PersonDTO added = (PersonDTO) model.asMap().get(PersonController.MODEL_ATTIRUTE_PERSON); assertNotNull(added); assertNull(added.getId()); assertNull(added.getFirstName()); assertNull(added.getLastName()); }
### Question: Person { @PrePersist public void prePersist() { Date now = new Date(); creationTime = now; modificationTime = now; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }### Answer: @Test public void prePersist() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.prePersist(); Date creationTime = built.getCreationTime(); Date modificationTime = built.getModificationTime(); assertNotNull(creationTime); assertNotNull(modificationTime); assertEquals(creationTime, modificationTime); }
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) public String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes) { LOGGER.debug("Rendering edit person form for person with id: " + id); Person person = personService.findById(id); if (person == null) { LOGGER.debug("No person found with id: " + id); addErrorMessage(attributes, ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); return createRedirectViewPath(REQUEST_MAPPING_LIST); } model.addAttribute(MODEL_ATTIRUTE_PERSON, constructFormObject(person)); return PERSON_EDIT_FORM_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void showEditPersonForm() { Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personServiceMock.findById(PERSON_ID)).thenReturn(person); Model model = new BindingAwareModelMap(); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.showEditPersonForm(PERSON_ID, model, attributes); verify(personServiceMock, times(1)).findById(PERSON_ID); verifyNoMoreInteractions(personServiceMock); assertEquals(PersonController.PERSON_EDIT_FORM_VIEW, view); PersonDTO formObject = (PersonDTO) model.asMap().get(PersonController.MODEL_ATTIRUTE_PERSON); assertNotNull(formObject); assertEquals(person.getId(), formObject.getId()); assertEquals(person.getFirstName(), formObject.getFirstName()); assertEquals(person.getLastName(), formObject.getLastName()); } @Test public void showEditPersonFormWhenPersonIsNotFound() { when(personServiceMock.findById(PERSON_ID)).thenReturn(null); initMessageSourceForErrorMessage(PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); Model model = new BindingAwareModelMap(); RedirectAttributes attributes = new RedirectAttributesModelMap(); String view = controller.showEditPersonForm(PERSON_ID, model, attributes); verify(personServiceMock, times(1)).findById(PERSON_ID); verifyNoMoreInteractions(personServiceMock); String expectedView = createExpectedRedirectViewPath(PersonController.REQUEST_MAPPING_LIST); assertEquals(expectedView, view); assertErrorMessage(attributes, PersonController.ERROR_MESSAGE_KEY_EDITED_PERSON_WAS_NOT_FOUND); }
### Question: Person { @PreUpdate public void preUpdate() { modificationTime = new Date(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }### Answer: @Test public void preUpdate() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.prePersist(); try { Thread.sleep(1000); } catch (InterruptedException e) { } built.preUpdate(); Date creationTime = built.getCreationTime(); Date modificationTime = built.getModificationTime(); assertNotNull(creationTime); assertNotNull(modificationTime); assertTrue(modificationTime.after(creationTime)); }
### Question: PersonController extends AbstractController { @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) public String showList(Model model) { LOGGER.debug("Rendering person list page"); List<Person> persons = personService.findAll(); model.addAttribute(MODEL_ATTRIBUTE_PERSONS, persons); model.addAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA, new SearchDTO()); return PERSON_LIST_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void showList() { List<Person> persons = new ArrayList<Person>(); when(personServiceMock.findAll()).thenReturn(persons); Model model = new BindingAwareModelMap(); String view = controller.showList(model); verify(personServiceMock, times(1)).findAll(); verifyNoMoreInteractions(personServiceMock); assertEquals(PersonController.PERSON_LIST_VIEW, view); assertEquals(persons, model.asMap().get(PersonController.MODEL_ATTRIBUTE_PERSONS)); SearchDTO searchCriteria = (SearchDTO) model.asMap().get(PersonController.MODEL_ATTRIBUTE_SEARCH_CRITERIA); assertNotNull(searchCriteria); assertNull(searchCriteria.getSearchTerm()); }
### Question: PersonController extends AbstractController { @RequestMapping(value = "/person/search", method=RequestMethod.POST) public String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model) { LOGGER.debug("Rendering search result page for search criteria: " + searchCriteria); model.addAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA, searchCriteria); return PERSON_SEARCH_RESULT_VIEW; } @RequestMapping(value="/person/count", method = RequestMethod.POST) @ResponseBody Long count(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/delete/{id}", method = RequestMethod.GET) String delete(@PathVariable("id") Long id, RedirectAttributes attributes); @RequestMapping(value = "/person/search/page", method = RequestMethod.POST) @ResponseBody List<PersonDTO> search(@RequestBody SearchDTO searchCriteria); @RequestMapping(value = "/person/create", method = RequestMethod.GET) String showCreatePersonForm(Model model); @RequestMapping(value = "/person/create", method = RequestMethod.POST) String submitCreatePersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO created, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = "/person/edit/{id}", method = RequestMethod.GET) String showEditPersonForm(@PathVariable("id") Long id, Model model, RedirectAttributes attributes); @RequestMapping(value = "/person/edit", method = RequestMethod.POST) String submitEditPersonForm(@Valid @ModelAttribute(MODEL_ATTIRUTE_PERSON) PersonDTO updated, BindingResult bindingResult, RedirectAttributes attributes); @RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET) String showList(Model model); @RequestMapping(value = "/person/search", method=RequestMethod.POST) String showSearchResultPage(@ModelAttribute(MODEL_ATTRIBUTE_SEARCH_CRITERIA) SearchDTO searchCriteria, Model model); }### Answer: @Test public void showSearchResultPage() { SearchDTO searchCriteria = createSearchDTO(); Model model = new BindingAwareModelMap(); String view = controller.showSearchResultPage(searchCriteria, model); SearchDTO modelAttribute = (SearchDTO) model.asMap().get(PersonController.MODEL_ATTRIBUTE_SEARCH_CRITERIA); assertEquals(searchCriteria.getPageIndex(), modelAttribute.getPageIndex()); assertEquals(searchCriteria.getSearchTerm(), modelAttribute.getSearchTerm()); assertEquals(PersonController.PERSON_SEARCH_RESULT_VIEW, view); }
### Question: AbstractController { protected void addErrorMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("adding error message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String localizedErrorMessage = messageSource.getMessage(code, params, current); LOGGER.debug("Localized message is: " + localizedErrorMessage); model.addFlashAttribute(FLASH_ERROR_MESSAGE, localizedErrorMessage); } }### Answer: @Test public void addErrorMessage() { RedirectAttributes model = new RedirectAttributesModelMap(); Object[] params = new Object[0]; when(messageSourceMock.getMessage(eq(ERROR_MESSAGE_CODE), eq(params), any(Locale.class))).thenReturn(ERROR_MESSAGE); controller.addErrorMessage(model, ERROR_MESSAGE_CODE, params); verify(messageSourceMock, times(1)).getMessage(eq(ERROR_MESSAGE_CODE), eq(params), any(Locale.class)); verifyNoMoreInteractions(messageSourceMock); String errorMessage = (String) model.getFlashAttributes().get(FLASH_ERROR_MESSAGE); assertEquals(ERROR_MESSAGE, errorMessage); }
### Question: AbstractController { protected void addFeedbackMessage(RedirectAttributes model, String code, Object... params) { LOGGER.debug("Adding feedback message with code: " + code + " and params: " + params); Locale current = LocaleContextHolder.getLocale(); LOGGER.debug("Current locale is " + current); String localizedFeedbackMessage = messageSource.getMessage(code, params, current); LOGGER.debug("Localized message is: " + localizedFeedbackMessage); model.addFlashAttribute(FLASH_FEEDBACK_MESSAGE, localizedFeedbackMessage); } }### Answer: @Test public void addFeedbackMessage() { RedirectAttributes model = new RedirectAttributesModelMap(); Object[] params = new Object[0]; when(messageSourceMock.getMessage(eq(FEEDBACK_MESSAGE_CODE), eq(params), any(Locale.class))).thenReturn(FEEDBACK_MESSAGE); controller.addFeedbackMessage(model, FEEDBACK_MESSAGE_CODE, params); verify(messageSourceMock, times(1)).getMessage(eq(FEEDBACK_MESSAGE_CODE), eq(params), any(Locale.class)); verifyNoMoreInteractions(messageSourceMock); String feedbackMessage = (String) model.getFlashAttributes().get(FLASH_FEEDBACK_MESSAGE); assertEquals(FEEDBACK_MESSAGE, feedbackMessage); }
### Question: AbstractController { protected String createRedirectViewPath(String path) { StringBuilder builder = new StringBuilder(); builder.append(VIEW_REDIRECT_PREFIX); builder.append(path); return builder.toString(); } }### Answer: @Test public void createRedirectViewPath() { String redirectView = controller.createRedirectViewPath(REDIRECT_PATH); String expectedView = buildExpectedRedirectViewPath(REDIRECT_PATH); verifyZeroInteractions(messageSourceMock); assertEquals(expectedView, redirectView); }
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findAllPersons() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }### Answer: @Test public void findAllPersons() { repository.findAllPersons(); ArgumentCaptor<Sort> sortArgument = ArgumentCaptor.forClass(Sort.class); verify(personRepositoryMock, times(1)).findAll(sortArgument.capture()); Sort sort = sortArgument.getValue(); assertEquals(Sort.Direction.ASC, sort.getOrderFor(PROPERTY_LASTNAME).getDirection()); }
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public long findPersonCount(String searchTerm) { LOGGER.debug("Finding person count with search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }### Answer: @Test public void findPersonCount() { when(personRepositoryMock.count(any(Predicate.class))).thenReturn(PERSON_COUNT); long actual = repository.findPersonCount(SEARCH_TERM); verify(personRepositoryMock, times(1)).count(any(Predicate.class)); verifyNoMoreInteractions(personRepositoryMock); assertEquals(PERSON_COUNT, actual); }
### Question: PaginatingPersonRepositoryImpl implements PaginatingPersonRepository { @Override public List<Person> findPersonsForPage(String searchTerm, int page) { LOGGER.debug("Finding persons for page " + page + " with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchTerm), constructPageSpecification(page)); return requestedPage.getContent(); } PaginatingPersonRepositoryImpl(); @Override List<Person> findAllPersons(); @Override long findPersonCount(String searchTerm); @Override List<Person> findPersonsForPage(String searchTerm, int page); @PostConstruct void init(); }### Answer: @Test public void findPersonsForPage() { List<Person> expected = new ArrayList<Person>(); Page foundPage = new PageImpl<Person>(expected); when(personRepositoryMock.findAll(any(Predicate.class), any(Pageable.class))).thenReturn(foundPage); List<Person> actual = repository.findPersonsForPage(SEARCH_TERM, PAGE_INDEX); ArgumentCaptor<Pageable> pageSpecificationArgument = ArgumentCaptor.forClass(Pageable.class); verify(personRepositoryMock, times(1)).findAll(any(Predicate.class), pageSpecificationArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Pageable pageSpecification = pageSpecificationArgument.getValue(); assertEquals(PAGE_INDEX, pageSpecification.getPageNumber()); assertEquals(PaginatingPersonRepositoryImpl.NUMBER_OF_PERSONS_PER_PAGE, pageSpecification.getPageSize()); assertEquals(Sort.Direction.ASC, pageSpecification.getSort().getOrderFor(PROPERTY_LASTNAME).getDirection()); assertEquals(expected, actual); }
### Question: PreCondition { public static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments) { isTrue(expression, String.format(errorMessageTemplate, errorMessageArguments)); } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }### Answer: @Test public void isTrueWithDynamicErrorMessage_ExpressionIsTrue_ShouldNotThrowException() { PreCondition.isTrue(true, "Dynamic error message with parameter: %d", 1L); } @Test public void isTrueWithDynamicErrorMessage_ExpressionIsFalse_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.isTrue(false, "Dynamic error message with parameter: %d", 1L)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Dynamic error message with parameter: 1"); } @Test public void isTrueWithStaticErrorMessage_ExpressionIsTrue_ShouldNotThrowException() { PreCondition.isTrue(true, STATIC_ERROR_MESSAGE); } @Test public void isTrueWithStaticErrorMessage_ExpressionIsFalse_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.isTrue(false, STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
### Question: Person { public void update(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }### Answer: @Test public void update() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); built.update(FIRST_NAME_UPDATED, LAST_NAME_UPDATED); assertEquals(FIRST_NAME_UPDATED, built.getFirstName()); assertEquals(LAST_NAME_UPDATED, built.getLastName()); }
### Question: PreCondition { public static void notEmpty(String string, String errorMessage) { if (string.isEmpty()) { throw new IllegalArgumentException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }### Answer: @Test public void notEmpty_StringIsNotEmpty_ShouldNotThrowException() { PreCondition.notEmpty(" ", STATIC_ERROR_MESSAGE); } @Test public void notEmpty_StringIsEmpty_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.notEmpty("", STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
### Question: PreCondition { public static void notNull(Object reference, String errorMessage) { if (reference == null) { throw new NullPointerException(errorMessage); } } private PreCondition(); static void isTrue(boolean expression, String errorMessageTemplate, Object... errorMessageArguments); static void isTrue(boolean expression, String errorMessage); static void notEmpty(String string, String errorMessage); static void notNull(Object reference, String errorMessage); }### Answer: @Test public void notNull_ObjectIsNotNull_ShouldNotThrowException() { PreCondition.notNull(new Object(), STATIC_ERROR_MESSAGE); } @Test public void notNull_ObjectIsNull_ShouldThrowException() { assertThatThrownBy(() -> PreCondition.notNull(null, STATIC_ERROR_MESSAGE)) .isExactlyInstanceOf(NullPointerException.class) .hasMessage(STATIC_ERROR_MESSAGE); }
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.findPersonCount(searchTerm); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void count() { personService.count(SEARCH_TERM); verify(personRepositoryMock, times(1)).findPersonCount(SEARCH_TERM); verifyNoMoreInteractions(personRepositoryMock); }
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public Person create(PersonDTO created) { LOGGER.debug("Creating a new person with information: " + created); Person person = Person.getBuilder(created.getFirstName(), created.getLastName()).build(); return personRepository.save(person); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void create() { PersonDTO created = PersonTestUtil.createDTO(null, FIRST_NAME, LAST_NAME); Person persisted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.save(any(Person.class))).thenReturn(persisted); Person returned = personService.create(created); ArgumentCaptor<Person> personArgument = ArgumentCaptor.forClass(Person.class); verify(personRepositoryMock, times(1)).save(personArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); assertPerson(created, personArgument.getValue()); assertEquals(persisted, returned); }
### Question: RepositoryPersonService implements PersonService { @Transactional(rollbackFor = PersonNotFoundException.class) @Override public Person delete(Long personId) throws PersonNotFoundException { LOGGER.debug("Deleting person with id: " + personId); Person deleted = personRepository.findOne(personId); if (deleted == null) { LOGGER.debug("No person found with id: " + personId); throw new PersonNotFoundException(); } personRepository.delete(deleted); return deleted; } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void delete() throws PersonNotFoundException { Person deleted = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(deleted); Person returned = personService.delete(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verify(personRepositoryMock, times(1)).delete(deleted); verifyNoMoreInteractions(personRepositoryMock); assertEquals(deleted, returned); } @Test(expected = PersonNotFoundException.class) public void deleteWhenPersonIsNotFound() throws PersonNotFoundException { when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(null); personService.delete(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verifyNoMoreInteractions(personRepositoryMock); }
### Question: Person { @Transient public String getName() { StringBuilder name = new StringBuilder(); name.append(firstName); name.append(" "); name.append(lastName); return name.toString(); } Long getId(); static Builder getBuilder(String firstName, String lastName); Date getCreationTime(); String getFirstName(); String getLastName(); @Transient String getName(); Date getModificationTime(); long getVersion(); void update(String firstName, String lastName); @PreUpdate void preUpdate(); @PrePersist void prePersist(); @Override String toString(); void setId(Long id); }### Answer: @Test public void getName() { Person built = Person.getBuilder(FIRST_NAME, LAST_NAME).build(); String expectedName = constructName(FIRST_NAME, LAST_NAME); assertEquals(expectedName, built.getName()); }
### Question: RepositoryPersonService implements PersonService { @Transactional @Override public long count(String searchTerm) { LOGGER.debug("Getting person count for search term: " + searchTerm); return personRepository.count(lastNameIsLike(searchTerm)); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void count() { when(personRepositoryMock.count(any(Specification.class))).thenReturn(PERSON_COUNT); long personCount = personService.count(SEARCH_TERM); verify(personRepositoryMock, times(1)).count(any(Specification.class)); verifyNoMoreInteractions(personRepositoryMock); assertEquals(PERSON_COUNT, personCount); }
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAll(sortByLastNameAsc()); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void findAll() { List<Person> persons = new ArrayList<Person>(); when(personRepositoryMock.findAll(any(Sort.class))).thenReturn(persons); List<Person> returned = personService.findAll(); ArgumentCaptor<Sort> sortArgument = ArgumentCaptor.forClass(Sort.class); verify(personRepositoryMock, times(1)).findAll(sortArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Sort actualSort = sortArgument.getValue(); assertEquals(Sort.Direction.ASC, actualSort.getOrderFor("lastName").getDirection()); assertEquals(persons, returned); }
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> search(String searchTerm, int pageIndex) { LOGGER.debug("Searching persons with search term: " + searchTerm); Page requestedPage = personRepository.findAll(lastNameIsLike(searchTerm), constructPageSpecification(pageIndex)); return requestedPage.getContent(); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void search() { List<Person> expected = new ArrayList<Person>(); Page expectedPage = new PageImpl(expected); when(personRepositoryMock.findAll(any(Specification.class), any(Pageable.class))).thenReturn(expectedPage); List<Person> actual = personService.search(SEARCH_TERM, PAGE_INDEX); ArgumentCaptor<Pageable> pageArgument = ArgumentCaptor.forClass(Pageable.class); verify(personRepositoryMock, times(1)).findAll(any(Specification.class), pageArgument.capture()); verifyNoMoreInteractions(personRepositoryMock); Pageable pageSpecification = pageArgument.getValue(); assertEquals(PAGE_INDEX, pageSpecification.getPageNumber()); assertEquals(RepositoryPersonService.NUMBER_OF_PERSONS_PER_PAGE, pageSpecification.getPageSize()); assertEquals(Sort.Direction.ASC, pageSpecification.getSort().getOrderFor("lastName").getDirection()); assertEquals(expected, actual); }
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public List<Person> findAll() { LOGGER.debug("Finding all persons"); return personRepository.findAllPersons(); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void findAll() { List<Person> persons = new ArrayList<Person>(); when(personRepositoryMock.findAllPersons()).thenReturn(persons); List<Person> returned = personService.findAll(); verify(personRepositoryMock, times(1)).findAllPersons(); verifyNoMoreInteractions(personRepositoryMock); assertEquals(persons, returned); }
### Question: RepositoryPersonService implements PersonService { @Transactional(readOnly = true) @Override public Person findById(Long id) { LOGGER.debug("Finding person by id: " + id); return personRepository.findOne(id); } @Transactional @Override Person create(PersonDTO created); @Transactional @Override long count(String searchTerm); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person delete(Long personId); @Transactional(readOnly = true) @Override List<Person> findAll(); @Transactional(readOnly = true) @Override Person findById(Long id); @Transactional(readOnly = true) @Override List<Person> search(String searchTerm, int pageIndex); @Transactional(rollbackFor = PersonNotFoundException.class) @Override Person update(PersonDTO updated); }### Answer: @Test public void findById() { Person person = PersonTestUtil.createModelObject(PERSON_ID, FIRST_NAME, LAST_NAME); when(personRepositoryMock.findOne(PERSON_ID)).thenReturn(person); Person returned = personService.findById(PERSON_ID); verify(personRepositoryMock, times(1)).findOne(PERSON_ID); verifyNoMoreInteractions(personRepositoryMock); assertEquals(person, returned); }
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void registerUser(User user, String plainPassword) { entryptPassword(user, plainPassword); generateActKey(user); user.setRoles("user"); user.setRegisterDate(Calendar.getInstance().getTime()); user.setNiceName(user.getLoginName()); user.setStatusCode(UserStatus.Pending.code()); user.setCreatedBy(user.getLoginName()); user.setCreatedWhen(Calendar.getInstance().getTime()); userRepository.save(user); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }### Answer: @Test public void registerUser() { User user = UserData.randomNewUser(); userService.registerUser(user, UserData.randomPassword()); assertEquals("user", user.getRoles()); assertNotNull(user.getPassword()); assertNotNull(user.getSalt()); }
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void updateUser(User user, String plainPassword) { if (StringUtils.isNotBlank(plainPassword)) { entryptPassword(user, plainPassword); } userRepository.save(user); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }### Answer: @Test public void updateUser() { User user = UserData.randomNewUser(); userService.updateUser(user, UserData.randomPassword()); assertNotNull(user.getSalt()); User user2 = UserData.randomNewUser(); userService.updateUser(user2, null); assertNull(user2.getSalt()); }
### Question: UserService extends BaseService { @Transactional(readOnly = false) public void deleteUser(Long id) { if (isSupervisor(id)) { logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName()); throw new ServiceException("不能删除超级管理员用户"); } userRepository.delete(id); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }### Answer: @Test public void deleteUser() { userService.deleteUser(2L); Mockito.verify(mockUserDao).delete(2L); try { userService.deleteUser(1L); fail("expected ServicExcepton not be thrown"); } catch (ServiceException e) { } Mockito.verify(mockUserDao, Mockito.never()).delete(1L); }
### Question: UserService extends BaseService { void entryptPassword(User user, String plainPassword) { byte[] salt = Digests.generateSalt(SALT_SIZE); user.setSalt(Encodes.encodeHex(salt)); byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS); user.setPassword(Encodes.encodeHex(hashPassword)); } User getUser(Long id); User findUserByLoginName(String loginName); User findUserByEmail(String email); @Transactional(readOnly = false) void registerUser(User user, String plainPassword); @Transactional(readOnly = false) void createUser(User user, String plainPassword); @Transactional(readOnly = false) void updateUser(User user, String plainPassword); @Transactional(readOnly = false) void updatePassword(User user, String plainPassword); @Transactional(readOnly = false) void deleteUser(Long id); @Transactional(readOnly = false) void activeUser(Long id); @Transactional(readOnly = false) void deactiveUser(Long id); Page<User> getUsers(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType); @Transactional(readOnly = false) void activeUser(String key); void sendResetPwdEmail(User user); @Transactional(readOnly = false) void resetPassword(String key); static final String HASH_ALGORITHM; static final int HASH_INTERATIONS; }### Answer: @Test public void entryptPassword() { User user = UserData.randomNewUser(); userService.entryptPassword(user, "admin"); System.out.println(user.getLoginName()); System.out.println("salt: " + user.getSalt()); System.out.println("entrypt password: " + user.getPassword()); }
### Question: MD5DigestCalculatingInputStream extends SdkFilterInputStream { @Override public boolean markSupported() { return super.markSupported() && digestCanBeCloned; } MD5DigestCalculatingInputStream(InputStream in); @Override boolean markSupported(); byte[] getMd5Digest(); @Override void mark(int readlimit); @Override void reset(); @Override int read(); @Override int read(byte[] b, int off, int len); }### Answer: @Test public void testMD5CloneSupportedTrue() throws Exception { InputStream in = mock(InputStream.class); doReturn(true).when(in).markSupported();; MD5DigestCalculatingInputStream md5Digest = new MD5DigestCalculatingInputStream(in); assertTrue(md5Digest.markSupported()); } @Test public void testMD5CloneSupportedFalse() throws Exception { InputStream in = mock(InputStream.class); doReturn(false).when(in).markSupported();; MD5DigestCalculatingInputStream md5Digest = new MD5DigestCalculatingInputStream(in); assertFalse(md5Digest.markSupported()); }
### Question: StringUtils { public static String fromByteBuffer(ByteBuffer byteBuffer) { return Base64.encodeAsString(copyBytesFrom(byteBuffer)); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }### Answer: @Test public void testFromByteBuffer() { String expectedData = "hello world"; String expectedEncodedData = "aGVsbG8gd29ybGQ="; ByteBuffer byteBuffer = ByteBuffer.wrap(expectedData.getBytes()); String encodedData = StringUtils.fromByteBuffer(byteBuffer); assertEquals(expectedEncodedData, encodedData); }
### Question: StringUtils { public static String fromByte(Byte b) { return Byte.toString(b); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }### Answer: @Test public void testFromByte() { assertEquals("123", StringUtils.fromByte(new Byte("123"))); assertEquals("-99", StringUtils.fromByte(new Byte("-99"))); }
### Question: StringUtils { public static String replace( String originalString, String partToMatch, String replacement ) { StringBuilder buffer = new StringBuilder( originalString.length() ); buffer.append( originalString ); int indexOf = buffer.indexOf( partToMatch ); while (indexOf != -1) { buffer = buffer.replace(indexOf, indexOf + partToMatch.length(), replacement); indexOf = buffer.indexOf(partToMatch, indexOf + replacement.length()); } return buffer.toString(); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }### Answer: @Test(timeout = 10 * 1000) public void replace_ReplacementStringContainsMatchString_DoesNotCauseInfiniteLoop() { assertEquals("aabc", StringUtils.replace("abc", "a", "aa")); } @Test public void replace_EmptyReplacementString_RemovesAllOccurencesOfMatchString() { assertEquals("bbb", StringUtils.replace("ababab", "a", "")); } @Test public void replace_MatchNotFound_ReturnsOriginalString() { assertEquals("abc", StringUtils.replace("abc", "d", "e")); }
### Question: StringUtils { public static String lowerCase(String str) { if(isNullOrEmpty(str)) { return str; } return str.toLowerCase(LOCALE_ENGLISH); } static Integer toInteger(StringBuilder value); static String toString(StringBuilder value); static Boolean toBoolean(StringBuilder value); static String fromInteger(Integer value); static String fromLong(Long value); static String fromString(String value); static String fromBoolean(Boolean value); static String fromBigInteger(BigInteger value); static String fromBigDecimal(BigDecimal value); static BigInteger toBigInteger(String s); static BigDecimal toBigDecimal(String s); static String fromFloat(Float value); static String fromDate(Date value); static String fromDouble(Double d); static String fromByte(Byte b); static String fromByteBuffer(ByteBuffer byteBuffer); static String replace( String originalString, String partToMatch, String replacement ); static String join(String joiner, String... parts); static String trim(String value); static boolean isNullOrEmpty(String value); static boolean hasValue(String str); static String lowerCase(String str); static String upperCase(String str); static int compare(String str1, String str2); static void appendCompactedString(final StringBuilder destination, final String source); static boolean beginsWithIgnoreCase(final String data, final String seq); static Character findFirstOccurrence(String s, char ...charsToMatch); static final String COMMA_SEPARATOR; static final Charset UTF8; }### Answer: @Test public void lowerCase_NonEmptyString() { String input = "x-amz-InvocAtion-typE"; String expected = "x-amz-invocation-type"; assertEquals(expected, StringUtils.lowerCase(input)); } @Test public void lowerCase_NullString() { assertNull(StringUtils.lowerCase(null)); } @Test public void lowerCase_EmptyString() { Assert.assertThat(StringUtils.lowerCase(""), Matchers.isEmptyString()); }