src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
FullTextSearch { public SearchTree search(SearchRequest searchRequest) { if(!searchAdapter.isEngineRunning()) { throw new SearchEngineNotRunningException(); } SearchResults searchResults; try { searchResults = searchAdapter.searchData(searchRequest); } catch (Throwable t) { throw new SearchFailedException(t); } return ... | @Test void searchWithoutRunningEngine() { givenNoRunningEngine(); assertThrows(SearchEngineNotRunningException.class, ()->fullTextSearch.search(new SearchRequest(new BuildIdentifier("testBranch", "testBuild"), "hi", true))); }
@Test void searchWithNoResults() { givenRunningEngineWithSearchResults(); SearchTree result =... |
FullTextSearch { public void updateAvailableBuilds(final List<BuildImportSummary> availableBuilds) { if(!searchAdapter.isEngineRunning()) { return; } List<BuildIdentifier> existingBuilds = getAvailableBuildIdentifiers(availableBuilds); searchAdapter.updateAvailableBuilds(existingBuilds); LOGGER.info("Updated available ... | @Test void updateAvailableBuildsWithoutRunningEngine() { givenNoRunningEngine(); fullTextSearch.updateAvailableBuilds(Collections.emptyList()); thenJustReturns(); } |
SearchTree { public ObjectTreeNode<ObjectReference> getResults() { return results; } SearchTree(SearchResults searchResults, SearchRequest searchRequest); static SearchTree empty(); ObjectTreeNode<ObjectReference> getResults(); long getHits(); long getTotalHits(); SearchRequest getSearchRequest(); } | @Test void treeWithASingleStep() { SearchTree searchTree = givenSearchTreeWithSingleStep(); ObjectTreeNode<ObjectReference> objectTree = searchTree.getResults(); thenHasNodes(objectTree, "Use Case 1", "Scenario 1", "Page 1/3/2"); } |
ScenariooValidator { public boolean validate() throws InterruptedException { cleanDerivedFilesIfRequested(); Map<BuildIdentifier, BuildImportSummary> buildImportSummaries = validationBuildImporter.importBuildsAndWaitForExecutor(); return evaluateSummaries(buildImportSummaries); } ScenariooValidator(File docuDirectory, ... | @Test void validation_successful_with_own_example_docu(@TempDir File testDirectory) throws InterruptedException, IOException { File docuDirectory = new File("../scenarioo-docu-generation-example/src/test/resources/example/documentation/scenarioDocuExample"); FileUtils.copyDirectory(docuDirectory, testDirectory); boolea... |
StepIdentifier { @JsonIgnore public URI getScreenshotUriForRedirect(final String screenshotFileNameExtension) { return createUriForRedirect(RedirectType.SCREENSHOT, screenshotFileNameExtension); } StepIdentifier(); StepIdentifier(final BuildIdentifier buildIdentifier, final String usecaseName, final String scenarioNam... | @Test public void redirectUrlForScreenshot() { assertEquals( "/scenarioo/rest/branch/bugfix-branch/build/build-2014-08-12/usecase/Find the answer/scenario/Actually find it/pageName/pageName1/pageOccurrence/0/stepInPageOccurrence/0/image.jpeg", stepIdentifier.getScreenshotUriForRedirect("jpeg").getPath()); assertEquals(... |
DateUtil { public static boolean isDate(String date) { return isDate(date, PATTERN_HAVE_TIME); } static boolean isDate(String date); static boolean isDate(String date, String pattern); static String format(Date date); static String formatTime(Date date); static String format(Date date, String pattern); static String g... | @Test void isDate() { System.out.println(DateUtil.isDate("2018-02-29", "yyyy-MM-dd")); } |
ModeParser { static void parseOne(final String instruction, final Set<PosixFilePermission> toAdd, final Set<PosixFilePermission> toRemove) { final int plus = instruction.indexOf('+'); final int minus = instruction.indexOf('-'); if (plus < 0 && minus < 0) { throw new RuntimeException("Invalid unix mode expresson: '" + i... | @Test @UseDataProvider(value = "invalidModeInstructions") public void invalidModeInstructionThrowsAppropriateException(final String instruction) { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<PosixFilePermission> toRemove = EnumSet.noneOf(PosixFilePermission.class); try { ... |
ModeParser { static void parse(final String instructions, final Set<PosixFilePermission> toAdd, final Set<PosixFilePermission> toRemove) { for (final String instruction : COMMA.split(instructions)) { parseOne(instruction, toAdd, toRemove); } } private ModeParser(); static PermissionsSet buildPermissionsSet(final Strin... | @Test @UseDataProvider("multipleInstructions") public void validModeMultipleInstructionAddsInstructionsInAppropriateSets( final String instruction, final Set<PosixFilePermission> add, final Set<PosixFilePermission> remove) { final Set<PosixFilePermission> toAdd = EnumSet.noneOf(PosixFilePermission.class); final Set<Pos... |
PosixModes { public static Set<PosixFilePermission> intModeToPosix(int intMode) { if ((intMode & INT_MODE_MAX) != intMode) { throw new RuntimeException("Invalid intMode: " + intMode); } final Set<PosixFilePermission> set = EnumSet.noneOf(PosixFilePermission.class); for (int i = 0; i < PERMISSIONS_LENGTH; i++) { if ((in... | @Test(expected = RuntimeException.class) public void outOfRangeNumberThrowsIllegalArgumentException() { try { PosixModes.intModeToPosix(-1); shouldHaveThrown(IllegalArgumentException.class); } catch (IllegalArgumentException e) { assertThat(e).isExactlyInstanceOf(RuntimeException.class); } try { PosixModes.intModeToPos... |
ProvisioUtils { public static String coordinateToPath(ProvisioArtifact a) { StringBuffer path = new StringBuffer() .append(a.getArtifactId()) .append("-") .append(a.getVersion()); if (a.getClassifier() != null && !a.getClassifier().isEmpty()) { path.append("-") .append(a.getClassifier()); } path.append(".") .append(a.g... | @Test public void validateCoordinateToPath() { ProvisioArtifact artifact = new ProvisioArtifact("io.prestosql:presto-main:332"); String path = coordinateToPath(artifact); assertEquals("presto-main-332.jar", path); } |
ParametricPlane { public Vector getDirectionY() { return directionY; } ParametricPlane(Point3D basePoint, Vector directionX,
Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPla... | @Test public void directionY() { ParametricPlane p = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Vector y = p.getDirectionY(); assertEquals(0.0, y.getX(), DELTA); assertEquals(1.0, y.getY(), DELTA); assertEquals(0.0, y.getZ(), DELTA); }
@Test public void directionX() { Parametr... |
ParametricPlane { public Point3D getPoint(double x, double y) { Point3D p = new Point3D(); p.setX(this.base.getX() + (this.directionX.getX() * x) + (this.directionY.getX() * y)); p.setY(this.base.getY() + (this.directionX.getY() * x) + (this.directionY.getY() * y)); p.setZ(this.base.getZ() + (this.directionX.getZ() * x... | @Test public void point1() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = plane.getPoint(2.0, 3.0); assertEquals(2.0, p.getX(), DELTA); assertEquals(3.0, p.getY(), DELTA); assertEquals(0.0, p.getZ(), DELTA); } |
ParametricPlane { public double[] getParameter(Point3D p) { double u = 0.0; double v = (this.directionX.getY() * this.directionY.getX()) - (this.directionX.getX() * this.directionY.getY()); if (v != 0.0) { v = ((p.getY() * this.directionY.getX()) - (this.base.getY() * this.directionY.getX()) - (this.directionY.getY() *... | @Test public void parameters() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = new Point3D(2.0, 3.0, 0.0); double[] paras = plane.getParameter(p); assertEquals(2.0, paras[0], DELTA); assertEquals(3.0, paras[1], DELTA); } |
ParametricPlane { public boolean isOnPlane(Point3D p) { double[] para = this.getParameter(p); double v = this.base.getZ() + (this.directionX.getZ() * para[0]) + (this.directionY.getZ() * para[1]); if (!(Math.abs((p.getZ() - v)) < MathUtils.DISTANCE_DELTA)) { return false; } v = this.base.getY() + (this.directionX.getY(... | @Test public void isOnPlane() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Vector(0, 0, 1)); Point3D p = new Point3D(2.0, 3.0, 0.0); assertTrue(plane.isOnPlane(p)); }
@Test public void isNotPlane() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new P... |
ParametricPlane { public Vector getNormal() { return normal; } ParametricPlane(Point3D basePoint, Vector directionX,
Vector directionY, Vector normal); ParametricPlane(Point3D basePoint, Vector directionX, Vector directionY); ParametricPlane(Point3D basePoint, Point3D b, Vector normal); ParametricPlane(Point... | @Test public void normal() { ParametricPlane plane = new ParametricPlane(new Point3D(0, 0, 0), new Point3D(1, 0, 0), new Point3D(1.0, DELTA, 0)); Vector n = plane.getNormal(); assertEquals(0.0, n.getX(), DELTA); assertEquals(0.0, n.getY(), DELTA); assertEquals(1.0, n.getZ(), DELTA); } |
NURBS { public double[] getBasicFunctions(int i, double u) { double[] n = new double[degree + 1]; n[0] = 1.0; double[] left = new double[degree + 1]; double[] right = new double[degree + 1]; for (int j = 1; j <= degree; j++) { left[j] = u - this.knots[(i + 1) - j]; right[j] = this.knots[i + j] - u; double saved = 0.0; ... | @Test public void baseFunctions1() { Point3D[] points = new Point3D[]{}; double[] knots = new double[]{0, 0, 0, 1, 2, 3, 4, 4, 5, 5}; double[] w = new double[]{}; NURBS n = new NURBS(points, knots, w, 2); double[] bf = n.getBasicFunctions(4, 2.5); assertEquals(3, bf.length); assertEquals(1.0 / 8.0, bf[0], DELTA); asser... |
ExportServer { public static void init(String[] args) throws Exception { Map<String, BiConsumer<ChannelHandlerContext, HttpRequest>> mapping = new HashMap<>(); mapping.put(HEALTH, (channelHandlerContext, request) -> { ExportResult result = SyncerHealth.export(); String json = result.getJson(); Health.HealthStatus overa... | @Test public void init() throws UnknownHostException, InterruptedException { HttpConnection connection = new HttpConnection(); connection.setAddress("localhost"); connection.setPort(PORT); connection.setPath(ExportServer.HEALTH); NettyHttpClient nettyClient = new NettyHttpClient(connection, new HttpClientInitializer())... |
BinlogDataId implements DataId { public String eventId() { return new StringBuilder(COMMON_LEN) .append(binlogFileName).append(SEP) .append(tableMapPos).append(SEP) .append(dataPos - tableMapPos) .toString(); } BinlogDataId(String binlogFileName, long tableMapPos, long dataPos); BinlogDataId setOrdinal(int ordinal); Bi... | @Test public void eventId() { } |
BinlogDataId implements DataId { public String dataId() { StringBuilder append = new StringBuilder(COMMON_LEN).append(eventId()).append(SEP).append(ordinal); if (offset != null) { return append.append(SEP).append(offset).toString(); } else { return append.toString(); } } BinlogDataId(String binlogFileName, long tableMa... | @Test public void dataId() { } |
BinlogDataId implements DataId { @Override public int compareTo(DataId dataId) { BinlogDataId o = (BinlogDataId) dataId; int cmp = getSyncInitMeta().compareTo(o.getSyncInitMeta()); if (cmp != 0) { return cmp; } cmp = Long.compare(tableMapPos, o.tableMapPos); if (cmp != 0) { return cmp; } cmp = Long.compare(dataPos, o.d... | @Test public void compareTo() { BinlogDataId _0 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(0).setOffset(null); BinlogDataId _00 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(0).setOffset(0); BinlogDataId _1 = new BinlogDataId("mysql-bin.000117", 4, 40).setOrdinal(1).setOffset(null); BinlogDataI... |
SyncData implements com.github.zzt93.syncer.data.SyncData, Serializable { public void recycleParseContext(ThreadLocal<StandardEvaluationContext> contexts) { inner.context = null; } SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName,
Object id, NamedChan... | @Test public void testToStringDefault() { SyncData write = SyncDataTestUtil.write("test", "test"); assertEquals("SyncData(inner=Meta{dataId=mysql-bin.00001/4/6/0, context=true, connectionIdentifier='null'}, syncByQuery=null, esScriptUpdate=null, result=SyncResult(super=SyncResultBase(super=SyncMeta(eventType=WRITE, rep... |
SyncData implements com.github.zzt93.syncer.data.SyncData, Serializable { @Override public boolean updated() { return updated != null; } SyncData(DataId dataId, SimpleEventType type, String database, String entity, String primaryKeyName,
Object id, NamedChange row); private SyncData(DataId dataId, Si... | @Test public void testUpdated() { HashMap<String, Object> before = new HashMap<>(); before.put("1", 1); before.put("2", "22"); before.put("3", "33".getBytes()); before.put("4", 4L); before.put("5", new Timestamp(System.currentTimeMillis())); before.put("6", "中文".getBytes(StandardCharsets.UTF_8)); before.put("7", "中文".g... |
SQLHelper { public static AlterMeta alterMeta(String database, String sql) { String alterTarget = isAlter(sql); if (alterTarget != null) { alterTarget = alterTarget.replaceAll("`|\\s", ""); if (!StringUtils.isEmpty(database)) { return new AlterMeta(database, alterTarget); } String[] split = alterTarget.split("\\."); as... | @Test public void alterMeta() { AlterMeta test = SQLHelper.alterMeta(TEST, "alter table xx add yy int null after zz"); assertNotNull(test); assertEquals("", TEST, test.getSchema()); assertEquals("", XX, test.getTable()); test = SQLHelper.alterMeta("", "alter table test.xx add yy int null after zz"); assertNotNull(test)... |
RegexUtil { public static Pattern env() { return env; } static Pattern getRegex(String input); static Pattern env(); static boolean isClassName(String consumerId); } | @Test public void env() throws Exception { Pattern env = RegexUtil.env(); Matcher m1 = env.matcher(" - name: \"menkor_${ACTIVE_PROFILE}.*\""); Assert.assertTrue(m1.find()); String group0 = m1.group(0); String group1 = m1.group(1); Assert.assertEquals("", "${ACTIVE_PROFILE}", group0); Assert.assertEquals("", "ACTIVE_PRO... |
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(S... | @Test public void getRegex() throws Exception { Pattern simple = RegexUtil.getRegex("simple"); Assert.assertNull(simple); Pattern star = RegexUtil.getRegex("dev.*"); Assert.assertNotNull(star); } |
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" + "impor... | @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)); } |
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); ... | @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.... |
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(); } | @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\... |
ESRequestMapper implements Mapper<SyncData, Object> { @ThreadSafe(safe = {SpelExpressionParser.class, ESRequestMapping.class, TransportClient.class}) @Override public Object map(SyncData data) { esQueryMapper.parseExtraQueryContext(data.getExtraQueryContext()); StandardEvaluationContext context = data.getContext(); Str... | @Test public void nestedWithExtraQuery() throws Exception { AbstractClient client = ElasticTestUtil.getDevClient(); Elasticsearch elasticsearch = new Elasticsearch(); ESRequestMapper mapper = new ESRequestMapper(client, elasticsearch.getRequestMapping()); SyncData data = SyncDataTestUtil.update("role", "role").setId(12... |
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 (Stri... | @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 ... |
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 ... | @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 BsonTim... |
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... | @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", ... |
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 binlogFilen... | @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"); } |
WadlZipper { public void saveTo(String zipPathName) throws IOException, URISyntaxException { saveTo(new File(zipPathName)); } WadlZipper(String wadlUri); void saveTo(String zipPathName); void saveTo(File zipFile); } | @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... |
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(); } } Si... | @Test public void givenClassWhichAttributeIsAnInterface_whenBuild_thenReturnSchemaWithTheInterface() { assertThat(new SingleType(ContactWhichAttributeIsAnInterface.class, IGNORED_Q_NAME).toSchema(), is(ContactWhichAttributeIsAnInterface.EXPECTED_SCHEMA)); }
@Test public void givenNameOfNonAnnotatedJaxbClass_whenBuild_t... |
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); } | @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_thenR... |
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); } | @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)); as... |
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; } p... | @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(typeCompat... |
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 me... | @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 MethodCont... |
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 di... | @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... |
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); } | @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)); } assertT... |
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; } ... | @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() {... |
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.getLocalPa... | @Test public void givenNameOfComplexTypeCollection_whenBuild_thenReturnSchemaWithTheCollection() { assertThat(new CollectionType(ContactAnnotated[].class, new QName("contactAnnotatedCollection"), new QName("contactAnnotated")).toSchema(), is(ContactAnnotated.EXPECTED_COLLECTION_SCHEMA)); } |
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); ClassT... | @Test(expected = ClassTypeNotFoundException.class) public void givenNonExistingLocalPart_whenFind_thenThrowException() { classTypeDiscoverer.getBy("nonExistingLocalPart"); } |
SchemaBuilder { public String buildFor(final String localPart) { return classTypeDiscoverer.getBy(localPart).toSchema(); } SchemaBuilder(ClassTypeDiscoverer classTypeDiscoverer); String buildFor(final String localPart); } | @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("dummyLocalPar... |
GeoRelationQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } void setRelation(String relation); String getRelation(); void setFunctionParent(QueryModelNode functionParent); void setQueryGeometry(Literal shape); Literal getQueryGeometry(); void... | @Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"matchUri\"\n" + " ProjectionElem \"match\"\n" + " BindingSetAssignment ([[toUri=urn:subject4;to=\"POLYGON ((2.3294 48.8726, 2.2719 48.8643, 2.3370 48.8398, 2.3... |
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 =... | @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.createLiter... |
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 =... | @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.createLiter... |
StrBefore implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("Incorrect number of arguments for STRBEFORE: " + args.length); } Value leftArg = args[0]; Value rightArg = arg... | @Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strBeforeFunc.evaluate(f, leftArg, rightArg); assertEquals("foo", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExp... |
HashFunction implements Function { @Override public abstract Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException; @Override abstract Literal evaluate(ValueFactory valueFactory, Value... args); } | @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.getMess... |
StringCast extends CastFunction { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 1) { throw new ValueExprEvaluationException( getXsdName() + " cast requires exactly 1 argument, got " + args.length); } if (args[0] instanceof Literal) {... | @Test public void testCastPlainLiteral() { Literal plainLit = f.createLiteral("foo"); try { Literal result = stringCast.evaluate(f, plainLit); assertNotNull(result); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprEvaluationException e) { fail(e.getMessage()); } }
@Test public void testCastInteg... |
StrictEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient, UUIDable { @Override public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(TupleExpr expr, BindingSet bindings) throws QueryEvaluationException { if (expr instanceof StatementPattern) { return evaluate((StatementP... | @Test public void testBindings() throws Exception { String query = "SELECT ?a ?b WHERE {}"; ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null); final ValueFactory vf = SimpleValueFactory.getInstance(); QueryBindingSet constants = new QueryBindingSet(); constants.addBinding("a", vf.createLite... |
StrictEvaluationStrategy implements EvaluationStrategy, FederatedServiceResolverClient, UUIDable { @Override public TupleExpr optimize(TupleExpr expr, EvaluationStatistics evaluationStatistics, BindingSet bindings) { TupleExpr optimizedExpr = expr; for (QueryOptimizer optimizer : pipeline.getOptimizers()) { optimizer.o... | @Test public void testOptimize() throws Exception { QueryOptimizer optimizer1 = mock(QueryOptimizer.class); QueryOptimizer optimizer2 = mock(QueryOptimizer.class); strategy.setOptimizerPipeline(new QueryOptimizerPipeline() { @Override public Iterable<QueryOptimizer> getOptimizers() { return Arrays.asList(optimizer1, op... |
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.replaceWi... | @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 testNormalizeUnion... |
ShaclSailConfig extends AbstractDelegatingSailImplConfig { @Override public void parse(Model m, Resource implNode) throws SailConfigException { super.parse(m, implNode); try { Models.objectLiteral(m.filter(implNode, PARALLEL_VALIDATION, null)) .ifPresent(l -> setParallelValidation(l.booleanValue())); Models.objectLiter... | @Test(expected = SailConfigException.class) public void parseInvalidModelGivesCorrectException() { mb.add(PARALLEL_VALIDATION, "I'm not a boolean"); subject.parse(mb.build(), implNode); } |
ShaclSailConfig extends AbstractDelegatingSailImplConfig { @Override public Resource export(Model m) { Resource implNode = super.export(m); m.setNamespace("sail-shacl", NAMESPACE); m.add(implNode, PARALLEL_VALIDATION, BooleanLiteral.valueOf(isParallelValidation())); m.add(implNode, UNDEFINED_TARGET_VALIDATES_ALL_SUBJEC... | @Test public void exportAddsAllConfigData() { Model m = new TreeModel(); Resource node = subject.export(m); assertThat(m.contains(node, PARALLEL_VALIDATION, null)).isTrue(); assertThat(m.contains(node, UNDEFINED_TARGET_VALIDATES_ALL_SUBJECTS, null)).isTrue(); assertThat(m.contains(node, LOG_VALIDATION_PLANS, null)).isT... |
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; } | @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); } |
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) { Sha... | @Test public void getSailWithDefaultConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSailConfig(); ShaclSail sail = (ShaclSail) subject.getSail(config); assertMatchesConfig(sail, config); }
@Test public void getSailWithCustomConfigSetsConfigurationCorrectly() { ShaclSailConfig config = new ShaclSa... |
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.getSpa... | @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", X... |
ProxyRepository extends AbstractRepository implements RepositoryResolverClient { @Override public RepositoryConnection getConnection() throws RepositoryException { return getProxiedRepository().getConnection(); } ProxyRepository(); ProxyRepository(String proxiedIdentity); ProxyRepository(RepositoryResolver resolver, ... | @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"), "htt... |
SPARQLUpdateDataBlockParser extends TriGParser { @Override protected void parseGraph() throws RDFParseException, RDFHandlerException, IOException { super.parseGraph(); skipOptionalPeriod(); } SPARQLUpdateDataBlockParser(); SPARQLUpdateDataBlockParser(ValueFactory valueFactory); @Override RDFFormat getRDFFormat(); bool... | @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 (Stri... |
ProxyRepositoryFactory implements RepositoryFactory { @Override public Repository getRepository(RepositoryImplConfig config) throws RepositoryConfigException { ProxyRepository result = null; if (config instanceof ProxyRepositoryConfig) { result = new ProxyRepository(((ProxyRepositoryConfig) config).getProxiedRepository... | @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, Repository... |
OrderComparator implements Comparator<BindingSet>, Serializable { @Override public int compare(BindingSet o1, BindingSet o2) { try { for (OrderElem element : order.getElements()) { Value v1 = evaluate(element.getExpr(), o1); Value v2 = evaluate(element.getExpr(), o2); int compare = cmp.compare(v1, v2); if (compare != 0... | @Test public void testEquals() throws Exception { order.addElement(asc); cmp.setIterator(Arrays.asList(ZERO).iterator()); OrderComparator sud = new OrderComparator(strategy, order, cmp); assertTrue(sud.compare(null, null) == 0); }
@Test public void testZero() throws Exception { order.addElement(asc); order.addElement(a... |
QuerySpecBuilder implements SearchQueryInterpreter { @SuppressWarnings("unchecked") @Deprecated public Set<QuerySpec> process(TupleExpr tupleExpr, BindingSet bindings) throws SailException { HashSet<QuerySpec> result = new HashSet<>(); process(tupleExpr, bindings, (Collection<SearchQueryEvaluator>) (Collection<?>) resu... | @Test public void testMultipleQueriesInterpretation() throws Exception { StringBuilder buffer = new StringBuilder(); buffer.append("SELECT sub1, score1, snippet1, sub2, score2, snippet2, x, p1, p2 "); buffer.append("FROM {sub1} <" + MATCHES + "> {} "); buffer.append("<" + TYPE + "> {<" + LUCENE_QUERY + ">}; "); buffer.... |
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)... | @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 testBothBno... |
DistanceQuerySpec extends AbstractSearchQueryEvaluator { @Override public QueryModelNode getParentQueryModelNode() { return filter; } DistanceQuerySpec(FunctionCall distanceFunction, ValueExpr distanceExpr, String distVar, Filter filter); DistanceQuerySpec(Literal from, IRI units, double dist, String distVar, IRI geoP... | @Test public void testReplaceQueryPatternsWithNonEmptyResults() { final String expectedQueryPlan = "Projection\n" + " ProjectionElemList\n" + " ProjectionElem \"toUri\"\n" + " ProjectionElem \"to\"\n" + " BindingSetAssignment ([[toUri=urn:subject1;to=\"POINT (2.2945 48.8582)\"^^<http: final ParsedQuery query = parseQue... |
XMLDatatypeMathUtil { public static Literal compute(Literal leftLit, Literal rightLit, MathOp op) throws ValueExprEvaluationException { IRI leftDatatype = leftLit.getDatatype(); IRI rightDatatype = rightLit.getDatatype(); if (XMLDatatypeUtil.isNumericDatatype(leftDatatype) && XMLDatatypeUtil.isNumericDatatype(rightData... | @Test public void testCompute() throws Exception { Literal float1 = vf.createLiteral("12", XMLSchema.INTEGER); Literal float2 = vf.createLiteral("2", XMLSchema.INTEGER); Literal duration1 = vf.createLiteral("P1Y1M", XMLSchema.YEARMONTHDURATION); Literal duration2 = vf.createLiteral("P1Y", XMLSchema.YEARMONTHDURATION); ... |
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 = rand... | @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.printStackTrac... |
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 = (Li... | @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 (ValueExprEvaluationEx... |
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 ... | @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.printStack... |
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... | @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) ... |
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)... | @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()); } Resou... |
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(); S... | @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() {... |
StrAfter implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length != 2) { throw new ValueExprEvaluationException("Incorrect number of arguments for STRAFTER: " + args.length); } Value leftArg = args[0]; Value rightArg = args[... | @Test public void testEvaluate4() { Literal leftArg = f.createLiteral("foobar", XMLSchema.STRING); Literal rightArg = f.createLiteral("b"); try { Literal result = strAfterFunc.evaluate(f, leftArg, rightArg); assertEquals("ar", result.getLabel()); assertEquals(XMLSchema.STRING, result.getDatatype()); } catch (ValueExprE... |
Substring implements Function { @Override public Literal evaluate(ValueFactory valueFactory, Value... args) throws ValueExprEvaluationException { if (args.length < 2 || args.length > 3) { throw new ValueExprEvaluationException("Incorrect number of arguments for SUBSTR: " + args.length); } Value argValue = args[0]; Valu... | @Test public void testEvaluateStartBefore1() { Literal pattern = f.createLiteral("ABC"); Literal startIndex = f.createLiteral(0); Literal length = f.createLiteral(1); try { Literal result = substrFunc.evaluate(f, pattern, startIndex, length); assertTrue(result.getLabel().equals("")); } catch (ValueExprEvaluationExcepti... |
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(repo... | @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); assertTr... |
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 report... | @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()); }
@Tes... |
Federate extends ConsoleCommand { @Override public void execute(String... parameters) throws IOException { if (parameters.length < 4) { consoleIO.writeln(getHelpLong()); } else { LinkedList<String> plist = new LinkedList<>(Arrays.asList(parameters)); plist.remove(); boolean distinct = getOptionalParamValue(plist, "dist... | @Test public void testInvalidArgumentPrintsError() throws Exception { execute("type=memory", FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID2); verifyFailure(); }
@Test public void testDuplicateMembersPrintsError() throws Exception { execute(FED_ID, MEMORY_MEMBER_ID1, MEMORY_MEMBER_ID1); verifyFailure(); }
@Test public voi... |
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 ... | @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 incorr... |
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); retu... | @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 (IOExc... |
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 getHelp... | @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()); }
@... |
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 (eqId... | @Test public void testUnknownParametersAreErrors() { setParameters.execute("set", "unknown"); verify(mockConsoleIO).writeError("Unknown parameter: unknown"); verifyNoMoreInteractions(mockConsoleIO); } |
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... | @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 Bad... |
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.spli... | @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.e... |
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 '"... | @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)).... |
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."); } TupleResultBuild... | @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(HttpServletRespons... |
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 FileInputStre... | @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... |
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... | @Test public void shouldGetMostRecentTimestamp() throws Exception { assertThat(whassup.getMostRecentTimestamp(true)).isEqualTo(1369589322298L); assertThat(whassup.getMostRecentTimestamp(false)).isEqualTo(1369589322298L); } |
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(c... | @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... |
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); Li... | @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(); } |
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 ignoreG... | @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 ... |
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 getLatitu... | @Test public void shouldParseTimestamp() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.timestamp = 1358086780000L; assertThat(m.getTimestamp().getTime()).isEqualTo(1358086780000L); } |
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 {... | @Test public void shouldParseNumber() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); m.key_remote_jid = "4915773981234@s.whatsapp.net"; assertThat(m.getNumber()).isEqualTo("4915773981234"); }
@Test public void shouldParseNumberFromGroupMessage() throws Exception { WhatsAppMessage m = new WhatsAppMessage(... |
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 getFilteredTex... | @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(... |
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 getLat... | @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(); } |
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... | @Test public void shouldCheckIfReceived() throws Exception { WhatsAppMessage m = new WhatsAppMessage(); assertThat(m.isReceived()).isTrue(); m.key_from_me = 1; assertThat(m.isReceived()).isFalse(); } |
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... | @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);... |
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(); } | @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_ima... |
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 =... | @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); } |
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 Pe... | @Test public void search() { personService.search(SEARCH_TERM, PAGE_INDEX); verify(personRepositoryMock, times(1)).findPersonsForPage(SEARCH_TERM, PAGE_INDEX); verifyNoMoreInteractions(personRepositoryMock); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.