src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Event { @android.support.annotation.NonNull public String getTag() { return mTag; } @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull String tag); @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull Object o); @android.support.annotation.NonNull String get... | @Test public void getTag() throws Exception { String mockTag = "Test"; Event event = new Event(mockTag); assertEquals(event.getTag(), mockTag); Integer mockObj = 34; event = new Event(mockObj); assertEquals(event.getTag(), mockObj.getClass().getSimpleName()); } |
Event { public Object getObject() { return mObject; } @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull String tag); @SuppressWarnings("ConstantConditions") Event(@android.support.annotation.NonNull Object o); @android.support.annotation.NonNull String getTag(); Object getObject(); } | @Test public void getObject() throws Exception { Integer mockObj = 34; Event event = new Event(mockObj); assertEquals(event.getObject(), mockObj); } |
InfoModel { public String getLabel() { return label; } InfoModel(@NonNull String label); String getInfo(); void setInfo(@NonNull String info); String getImageUrl(); void setImageUrl(String imageUrl); String getLabel(); } | @SuppressWarnings("ConstantConditions") @Test public void checkLLabel() throws Exception { try { new InfoModel(null); fail(); } catch (IllegalArgumentException e) { } InfoModel infoModel = new InfoModel(MOCK_LABEL); assertEquals(infoModel.getLabel(), MOCK_LABEL); } |
BarcodeInfo { Contact getContact() { return mContact; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void ... | @Test public void getContact() throws Exception { BarcodeInfo.Contact contact = new BarcodeInfo.Contact(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setContact(contact); assertEquals(barcodeInfo.getContact(), contact); } |
BarcodeInfo { UrlBookmark getUrlBookmark() { return mUrlBookmark; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone p... | @Test public void getUrlBookmark() throws Exception { BarcodeInfo.UrlBookmark urlBookmark = new BarcodeInfo.UrlBookmark("Google", "www.google.com"); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setUrlBookmark(urlBookmark); assertEquals(barcodeInfo.getUrlBookmark(), urlBookmark); } |
BarcodeInfo { Sms getSms() { return mSms; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); void setRawValue(... | @Test public void getSms() throws Exception { BarcodeInfo.Sms sms = new BarcodeInfo.Sms("This is test message.", "1234567890"); BarcodeInfo info = new BarcodeInfo(); info.setSms(sms); assertEquals(info.getSms(), sms); } |
BarcodeInfo { GeoPoint getGeoPoint() { return mGeoPoint; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(Phone phone); vo... | @Test public void getGeoPoint() throws Exception { BarcodeInfo.GeoPoint geoPoint = new BarcodeInfo.GeoPoint(23.0225, 72.5714); BarcodeInfo info = new BarcodeInfo(); info.setGeoPoint(geoPoint); assertEquals(info.getGeoPoint(), geoPoint); } |
BarcodeInfo { CalendarEvent getCalendarEvent() { return mCalendarEvent; } void setBoundingBox(Rect boundingBox); void setContact(Contact contact); void setUrlBookmark(UrlBookmark urlBookmark); void setSms(Sms sms); void setGeoPoint(GeoPoint geoPoint); void setCalendarEvent(CalendarEvent calendarEvent); void setPhone(P... | @Test public void getCalendarEvent() throws Exception { BarcodeInfo.CalendarEvent calendarEvent = new BarcodeInfo.CalendarEvent(); BarcodeInfo barcodeInfo = new BarcodeInfo(); barcodeInfo.setCalendarEvent(calendarEvent); assertEquals(barcodeInfo.getCalendarEvent(), calendarEvent); } |
ClasspathUtils { @SuppressWarnings("unchecked") public static <T> Class<? extends T> findImplementationClass(Class<T> clazz) { if (!Modifier.isAbstract(clazz.getModifiers())) return clazz; String implementationClass = String.format("%s.impl.%sImpl", clazz.getPackage().getName(), clazz.getSimpleName()); try { return (Cl... | @Test public void shouldFindImplementation() { Class<? extends DummyComponent> clazz = ClasspathUtils .findImplementationClass(DummyComponent.class); assertEquals(clazz, DummyComponentImpl.class); }
@Test(expectedExceptions = RuntimeException.class) public void shouldThrowExceptionWhenNoImplementationIsFound() { Classp... |
WisePageFactory { public static <T> T initElements(WebDriver driver, Class<T> clazz) { T instance = instantiatePage(driver, clazz); return initElements(driver, instance); } private WisePageFactory(); static T initElements(WebDriver driver, Class<T> clazz); static T initElements(SearchContext searchContext, T instance)... | @Test public void shouldCreatePageWithWebDriverConstructorAndInitElements() { DummyPageWithWebDriverConstructor page = WisePageFactory.initElements( this.driver, DummyPageWithWebDriverConstructor.class); assertNotNull(page.getDummyComponent()); }
@Test public void shouldCreatePageWithNoArgConstructorAndInitElements() {... |
Wiselenium { public static <E> E findElement(Class<E> clazz, By by, SearchContext searchContext) { WebElement webElement = searchContext.findElement(by); return decorateElement(clazz, webElement); } private Wiselenium(); static E findElement(Class<E> clazz, By by, SearchContext searchContext); static List<E> findEleme... | @Test public void shouldFindElement() { DummyComponent select = Wiselenium.findElement(DummyComponent.class, BY_SELECT1, this.driver); assertNotNull(select); }
@Test(expectedExceptions = NoSuchElementException.class) public void shouldThrowExceptionWhenElementIsntFound() { Wiselenium.findElement(DummyComponent.class, B... |
Wiselenium { public static <E> List<E> findElements(Class<E> clazz, By by, SearchContext searchContext) { List<WebElement> webElements = searchContext.findElements(by); if (webElements.isEmpty()) return Lists.newArrayList(); WiseDecorator decorator = new WiseDecorator(new DefaultElementLocatorFactory(searchContext)); r... | @SuppressWarnings("null") @Test public void shouldFindElements() { List<DummyComponent> elements = Wiselenium.findElements( DummyComponent.class, BY_RADIOBUTTON, this.driver); assertTrue(elements != null && !elements.isEmpty()); for (DummyComponent element : elements) { assertNotNull(element); } }
@Test public void sho... |
LexerStream extends LineNumberReader { public int peek() throws IOException { super.mark(1); int c = super.read(); super.reset(); return c; } LexerStream(Reader in_stream); int getLine(); int getCol(); int getPosition(); @Override int read(); @Override String readLine(); int peek(); int peek(int ahead); @Override int r... | @Test public void peek() throws Exception { Reader in = new StringReader("I see you"); LexerStream ls = new LexerStream(in); assertEquals(1, ls.getLine()); assertEquals(1, ls.getCol()); int c = ls.peek(); assertEquals('I', (char)c); assertTrue(1 == ls.getLine() && 1 == ls.getCol()); c = ls.peek(2); assertEquals(' ', (c... |
LexCharLiteral { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int code_point; int next = in_stream.peek(); if (next != '\'') { throw new LexerException(start_line, start_col, "Not a character... | @Test public void chars() throws Exception { String str = "'a' '\\n' '' '\\t'"; LexerStream ls = new LexerStream(new StringReader(str)); LexCharLiteral lex = new LexCharLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralChar, tok.getType()); assertEquals("a", tok.getValue()); ass... |
LexDelimitedString { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of input strea... | @Test public void normal() throws Exception { String str = "q\"!foo!\""; LexerStream ls = new LexerStream(new StringReader(str)); LexDelimitedString lex = new LexDelimitedString(new BaseTokenFactory(), ls); Token tok = lex.read(); Assert.assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() inst... |
LexerStream extends LineNumberReader { @Override public String readLine() throws IOException { String ln = super.readLine(); if (ln != null) { index += ln.length(); } line = super.getLineNumber(); col = 1; return ln; } LexerStream(Reader in_stream); int getLine(); int getCol(); int getPosition(); @Override int read(); ... | @Test public void readLine() throws Exception { Reader in = new StringReader("line1\nline2\n3line\n\nline5"); LexerStream ls = new LexerStream(in); assertEquals(1, ls.getLine()); assertEquals(1, ls.getCol()); assertEquals('l', (char)ls.read()); assertEquals(1, ls.getLine()); assertEquals(2, ls.getCol()); assertEquals("... |
LexHexLiteral { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of input stream whe... | @Test public void simple() throws Exception { String str = "x\"0A\""; StringBuilder sb = new StringBuilder(); sb.append(Character.toChars(0x0a)); String expected = sb.toString(); LexerStream ls = new LexerStream(new StringReader(str)); LexHexLiteral lex = new LexHexLiteral(new BaseTokenFactory(), ls); Token tok = lex.r... |
LexOperator { public Token read() throws IOException, LexerException { int index = in_stream.getPosition(); int line = in_stream.getLine(); int col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when ... | @Test public void not_op() throws Exception { String str = "foo"; LexerStream ls = new LexerStream(new StringReader(str)); LexOperator lex = new LexOperator(new BaseTokenFactory(), ls); Token tok = lex.read(); assertNull(tok); lex = new LexOperator(new BaseTokenFactory(), new LexerStream(new StringReader(""))); try { t... |
LexIdentifier { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of input stream whe... | @Test public void keywords() throws Exception { StringBuilder words = new StringBuilder(); for (String word : keywords) { words.append(word).append(" "); } LexerStream ls = new LexerStream(new StringReader(words.toString())); LexIdentifier lex = new LexIdentifier(new BaseTokenFactory(), ls); for (String word : keywords... |
LexStringLiteral { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); boolean is_literal = false; int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Une... | @Test public void simple() throws Exception { String str = "\"Here is a string\""; LexerStream ls = new LexerStream(new StringReader(str)); LexStringLiteral lex = new LexStringLiteral(new BaseTokenFactory(), ls); Token tok = lex.read(); assertEquals(TokenType.LiteralUtf8, tok.getType()); assertTrue(tok.getValue() insta... |
LexTokenString { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(start_line, start_col, "Unexpected end of stream when par... | @Test(expected = LexerException.class) public void empty() throws Exception { String str = ""; LexerStream ls = new LexerStream(new StringReader(str)); LexTokenString lex = new LexTokenString(new BaseTokenFactory(), ls, null); lex.read(); }
@Test(expected = LexerException.class) public void not() throws Exception { Str... |
LexComment { public Token read() throws IOException, LexerException { int start_index = in_stream.getPosition(); int start_line = in_stream.getLine(); int start_col = in_stream.getCol(); int next = in_stream.peek(); if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of i... | @Test public void line() throws Exception { String str = "a LexerStream ls = new LexerStream(new StringReader(str)); LexComment lex = new LexComment(new BaseTokenFactory(), ls); ls.read(); Token tok = lex.read(); assertEquals(TokenType.LineComment, tok.getType()); assertEquals(" assertEquals(1, tok.getLine()); assertEq... |
LexEscape { public static int read(final LexerStream in_stream) throws IOException, LexerException { int next = in_stream.peek(); if (next == -1) { throw new LexerException(in_stream.getLine(), in_stream.getCol(), "Unexpected end of input stream when inside escape sequence"); } if (next != '\\') { throw new LexerExcept... | @Test public void escape() throws Exception { String str = "\\'" + "\\\"" + "\\?" + "\\\\" + "\\a" + "\\b" + "\\f" + "\\n" + "\\r" + "\\t" + "\\v" + "\\0" + ""; LexerStream ls = new LexerStream(new StringReader(str)); assertEquals('\'', (char)LexEscape.read(ls)); assertEquals('"', (char)LexEscape.read(ls)); assertEqual... |
Lexer { public Token next() throws IOException { Token token; try { token = _next(); } catch (LexerException e) { token = factory.create(TokenType.Unknown, in_stream.getPosition(), in_stream.getLine(), in_stream.getCol()); in_stream.read(); } return token; } Lexer(TokenFactory tokenFactory, Reader inStream); private L... | @Test public void lex() throws Exception { String code = "" + " "import std.stdio;\n" + "\n" + "void main() {\n" + " ulong lines = 0;\n" + " double sumLength=0;\n" + " foreach (line;stdin.byLine()){\n" + " ++lines;\n" + " sumLength += line.length;\n" + " }\n" + " writeln(\"Average line length: \",\n" + " lines ? sumLen... |
MCacheDb extends AbstractActor { public String getValue(String key) { return this.map.get(key); } @Override Receive createReceive(); String getValue(String key); } | @Test public void testPut() { TestActorRef<MCacheDb> actorRef = TestActorRef.create(actorSystem, Props.create(MCacheDb.class)); actorRef.tell(new SetRequest("key", "value"), ActorRef.noSender()); MCacheDb mCacheDb = actorRef.underlyingActor(); Assert.assertEquals(mCacheDb.getValue("key"), "value"); } |
HelloWorldImpl implements HelloWorldPortType { @Override public Greeting sayHello(Person person) { String firstName = person.getFirstName(); LOGGER.info("firstName={}", firstName); String lasttName = person.getLastName(); LOGGER.info("lastName={}", lasttName); ObjectFactory factory = new ObjectFactory(); Greeting respo... | @Test public void testSayHelloProxy() { Person person = new Person(); person.setFirstName("Jane"); person.setLastName("Doe"); Greeting greeting = helloWorldRequesterProxy.sayHello(person); assertEquals("Hello Jane Doe!", greeting.getText()); } |
DefaultRegisteredServiceMfaRoleProcessorImpl implements RegisteredServiceMfaRoleProcessor { public List<MultiFactorAuthenticationRequestContext> resolve(@NotNull final Authentication authentication, @NotNull final WebApplicationService targetService) { String authenticationMethodAttributeName = null; final List<MultiFa... | @Test public void testResolveWithoutAnyServiceMfaAttributes() throws Exception { final WebApplicationService was = getTargetService(); final Authentication auth = getAuthentication(true); final RegisteredService rswa = TestUtils.getRegisteredService("test1"); final DefaultRegisteredServiceMfaRoleProcessorImpl resolver ... |
RevisionRemoverJob implements Runnable { void setRevisionInformation(RevisionInformation revisionInformation) { this.revisionInformation = revisionInformation; } RevisionRemoverJob(DataSetServiceClient dataSetServiceClient, RecordServiceClient recordServiceClient, RevisionInformation revisionInformation, RevisionServic... | @Test public void shouldRemoveRevisionsOnly() throws Exception { final int NUMBER_OF_REVISIONS = 3; final int NUMBER_OF_RESPONSES = 2; RevisionInformation revisionInformation = new RevisionInformation("DATASET", DATA_PROVIDER, SOURCE + REPRESENTATION_NAME, REVISION_NAME, REVISION_PROVIDER, getUTCDateString(date)); revi... |
LinkCheckBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple tuple) { ResourceInfo resourceInfo = readResourceInfoFromTuple(tuple); if (!hasLinksForCheck(resourceInfo)) { emitSuccessNotification(anchorTuple, tuple.getTaskId(), tuple.getFileUrl(), "", "The EDM file has no resou... | @Test public void shouldEmitSameTupleWhenNoResourcesHasToBeChecked() { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = prepareTupleWithLinksCountEqualsToZero(); linkCheckBolt.execute(anchorTuple, tuple); verify(outputCollector, times(1)).emit( eq("NotificationStream"), eq(anchorTuple), captor.capture(... |
EnrichmentBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { String fileContent = new String(stormTaskTuple.getFileData()); LOGGER.info("starting enrichment on {} .....", stormTaskTuple.getFileUrl()); String output = enrichmentWorker.process(fileConten... | @Test public void enrichEdmInternalSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, new HashMap<String, ... |
RecordHarvestingBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { long harvestingStartTime = new Date().getTime(); LOGGER.info("Starting harvesting for: {}", stormTaskTuple.getParameter(CLOUD_LOCAL_IDENTIFIER)); String endpointLocation = readEndpointLocatio... | @Test public void harvestingForAllParametersSpecified() throws IOException, HarvesterException { Tuple anchorTuple = mock(TupleImpl.class); InputStream fileContentAsStream = getFileContentAsStream("/sampleEDMRecord.xml"); when(harvester.harvestRecord(anyString(), anyString(), anyString(), any(XPathExpression.class), an... |
RemoverInvoker { public void executeInvokerForSingleTask(long taskId, boolean shouldRemoveErrors) { remover.removeNotifications(taskId); LOGGER.info("Logs for task Id:" + taskId + " were removed successfully"); LOGGER.info("Removing statistics for:" + taskId + " was started. This step could take times depending on the ... | @Test public void shouldInvokeAllTheRemovalStepsExcludingErrorReports() { removerInvoker.executeInvokerForSingleTask(TASK_ID, false); verify(remover, times(1)).removeNotifications((eq(TASK_ID))); verify(remover, times(1)).removeStatistics((eq(TASK_ID))); verify(remover, times(0)).removeErrorReports((eq(TASK_ID))); }
@T... |
ReadFileBolt extends AbstractDpsBolt { private InputStream getFile(FileServiceClient fileClient, String file, String authorization) throws MCSException, IOException { int retries = DEFAULT_RETRIES; while (true) { try { return fileClient.getFile(file, AUTHORIZATION, authorization); } catch (Exception e) { if (retries-- ... | @Test public void shouldEmmitNotificationWhenDataSetListHasOneElement() throws MCSException, IOException { when(fileServiceClient.getFile(eq(FILE_URL),eq(AUTHORIZATION), eq(AUTHORIZATION_HEADER))).thenReturn(null); verifyMethodExecutionNumber(1, 0, FILE_URL); }
@Test public void shouldRetry3TimesBeforeFailingWhenThrowi... |
HarvestingWriteRecordBolt extends WriteRecordBolt { private String getCloudId(String authorizationHeader, String providerId, String localId, String additionalLocalIdentifier) throws CloudException { String result; CloudId cloudId; cloudId = getCloudId(providerId, localId, authorizationHeader); if (cloudId != null) { re... | @Test public void successfulExecuteStormTupleWithExistedCloudId() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); CloudId cloudId = mock(CloudId.class); when(cloudId.getId()).thenReturn(SOURCE + CLOUD_ID); when(uisClient.getCloudId(SOURCE + DATA_PROVIDER, SOURCE + LOCAL_ID,AUTHORIZATION,AUTHORIZATION_HEAD... |
RemoverInvoker { public void executeInvokerForListOfTasks(String filePath, boolean shouldRemoveErrors) throws IOException { TaskIdsReader reader = new CommaSeparatorReaderImpl(); List<String> taskIds = reader.getTaskIds(filePath); for (String taskId : taskIds) { executeInvokerForSingleTask(Long.valueOf(taskId), shouldR... | @Test public void shouldExecuteTheRemovalOnListOfTASKS() throws IOException { removerInvoker.executeInvokerForListOfTasks("src/test/resources/taskIds.csv", true); verify(remover, times(6)).removeNotifications(anyLong()); verify(remover, times(6)).removeStatistics((anyLong())); verify(remover, times(6)).removeErrorRepor... |
ParseFileBolt extends ReadFileBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try (InputStream stream = getFileStreamByStormTuple(stormTaskTuple)) { byte[] fileContent = IOUtils.toByteArray(stream); List<RdfResourceEntry> rdfResourceEntries = getResourcesFromRDF(fileContent); in... | @Test public void shouldParseFileAndEmitResources() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); when(taskStatusC... |
AddResultToDataSetBolt extends AbstractDpsBolt { private void assignRepresentationToDataSet(DataSet dataSet, Representation resultRepresentation, String authorizationHeader) throws MCSException { int retries = DEFAULT_RETRIES; while (true) { try { dataSetServiceClient.assignRepresentationToDataSet( dataSet.getProviderI... | @Test public void shouldRetry3TimesBeforeFailingWhenThrowingMCSException() throws MCSException { stormTaskTuple = prepareTupleWithSingleDataSet(); doThrow(MCSException.class).when(dataSetServiceClient).assignRepresentationToDataSet(anyString(), anyString(), anyString(), anyString(), anyString(),eq(AUTHORIZATION),eq(AUT... |
QueueFiller { public int addTupleToQueue(StormTaskTuple stormTaskTuple, FileServiceClient fileServiceClient, Representation representation) { int count = 0; final long taskId = stormTaskTuple.getTaskId(); if (representation != null) { for (eu.europeana.cloud.common.model.File file : representation.getFiles()) { String ... | @Test public void testAddingToQueueSuccessfully() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); Representation representation = testHelper.prepareRepresentation(SOURCE + CLOUD_ID, SOURCE + REPRESENTATION_NAME, SOURCE + VERSION, SOURCE_VERSION_URL, DATA_PROVIDER, false, new Date())... |
FileUtil { public static String createFilePath(String folderPath, String fileName, String extension) { String filePtah = folderPath + fileName; if ("".equals(FilenameUtils.getExtension(fileName))) filePtah = filePtah + extension; return filePtah; } static void persistStreamToFile(InputStream inputStream, String folder... | @Test public void shouldCreateTheCorrectFilePath() throws Exception { String filePath = FileUtil.createFilePath(FOLDER_PATH, FILE_NAME_WITHOUT_EXTENSION, EXTENSION); assertEquals(filePath, FILE_PATH); filePath = FileUtil.createFilePath(FOLDER_PATH, FILE_NAME_WITH_EXTENSION, EXTENSION); assertEquals(filePath, FILE_PATH)... |
TaskExecutor implements Callable<Void> { @Override public Void call() { try { execute(); } catch (Exception e) { taskStatusUpdater.setTaskDropped(dpsTask.getTaskId(), "The task was dropped because of " + e.getMessage() + ". The full exception is" + Throwables.getStackTraceAsString(e)); } return null; } TaskExecutor(Spo... | @Test public void shouldEmitTheFilesWhenNoRevisionIsSpecified() throws Exception { when(taskStatusChecker.hasKillFlag(anyLong())).thenReturn(false); when(collector.emit(anyListOf(Object.class))).thenReturn(null); List<String> dataSets = new ArrayList<>(); dataSets.add(DATASET_URL); DpsTask dpsTask = prepareDpsTask(data... |
PropertyFileLoader { public void loadDefaultPropertyFile(String defaultPropertyFile, Properties topologyProperties) throws IOException { InputStream propertiesInputStream = Thread.currentThread() .getContextClassLoader().getResourceAsStream(defaultPropertyFile); if (propertiesInputStream == null) throw new FileNotFound... | @Test public void testLoadingDefaultPropertiesFile() throws FileNotFoundException, IOException { reader.loadDefaultPropertyFile(DEFAULT_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet... |
PropertyFileLoader { public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); FileInputStream fileInput = new FileInputStream(file); topologyProperties.load(fileInput); fileInput.close(); } static void loadPropertyFile(String defaultPrope... | @Test public void testLoadingProvidedPropertiesFile() throws FileNotFoundException, IOException { reader.loadProvidedPropertyFile(PROVIDED_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entry... |
FileUtil { public static String createZipFolderPath(Date date) { String folderName = generateFolderName(date); return System.getProperty("user.dir") + "/" + folderName + ZIP_FORMAT_EXTENSION; } static void persistStreamToFile(InputStream inputStream, String folderPath, String fileName, String extension); static String... | @Test public void testCreateZipFolderPath() { Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ssss"); String expectedFolderName = ECLOUD_SUFFIX + "-" + dateFormat.format(date); String folderPath = FileUtil.createZipFolderPath(date); String extension = FilenameUtils.getExtension... |
PropertyFileLoader { public static void loadPropertyFile(String defaultPropertyFile, String providedPropertyFile, Properties topologyProperties) { try { PropertyFileLoader reader = new PropertyFileLoader(); reader.loadDefaultPropertyFile(defaultPropertyFile, topologyProperties); if (!"".equals(providedPropertyFile)) { ... | @Test public void testLoadingFileWhenProvidedPropertyFileNotExisted() throws FileNotFoundException, IOException { PropertyFileLoader.loadPropertyFile(DEFAULT_PROPERTIES_FILE, "NON_EXISTED_PROVIDED_FILE", topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.En... |
CassandraValidationStatisticsService implements ValidationStatisticsReportService { @Override public StatisticsReport getTaskStatisticsReport(long taskId) { StatisticsReport report = cassandraNodeStatisticsDAO.getStatisticsReport(taskId); if (report == null) { List<NodeStatistics> nodeStatistics = cassandraNodeStatisti... | @Test public void getTaskStatisticsReport() { List<NodeStatistics> stats = prepareStats(); Mockito.when(cassandraNodeStatisticsDAO.getNodeStatistics(TASK_ID)).thenReturn(stats); Mockito.when(cassandraNodeStatisticsDAO.getStatisticsReport(TASK_ID)).thenReturn(null); StatisticsReport actual = cassandraStatisticsService.g... |
TaskStatusChecker { public boolean hasKillFlag(long taskId) { try { return cache.get(taskId); } catch (ExecutionException e) { LOGGER.info(e.getMessage()); return false; } } private TaskStatusChecker(CassandraConnectionProvider cassandraConnectionProvider); TaskStatusChecker(CassandraTaskInfoDAO taskDAO); static sync... | @Test public void testExecutionWithMultipleTasks() throws Exception { when(taskInfoDAO.hasKillFlag(TASK_ID)).thenReturn(false, false, false, true, true); when(taskInfoDAO.hasKillFlag(TASK_ID2)).thenReturn(false, false, true); boolean task1killedFlag = false; boolean task2killedFlag = false; for (int i = 0; i < 8; i++) ... |
TaskTupleUtility { protected static boolean isProvidedAsParameter(StormTaskTuple stormTaskTuple, String parameter) { if (stormTaskTuple.getParameter(parameter) != null) { return true; } else { return false; } } static String getParameterFromTuple(StormTaskTuple stormTaskTuple, String parameter); } | @Test public void parameterIsProvidedTest() { stormTaskTuple.addParameter(PluginParameterKeys.MIME_TYPE, MIME_TYPE); assertTrue(TaskTupleUtility.isProvidedAsParameter(stormTaskTuple, PluginParameterKeys.MIME_TYPE)); }
@Test public void parameterIsNotProvidedTest() { assertFalse(TaskTupleUtility.isProvidedAsParameter(st... |
TaskTupleUtility { public static String getParameterFromTuple(StormTaskTuple stormTaskTuple, String parameter) { String outputValue = PluginParameterKeys.PLUGIN_PARAMETERS.get(parameter); if (isProvidedAsParameter(stormTaskTuple, parameter)) { outputValue = stormTaskTuple.getParameter(parameter); } return outputValue; ... | @Test public void getDefaultValueTest() { assertEquals(TaskTupleUtility.getParameterFromTuple(stormTaskTuple, PluginParameterKeys.MIME_TYPE), PluginParameterKeys.PLUGIN_PARAMETERS.get(PluginParameterKeys.MIME_TYPE)); }
@Test public void getProvidedValueTest() { stormTaskTuple.addParameter(PluginParameterKeys.MIME_TYPE,... |
FolderCompressor { public static void compress(String folderPath, String zipFolderPath) throws ZipException { File folder = new File(folderPath); ZipUtil.pack(folder, new File(zipFolderPath)); } static void compress(String folderPath, String zipFolderPath); } | @Test(expected = ZipException.class) public void shouldThrowZipExceptionWhileCompressEmptyFolder() throws Exception { folderPath = FileUtil.createFolder(); File folder = new File(folderPath); assertTrue(folder.isDirectory()); zipFolderPath = FileUtil.createZipFolderPath(new Date()); FolderCompressor.compress(folderPath... |
Retriever { public static void retryOnError3Times(String errorMessage, Runnable runnable) { retryOnError3Times(errorMessage,()->{ runnable.run(); return null; }); } static void retryOnError3Times(String errorMessage, Runnable runnable); static V retryOnError3Times(String errorMessage, Callable<V> callable); static voi... | @Test public void repeatOnError3Times_callNoThrowsExceptions_validResult() throws Exception { when(call.call()).thenReturn(RESULT); String result = Retriever.retryOnError3Times(ERROR_MESSAGE, call); assertEquals(RESULT, result); }
@Test public void repeatOnError3Times_callNoThrowsExceptions_callInvokedOnce() throws Exc... |
TaskStatusSynchronizer { public void synchronizeTasksByTaskStateFromBasicInfo(String topologyName, Collection<String> availableTopics) { List<TaskInfo> tasksFromTaskByTaskStateTableList = tasksByStateDAO.listAllActiveTasksInTopology(topologyName); Map<Long, TaskInfo> tasksFromTaskByTaskStateTableMap = tasksFromTaskByTa... | @Test public void synchronizeShouldNotFailIfThereIsNoTask() { synchronizer.synchronizeTasksByTaskStateFromBasicInfo(TOPOLOGY_NAME, TOPICS); }
@Test public void synchronizedShouldRepairInconsistentData() { when(tasksByStateDAO.listAllActiveTasksInTopology(eq(TOPOLOGY_NAME))).thenReturn(Collections.singletonList(TASK_TOP... |
NotificationBolt extends BaseRichBolt { @Override public void execute(Tuple tuple) { try { NotificationTuple notificationTuple = NotificationTuple .fromStormTuple(tuple); NotificationCache nCache = cache.get(notificationTuple.getTaskId()); if (nCache == null) { nCache = new NotificationCache(notificationTuple.getTaskId... | @Test public void testUpdateBasicInfoStateWithStartDateAndInfo() throws Exception { long taskId = 1; int containsElements = 1; int expectedSize = 1; String topologyName = null; TaskState taskState = TaskState.CURRENTLY_PROCESSING; String taskInfo = ""; Date startTime = new Date(); TaskInfo expectedTaskInfo = createTask... |
MCSTaskSubmiter { public void execute(SubmitTaskParameters submitParameters) { DpsTask task = submitParameters.getTask(); try { LOGGER.info("Sending task id={} to topology {} by kafka topic {}. Parameters:\n{}", task.getTaskId(), submitParameters.getTopologyName(), submitParameters.getTopicName(), submitParameters); ch... | @Test public void executeMcsBasedTask_taskIsNotKilled_verifyUpdateTaskInfoInCassandra() { task.addDataEntry(InputDataType.FILE_URLS, Collections.singletonList(FILE_URL_1)); submiter.execute(submitParameters); verify(taskStatusUpdater).updateStatusExpectedSize(eq(TASK_ID), eq(String.valueOf(TaskState.QUEUED)),eq(1)); }
... |
RecordDownloader { public final String downloadFilesFromDataSet(String providerId, String datasetName, String representationName, int threadsCount) throws InterruptedException, ExecutionException, IOException, DriverException,MimeTypeException, RepresentationNotFoundException { ExecutorService executorService = Executo... | @Test public void shouldSuccessfullyDownloadTwoRecords() throws Exception { Representation representation = prepareRepresentation(); inputStream = IOUtils.toInputStream("some test data for my input stream"); inputStream2 = IOUtils.toInputStream("some test data for my input stream"); when(dataSetServiceClient.getReprese... |
TopologyTasksResource { @GetMapping(value = "{taskId}/progress", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") public TaskInfo getTaskProgress( @PathVariable final String topologyName, @PathVariable final String taskId... | @Test public void shouldGetProgressReport() throws Exception { TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, EMPTY_STRING, 100, 100, 10, 50, new Date(), new Date(), new Date()); when(reportService.getTaskProgress(eq(Long.toString(TASK_ID)))).thenReturn(taskInfo); when(topologyManager.con... |
ReportResource { @GetMapping(path = "{taskId}/statistics", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasPermission(#taskId,'" + TASK_PREFIX + "', read)") public StatisticsReport getTaskStatisticsReport( @PathVariable String topologyName, @PathVariable String taskId) ... | @Test public void shouldGetStatisticReport() throws Exception { when(validationStatisticsService.getTaskStatisticsReport(TASK_ID)).thenReturn(new StatisticsReport(TASK_ID, null)); when(topologyManager.containsTopology(anyString())).thenReturn(true); ResultActions response = mockMvc.perform(get(VALIDATION_STATISTICS_REP... |
TaskSubmitterFactory { public TaskSubmitter provideTaskSubmitter(SubmitTaskParameters parameters) { switch (parameters.getTopologyName()) { case TopologiesNames.OAI_TOPOLOGY: return oaiTopologyTaskSubmitter; case TopologiesNames.HTTP_TOPOLOGY: return httpTopologyTaskSubmitter; case TopologiesNames.ENRICHMENT_TOPOLOGY: ... | @Test public void shouldProvideSubmitterForDepublicationTopology() { TaskSubmitter taskSubmitter = new TaskSubmitterFactory( Mockito.mock(OaiTopologyTaskSubmitter.class), Mockito.mock(HttpTopologyTaskSubmitter.class), Mockito.mock(OtherTopologiesTaskSubmitter.class), Mockito.mock(DepublicationTaskSubmitter.class) ).pro... |
UnfinishedTasksExecutor { @PostConstruct public void reRunUnfinishedTasks() { LOGGER.info("Will restart all pending tasks"); List<TaskInfo> results = findProcessingByRestTasks(); List<TaskInfo> tasksForCurrentMachine = findTasksForCurrentMachine(results); resumeExecutionFor(tasksForCurrentMachine); } UnfinishedTasksExe... | @Test public void shouldNotStartExecutionForEmptyTasksList() { List<TaskInfo> unfinishedTasks = new ArrayList<>(); Mockito.reset(cassandraTasksDAO); when(cassandraTasksDAO.findTasksInGivenState(Mockito.any(List.class))).thenReturn(unfinishedTasks); unfinishedTasksExecutor.reRunUnfinishedTasks(); Mockito.verify(cassandr... |
RowsValidatorJob implements Callable<Void> { @Override public Void call() throws Exception { validateRows(); return null; } RowsValidatorJob(Session session, List<String> primaryKeys, BoundStatement matchingBoundStatement, List<Row> rows); @Override Void call(); } | @Test public void shouldExecuteTheSessionWithoutRetry() throws Exception { ResultSet resultSet = mock(ResultSet.class); when(resultSet.one()).thenReturn(rows.get(0)); when(resultSet.one().getLong("count")).thenReturn(1l); when(session.execute(matchingBoundStatement)).thenReturn(resultSet); PreparedStatement preparedSta... |
TopologiesTopicsParser { public Map<String, List<String>> parse(String topicsList) { if (isInputValid(topicsList)) { List<String> topologies = extractTopologies(topicsList); return extractTopics(topologies); } else { throw new RuntimeException("Topics list is not valid"); } } Map<String, List<String>> parse(String top... | @Test public void shouldSuccessfullyParseTopicsList() { TopologiesTopicsParser t = new TopologiesTopicsParser(); Map<String, List<String>> topologiesTopicsList = t.parse(VALID_INPUT); Assert.assertEquals(2, topologiesTopicsList.size()); Assert.assertNotNull(topologiesTopicsList.get("oai_topology")); Assert.assertNotNul... |
GhostTaskService { public List<TaskInfo> findGhostTasks() { return findTasksInGivenStates(TaskState.PROCESSING_BY_REST_APPLICATION, TaskState.QUEUED). filter(this::isGhost).collect(Collectors.toList()); } GhostTaskService(Environment environment); @Scheduled(cron = "0 0 * * * *") void serviceTask(); List<TaskInfo> find... | @Test public void findGhostTasksReturnsEmptyListIfNotTaskActive() { assertThat(service.findGhostTasks(), empty()); }
@Test public void findGhostTasksReturnsTaskIfItIsOldSentAndNoStarted() { when(tasksByStateDAO.findTasksInGivenState(eq(ACTIVE_TASK_STATES))) .thenReturn(Collections.singletonList(TOPIC_INFO_1)); when(tas... |
DatasetFilesCounter extends FilesCounter { public int getFilesCount(DpsTask task) throws TaskSubmissionException { String providedTaskId = task.getParameter(PluginParameterKeys.PREVIOUS_TASK_ID); if (providedTaskId==null) return UNKNOWN_EXPECTED_SIZE; try { long taskId = Long.parseLong(providedTaskId); TaskInfo taskInf... | @Test public void shouldReturnProcessedFiles() throws Exception { TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, "", EXPECTED_SIZE, EXPECTED_SIZE, 0, 0, new Date(), new Date(), new Date()); when(taskInfoDAO.findById(TASK_ID)).thenReturn(Optional.of(taskInfo)); dpsTask.addParameter(PluginP... |
OaiPmhFilesCounter extends FilesCounter { @Override public int getFilesCount(DpsTask task) throws TaskSubmissionException { OAIPMHHarvestingDetails harvestingDetails = task.getHarvestingDetails(); if (harvestingDetails != null) { if (specified(harvestingDetails.getExcludedSets()) || specified(harvestingDetails.getExclu... | @Test public void shouldGetCorrectCompleteListSize() throws Exception { stubFor(get(urlEqualTo("/oai-phm/?verb=ListIdentifiers")) .willReturn(response200XmlContent(getFileContent("/oaiListIdentifiers.xml")))); OaiPmhFilesCounter counter = new OaiPmhFilesCounter(); OAIPMHHarvestingDetails details = new OAIPMHHarvestingD... |
ValidatorFactory { public static Validator getValidator(ValidatorType type) { if (type == ValidatorType.KEYSPACE) return new KeyspaceValidator(); if (type == ValidatorType.TABLE) return new TableValidator(); return null; } static Validator getValidator(ValidatorType type); } | @Test public void TestValidator() { Validator validator = ValidatorFactory.getValidator(ValidatorType.KEYSPACE); assertTrue(validator instanceof KeyspaceValidator); validator = ValidatorFactory.getValidator(ValidatorType.TABLE); assertTrue(validator instanceof TableValidator); } |
DepublicationFilesCounter extends FilesCounter { @Override public int getFilesCount(DpsTask task) throws TaskSubmissionException { if (task.getParameter(PluginParameterKeys.RECORD_IDS_TO_DEPUBLISH) != null) { return calculateRecordsNumber(task); } if (task.getParameter(PluginParameterKeys.METIS_DATASET_ID) != null) { r... | @Test public void shouldCountRecords() throws Exception { int randomNum = ThreadLocalRandom.current().nextInt(1, DATASET_EXPECTED_SIZE); StringBuilder records = new StringBuilder("r1"); for(int index = 2; index <= randomNum; index++) { records.append(", r"); records.append(index); } DpsTask dpsTask = new DpsTask(); dps... |
DepublicationService { public void depublishDataset(SubmitTaskParameters parameters) { try { long taskId = parameters.getTask().getTaskId(); checkTaskKilled(taskId); Future<Integer> future = depublisher.executeDatasetDepublicationAsync(parameters); waitForFinish(future, parameters); } catch (SubmitingTaskWasKilled e) {... | @Test public void verifyUseValidEnvironmentIfNoAlternativeEnvironmentParameterSet() throws IndexingException, URISyntaxException { service.depublishDataset(parameters); verify(metisIndexerFactory, atLeast(1)).openIndexer(eq(false)); verify(metisIndexerFactory, never()).openIndexer(eq(true)); }
@Test public void verifyU... |
KeyspaceValidator implements Validator { @Override public void validate(CassandraConnectionProvider sourceCassandraConnectionProvider, CassandraConnectionProvider targetCassandraConnectionProvider, String sourceTableName, String targetTableName, int threadsCount) throws InterruptedException, ExecutionException { Execut... | @Test public void verifyJobExecution() throws Exception { CassandraConnectionProvider cassandraConnectionProvider = mock(CassandraConnectionProvider.class); int threadCount = 1; String tableName = "tableName"; KeyspaceValidator keyspaceValidator = new KeyspaceValidator(); Metadata metadata = mock(Metadata.class); Keysp... |
DpsClient { public long submitTask(DpsTask task, String topologyName) throws DpsException { Response resp = null; try { resp = client.target(dpsUrl) .path(TASKS_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .request() .post(Entity.json(task)); if (resp.getStatus() == Response.Status.CREATED.getStatusCode()) { retu... | @Betamax(tape = "DPSClient/submitTaskAndFail") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public final void shouldThrowAnExceptionWhenCannotSubmitATask() throws Exception { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); DpsTask task = prepareDpsTask(); dpsClient.su... |
DpsClient { public Response.StatusType topologyPermit(String topologyName, String username) throws DpsException { Form form = new Form(); form.param("username", username); Response resp = null; try { resp = client.target(dpsUrl) .path(PERMIT_TOPOLOGY_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .request() .post(E... | @Test @Betamax(tape = "DPSClient/permitForNotDefinedTopologyTest") public final void shouldNotBeAbleToPermitUserForNotDefinedTopology() throws Exception { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); try { dpsClient.topologyPermit(NOT_DEFINED_TOPOLOGY_NAME, "user"); fail(); } catch (Ac... |
DpsClient { public TaskInfo getTaskProgress(String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(TASK_PROGRESS_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().get(); if (response.getStatus() ... | @Test @Betamax(tape = "DPSClient/getTaskProgressTest") public final void shouldReturnedProgressReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); TaskInfo taskInfo = new TaskInfo(TASK_ID, TOPOLOGY_NAME, TaskState.PROCESSED, "", 1, 0, 0, 0, null, null, null); assert... |
DpsClient { public String killTask(final String topologyName, final long taskId, String info) throws DpsException { Response response = null; try { WebTarget webTarget = client.target(dpsUrl).path(KILL_TASK_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName).resolveTemplate(TASK_ID, taskId); if (info != null) { webTarge... | @Test @Betamax(tape = "DPSClient/killTaskTest") public final void shouldKillTask() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_NAME); String responseMessage = dpsClient.killTask(TOPOLOGY_NAME, TASK_ID, null); assertEquals(responseMessage, "The task was killed because of Dro... |
DpsClient { public List<SubTaskInfo> getDetailedTaskReport(final String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(DETAILED_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().get(... | @Test @Betamax(tape = "DPSClient_getTaskDetailsReportTest") public final void shouldReturnedDetailsReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); SubTaskInfo subTaskInfo = new SubTaskInfo(1, "resource", RecordState.SUCCESS, "", "", "result"); List<SubTaskIn... |
DpsClient { public TaskErrorsInfo getTaskErrorsReport(final String topologyName, final long taskId, final String error, final int idsCount) throws DpsException { Response response = null; try { response = client .target(dpsUrl) .path(ERRORS_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate... | @Test @Betamax(tape = "DPSClient_shouldReturnedGeneralErrorReport") public final void shouldReturnedGeneralErrorReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); TaskErrorsInfo report = createErrorInfo(TASK_ID, false); assertThat(dpsClient.getTaskErrorsReport(... |
CassandraHelper { public static BoundStatement prepareBoundStatementForMatchingTargetTable(CassandraConnectionProvider cassandraConnectionProvider, String targetTableName, List<String> primaryKeys) { String matchCountStatementCQL = CQLBuilder.getMatchCountStatementFromTargetTable(targetTableName, primaryKeys); Prepared... | @Test public void prepareBoundStatementForMatchingTargetTableTest() { assertThat(CassandraHelper.prepareBoundStatementForMatchingTargetTable(cassandraConnectionProvider, "table", primaryKeys), is(boundStatement)); } |
DpsClient { public boolean checkIfErrorReportExists(final String topologyName, final long taskId) { Response response = null; try { response = client .target(dpsUrl) .path(ERRORS_TASK_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId) .request().head(); return response.getStatus... | @Test @Betamax(tape = "DPSClient_shouldReturnTrueWhenErrorsReportExists") public final void shouldReturnTrueWhenErrorsReportExists() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); assertTrue(dpsClient.checkIfErrorReportExists(TOPOLOGY_NAME, TASK_ID)); }
@Test @Betam... |
DpsClient { public List<NodeReport> getElementReport(final String topologyName, final long taskId, String elementPath) throws DpsException { Response getResponse = null; try { getResponse = client .target(dpsUrl) .path(ELEMENT_REPORT) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, taskId).query... | @Test @Betamax(tape = "DPSClient_shouldReturnElementReport") public void shouldGetTheElementReport() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); List<NodeReport> nodeReports = dpsClient.getElementReport(TOPOLOGY_NAME, TASK_ID, " assertNotNull(nodeReports); assert... |
DpsClient { public StatisticsReport getTaskStatisticsReport(final String topologyName, final long taskId) throws DpsException { Response response = null; try { response = client.target(dpsUrl).path(STATISTICS_REPORT_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName).resolveTemplate(TASK_ID, taskId).request() .get(); if... | @Test(expected = AccessDeniedOrTopologyDoesNotExistException.class) @Betamax(tape = "DPSClient_shouldThrowExceptionForStatisticsWhenTopologyDoesNotExist") public void shouldThrowExceptionForStatistics() throws DpsException { dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); dpsClient.getTas... |
DpsClient { public void cleanMetisIndexingDataset(String topologyName, long taskId, DataSetCleanerParameters dataSetCleanerParameters) throws DpsException { Response resp = null; try { resp = client.target(dpsUrl) .path(TASK_CLEAN_DATASET_URL) .resolveTemplate(TOPOLOGY_NAME, topologyName) .resolveTemplate(TASK_ID, task... | @Test @Betamax(tape = "DPSClient_shouldCleanIndexingDataSet") public void shouldCleanIndexingDataSet() throws DpsException { DpsClient dpsClient = new DpsClient(BASE_URL, REGULAR_USER_NAME, REGULAR_USER_PASSWORD); dpsClient.cleanMetisIndexingDataset(TOPOLOGY_NAME, TASK_ID, new DataSetCleanerParameters()); }
@Test(expec... |
XmlXPath { InputStream xpathToStream(XPathExpression expr) throws HarvesterException { try { final InputSource inputSource = getInputSource(); final ArrayList<NodeInfo> result = (ArrayList<NodeInfo>) expr.evaluate(inputSource, XPathConstants.NODESET); return convertToStream(result); } catch (XPathExpressionException | ... | @Test public void shouldFilterOaiDcResponse() throws IOException, HarvesterException { final String fileContent = WiremockHelper.getFileContent("/sampleOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); final InputStre... |
CassandraHelper { public static ResultSet getPrimaryKeysFromSourceTable(CassandraConnectionProvider cassandraConnectionProvider, String sourceTableName, List<String> primaryKeys) { String selectPrimaryKeysFromSourceTable = CQLBuilder.constructSelectPrimaryKeysFromSourceTable(sourceTableName, primaryKeys); PreparedState... | @Test public void getPrimaryKeysFromSourceTableTest() { ResultSet resultSet = mock(ResultSet.class); when(session.execute(boundStatement)).thenReturn(resultSet); assertThat(CassandraHelper.getPrimaryKeysFromSourceTable(cassandraConnectionProvider, "table", primaryKeys), is(resultSet)); } |
XmlXPath { String xpathToString(XPathExpression expr) throws HarvesterException { try { return evaluateExpression(expr); } catch (XPathExpressionException e) { throw new HarvesterException("Cannot xpath XML!", e); } } XmlXPath(String input); } | @Test public void shouldReturnRecordIsDeleted() throws IOException, HarvesterException { final String fileContent = WiremockHelper.getFileContent("/deletedOaiRecord.xml"); final InputStream inputStream = IOUtils.toInputStream(fileContent, ENCODING); String content = IOUtils.toString(inputStream, ENCODING); assertEquals... |
HarvesterImpl implements Harvester { @Override public InputStream harvestRecord(String oaiPmhEndpoint, String recordId, String metadataPrefix, XPathExpression expression, XPathExpression statusCheckerExpression) throws HarvesterException { return harvestRecord(DEFAULT_CONNECTION_FACTORY, oaiPmhEndpoint, recordId, metad... | @Test public void shouldHarvestRecord() throws IOException, HarvesterException { stubFor(get(urlEqualTo("/oai-phm/?verb=GetRecord&identifier=mediateka" + "&metadataPrefix=oai_dc")) .willReturn(response200XmlContent(getFileContent("/sampleOaiRecord.xml")) )); final HarvesterImpl harvester = new HarvesterImpl(DEFAULT_RET... |
TopologyManager { public List<String> getNames() { return topologies; } TopologyManager(final String nameList); List<String> getNames(); boolean containsTopology(String topologyName); static final String separatorChar; static final Logger logger; } | @Test public void should_successfully_getTopologyNames() { List<String> resultNameList = instance.getNames(); List<String> expectedNameList = convertStringToList(nameList); assertThat(resultNameList, is(equalTo(expectedNameList))); } |
TopologyManager { public boolean containsTopology(String topologyName) { return topologies.contains(topologyName); } TopologyManager(final String nameList); List<String> getNames(); boolean containsTopology(String topologyName); static final String separatorChar; static final Logger logger; } | @Test public void should_successfully_containsTopology1() { final String topologyName = "topologyA"; boolean result = instance.containsTopology(topologyName); assertThat(result, is(equalTo(true))); }
@Test public void should_successfully_containsTopology2() { final String topologyName = "topologyB"; boolean result = in... |
CassandraHelper { public static List<String> getPrimaryKeysNames(CassandraConnectionProvider cassandraConnectionProvider, String tableName, String selectColumnNames) { List<String> names = new LinkedList<>(); PreparedStatement selectStatement = cassandraConnectionProvider.getSession().prepare(selectColumnNames); select... | @Test public void getPrimaryKeysNamesTest() { ResultSet resultSet = mock(ResultSet.class); when(preparedStatement.bind(anyString(), anyString())).thenReturn(boundStatement); when(session.execute(boundStatement)).thenReturn(resultSet); Iterator iterator = mock(Iterator.class); when(resultSet.iterator()).thenReturn(itera... |
SimplifiedRepresentationResource { @GetMapping @PostAuthorize("hasPermission" + "( " + " (returnObject.cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") public @ResponseBody Representation getRepresentation( Ht... | @Test(expected = ProviderNotExistsException.class) public void exceptionShouldBeThrowForNotExistingProviderId() throws RepresentationNotExistsException, ProviderNotExistsException, RecordNotExistsException { representationResource.getRepresentation(null, NOT_EXISTING_PROVIDER_ID, "localID", "repName"); }
@Test(expected... |
SimplifiedFileAccessResource { @GetMapping public ResponseEntity<StreamingResponseBody> getFile( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName) throws RepresentationNotE... | @Test(expected = RecordNotExistsException.class) public void exceptionShouldBeThrownWhenProviderIdDoesNotExist() throws RecordNotExistsException, FileNotExistsException, WrongContentRangeException, RepresentationNotExistsException, ProviderNotExistsException { fileAccessResource.getFile(null, NOT_EXISTING_PROVIDER_ID, ... |
CQLBuilder { public static String constructSelectPrimaryKeysFromSourceTable(String sourceTableName, List<String> primaryKeyNames) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT "); for (int i = 0; i < primaryKeyNames.size() - 1; i++) stringBuilder.append(primaryKeyNames.get(i)).append... | @Test public void shouldReturnTheExpectedPrimaryKeysSelectionCQL() { assertEquals(EXPECTED_PRIMARY_KEYS_SELECTION_STATEMENT, CQLBuilder.constructSelectPrimaryKeysFromSourceTable(SOURCE_TABLE, primaryKeys)); } |
SimplifiedFileAccessResource { @RequestMapping(method = RequestMethod.HEAD) public ResponseEntity<?> getFileHeaders( HttpServletRequest httpServletRequest, @PathVariable final String providerId, @PathVariable final String localId, @PathVariable final String representationName, @PathVariable final String fileName) throw... | @Test public void fileHeadersShouldBeReadSuccessfully() throws FileNotExistsException, RecordNotExistsException, ProviderNotExistsException, RepresentationNotExistsException, URISyntaxException { setupUriInfo(); ResponseEntity<?> response = fileAccessResource.getFileHeaders(URI_INFO, EXISTING_PROVIDER_ID, EXISTING_LOCA... |
RepresentationVersionsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public RepresentationsListWrapper listVersions( final HttpServletRequest request, @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExis... | @Test @Parameters(method = "mimeTypes") public void testListVersions(MediaType mediaType) throws Exception { List<Representation> expected = copy(REPRESENTATIONS); Representation expectedRepresentation = expected.get(0); URITools.enrich(expectedRepresentation, getBaseUri()); when(recordService.listRepresentationVersion... |
SimplifiedRecordsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public @ResponseBody Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String providerId, @PathVariable String localId) throws RecordNotExistsException, ProviderNotExistsException... | @Test(expected = ProviderNotExistsException.class) public void exceptionShouldBeThrowForNotExistingProviderId() throws RecordNotExistsException, ProviderNotExistsException { recordsResource.getRecord(null, NOT_EXISTING_PROVIDER_ID, "anyLocalId"); }
@Test(expected = RecordNotExistsException.class) public void exceptionS... |
RepresentationVersionResource { @GetMapping(value = REPRESENTATION_VERSION, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', r... | @Test @Parameters(method = "mimeTypes") public void testGetRepresentationVersion(MediaType mediaType) throws Exception { Representation expected = new Representation(representation); URITools.enrich(expected, getBaseUri()); when(recordService.getRepresentation(globalId, schema, version)).thenReturn(new Representation(r... |
RepresentationVersionResource { @DeleteMapping(value = REPRESENTATION_VERSION) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', delete)") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteRepresentat... | @Test public void testDeleteRepresentation() throws Exception { mockMvc.perform(delete(URITools.getVersionPath(globalId, schema, version))) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRepresentation(globalId, schema, version); verifyNoMoreInteractions(recordService); }
@Test @Parameters(me... |
CQLBuilder { public static String getMatchCountStatementFromTargetTable(String targetTableName, List<String> names) { String wherePart = getStringWherePart(names); StringBuilder selectStatementFromTargetTableBuilder = new StringBuilder(); selectStatementFromTargetTableBuilder.append("Select count(*) from ").append(targ... | @Test public void shouldReturnTheExpectedCountStatement() { assertEquals(EXPECTED_COUNT_STATEMENT, CQLBuilder.getMatchCountStatementFromTargetTable(SOURCE_TABLE, primaryKeys)); } |
RepresentationVersionResource { @PostMapping(value = REPRESENTATION_VERSION_PERSIST) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', write)") public ResponseEntity<Void> persistRepresentation( HttpServletR... | @Test public void testPersistRepresentation() throws Exception { when(recordService.persistRepresentation(globalId, schema, version)).thenReturn( new Representation(representation)); mockMvc.perform(post(persistPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isCreated()) .andExpect(header(... |
RepresentationVersionResource { @PostMapping(value = REPRESENTATION_VERSION_COPY) @PreAuthorize("hasPermission(#cloudId.concat('/').concat(#representationName).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)") public ResponseEntity<Void> copyRepresentation( HttpServletRequest ... | @Test public void testCopyRepresentation() throws Exception { when(recordService.copyRepresentation(globalId, schema, version)) .thenReturn(new Representation(representation)); mockMvc.perform(post(copyPath).contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isCreated()) .andExpect(header().string(... |
RecordsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public Record getRecord( HttpServletRequest httpServletRequest, @PathVariable String cloudId) throws RecordNotExistsException { Record record = recordService.getRecord(cloudId); prepare(httpServle... | @Test @Parameters(method = "mimeTypes") public void getRecord(MediaType mediaType) throws Exception { String globalId = "global1"; Record record = new Record(globalId, Lists.newArrayList(new Representation(globalId, "DC", "1", null, null, "FBC", Lists.newArrayList(new File("dc.xml", "text/xml", "91162629d258a876ee994e9... |
RecordsResource { @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") public void deleteRecord( @PathVariable String cloudId) throws RecordNotExistsException, RepresentationNotExistsException { recordService.deleteRecord(cloudId); } RecordsResource(RecordService recordService); ... | @Test public void deleteRecord() throws Exception { String globalId = "global1"; mockMvc.perform(delete("/records/" + globalId)) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRecord(globalId); verifyNoMoreInteractions(recordService); }
@Test public void deleteRecordReturns404IfRecordDoesNotE... |
DataSetsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public ResultSlice<DataSet> getDataSets( @PathVariable String providerId, @RequestParam(required = false) String startFrom) { return dataSetService.getDataSets(providerId, startFrom, numberOfElem... | @Test public void shouldCreateDataset() throws Exception { Mockito.doReturn(new DataProvider()).when(uisHandler) .getProvider("provId"); String datasetId = "datasetId"; String description = "dataset description"; ResultActions createResponse = mockMvc.perform(post(dataSetsWebTarget, "provId").contentType(MediaType.APPL... |
MigrationExecutor { public void migrate() { CassandraMigration cm = new CassandraMigration(); cm.getConfigs().setScriptsLocations(scriptsLocations); cm.setKeyspace(keyspace); cm.migrate(); } MigrationExecutor(String cassandraKeyspace, String cassandraContactPoint, int cassandraPort, String cassandraUsername, String cas... | @Test public void shouldSuccessfullyMigrateData() { MigrationExecutor migrator = new MigrationExecutor(EmbeddedCassandra.KEYSPACE, contactPoint, EmbeddedCassandra.PORT, cassandraUsername, cassandraPassword, scriptsLocations); migrator.migrate(); validateMigration(); List<String> cloudIds = getCloudIds(session.execute("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.