method2testcases stringlengths 118 3.08k |
|---|
### Question:
RecordApi extends BaseProvider implements RecordProvider { @Override public void checkRecordExists(String id) throws OaiPmhException { ResponseEntity<String> response = getResponseForRecord(id); if (response == null) { throw new IdDoesNotExistException("Record with id '" + id + "' not found"); } } @Override Record getRecord(String id); @Override void checkRecordExists(String id); @Override ListRecords listRecords(List<Header> identifiers); void close(); }### Answer:
@Test public void checkRecordExists() throws OaiPmhException { Mockito.doNothing().when(recordApi).checkRecordExists(TEST_RECORD_ID); recordApi.checkRecordExists(TEST_RECORD_ID); }
@Test(expected = IdDoesNotExistException.class) public void checkRecordExistsWithWrongIdentifier() throws OaiPmhException { Mockito.doThrow(new IdDoesNotExistException("INCORRECT/ID")).when(recordApi).checkRecordExists("INCORRECT/ID"); recordApi.checkRecordExists("INCORRECT/ID"); fail(); } |
### Question:
ResumptionTokenHelper { public static long getCompleteListSize(String token) { return Long.parseLong(tokenize(token)[COMPLETE_LIST_SIZE_INDEX]); } private ResumptionTokenHelper(); static ResumptionToken createResumptionToken(String from,
String until,
String set,
String format,
Date expirationDate,
long completeListSize,
long cursor,
String nextCursorMark); static ResumptionToken createResumptionToken(Date expirationDate,
long completeListSize,
long cursor); static ResumptionToken decodeResumptionToken(String base64EncodedToken); static String getFrom(String token); static String getUntil(String token); static String getSet(String token); static String getFormat(String token); static Date getExpirationDate(String token); static long getCompleteListSize(String token); static long getCursor(String token); static String getCursorMark(String token); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testGetPartFromIncorrectToken() { ResumptionTokenHelper.getCompleteListSize(INCORRECT_DECODED_TOKEN); } |
### Question:
DefaultIdentifyProvider extends SolrBasedProvider implements IdentifyProvider { @Override public Identify provideIdentify() throws OaiPmhException { Identify identify = new Identify(); identify.setBaseURL(baseURL); identify.setAdminEmail(adminEmail); identify.setCompression(compression); identify.setDeletedRecord(deletedRecord); identify.setEarliestDatestamp(getEarliestTimestamp()); identify.setGranularity(granularity); identify.setProtocolVersion(protocolVersion); identify.setRepositoryName(repositoryName); return identify; } @Override Identify provideIdentify(); }### Answer:
@Test public void provideIdentify() throws OaiPmhException, IOException, SolrServerException { QueryResponse response = getResponse(IDENTIFY); Mockito.when(solrClient.query(Mockito.any(SolrParams.class))).thenReturn(response); Identify identify = defaultIdentifyProvider.provideIdentify(); assertEquals(REPOSITORY_NAME, identify.getRepositoryName()); assertEquals(BASE_URL, identify.getBaseURL()); assertEquals(PROTOCOL_VERSION, identify.getProtocolVersion()); assertEquals(EARLIEST_DATESTAMP, identify.getEarliestDatestamp()); assertEquals(DELETED_RECORD, identify.getDeletedRecord()); assertEquals(1, identify.getAdminEmail().length); assertEquals(ADMIN_EMAIL, identify.getAdminEmail()[0]); assertEquals(1, identify.getCompression().length); assertEquals(COMPRESSION, identify.getCompression()[0]); } |
### Question:
OaiPmhRequestFactory { public static IdentifyRequest createIdentifyRequest(String baseUrl) { return new IdentifyRequest(Identify.class.getSimpleName(), baseUrl); } private OaiPmhRequestFactory(); static void validateVerb(String verb); static void validateParameterNames(String request); static OAIRequest createRequest(String baseUrl, String request, boolean ignoreErrors); static ListSetsRequest createListSetsRequest(String baseUrl, String resumptionToken); static ListSetsRequest createListSetsRequest(String baseUrl, String from, String until); static ListIdentifiersRequest createListIdentifiersRequest(String baseUrl, String metadataPrefix, String set, String from, String until); static ListIdentifiersRequest createListIdentifiersRequest(String baseUrl, String resumptionToken); static IdentifyRequest createIdentifyRequest(String baseUrl); static GetRecordRequest createGetRecordRequest(String baseUrl, String metadataPrefix, String identifier); static ListMetadataFormatsRequest createListMetadataFormatsRequest(String baseUrl, String identifier); static ListRecordsRequest createListRecordsRequest(String baseUrl, String metadataPrefix, String set, String from, String until); static ListRecordsRequest createListRecordsRequest(String baseUrl, String resumptionToken); }### Answer:
@Test public void createIdentifyRequest() { OAIRequest request = OaiPmhRequestFactory.createIdentifyRequest(BASE_URL); assertIdentify(request); } |
### Question:
DBRecordProvider extends BaseProvider implements RecordProvider, ConnectionPoolListener { @Override @TrackTime public Record getRecord(String id) throws OaiPmhException { String recordId = prepareRecordId(id); FullBean bean = getFullBean(recordId); return new Record(getHeader(id, bean), prepareRDFMetadata(recordId, (FullBeanImpl) bean)); } @Override void connectionPoolOpened(ConnectionPoolOpenedEvent connectionPoolOpenedEvent); @Override void connectionPoolClosed(ConnectionPoolClosedEvent connectionPoolClosedEvent); @Override void connectionCheckedOut(ConnectionCheckedOutEvent connectionCheckedOutEvent); @Override void connectionCheckedIn(ConnectionCheckedInEvent connectionCheckedInEvent); @Override void waitQueueEntered(ConnectionPoolWaitQueueEnteredEvent connectionPoolWaitQueueEnteredEvent); @Override void waitQueueExited(ConnectionPoolWaitQueueExitedEvent connectionPoolWaitQueueExitedEvent); @Override synchronized void connectionAdded(ConnectionAddedEvent connectionAddedEvent); @Override synchronized void connectionRemoved(ConnectionRemovedEvent connectionRemovedEvent); @Override @TrackTime Record getRecord(String id); @Override void checkRecordExists(String id); @TrackTime String getEDM(RDF rdf); @TrackTime RDF getRDF(FullBeanImpl bean); @Override ListRecords listRecords(List<Header> identifiers); @Override @PreDestroy void close(); }### Answer:
@Test public void getRecord() throws IOException, EuropeanaException, OaiPmhException { String record = loadRecord(); prepareTest(record); Record preparedRecord = prepareRecord(record); Record retrievedRecord = recordProvider.getRecord(TEST_RECORD_ID); Assert.assertNotNull(retrievedRecord); assertRecordEquals(retrievedRecord, preparedRecord); } |
### Question:
DBRecordProvider extends BaseProvider implements RecordProvider, ConnectionPoolListener { @Override public void checkRecordExists(String id) throws OaiPmhException { String recordId = prepareRecordId(id); FullBean bean = getFullBean(recordId); if (bean == null) { throw new IdDoesNotExistException("Record with identifier " + id + " not found!"); } } @Override void connectionPoolOpened(ConnectionPoolOpenedEvent connectionPoolOpenedEvent); @Override void connectionPoolClosed(ConnectionPoolClosedEvent connectionPoolClosedEvent); @Override void connectionCheckedOut(ConnectionCheckedOutEvent connectionCheckedOutEvent); @Override void connectionCheckedIn(ConnectionCheckedInEvent connectionCheckedInEvent); @Override void waitQueueEntered(ConnectionPoolWaitQueueEnteredEvent connectionPoolWaitQueueEnteredEvent); @Override void waitQueueExited(ConnectionPoolWaitQueueExitedEvent connectionPoolWaitQueueExitedEvent); @Override synchronized void connectionAdded(ConnectionAddedEvent connectionAddedEvent); @Override synchronized void connectionRemoved(ConnectionRemovedEvent connectionRemovedEvent); @Override @TrackTime Record getRecord(String id); @Override void checkRecordExists(String id); @TrackTime String getEDM(RDF rdf); @TrackTime RDF getRDF(FullBeanImpl bean); @Override ListRecords listRecords(List<Header> identifiers); @Override @PreDestroy void close(); }### Answer:
@Test public void checkRecordExists() throws EuropeanaException, OaiPmhException { FullBeanImpl bean = mock(FullBeanImpl.class); given(mongoServer.getFullBean(anyString())).willReturn(bean); recordProvider.checkRecordExists(TEST_RECORD_ID); } |
### Question:
DefaultSetsProvider extends SolrBasedProvider implements SetsProvider { @Override public ListSets listSets(Date from, Date until) throws OaiPmhException { QueryResponse response = executeQuery(SolrQueryBuilder.listSets(setsPerPage, from, until, 0)); FieldStatsInfo info = response.getFieldStatsInfo().get(DATASET_NAME); if (info == null) { throw new InternalServerErrorException("An error occurred while retrieving information from the index."); } return responseToListSets(response, 0, info.getCountDistinct()); } @Override ListSets listSets(Date from, Date until); @Override ListSets listSets(ResumptionToken resumptionToken); }### Answer:
@Test public void listSets() throws IOException, SolrServerException, OaiPmhException { QueryResponse response = getResponse(LIST_SETS); Mockito.when(solrClient.query(Mockito.any(SolrParams.class))).thenReturn(response); ListSets result = setsProvider.listSets(null, null); assertResults(result); }
@Test public void listSetsFrom() throws IOException, SolrServerException, OaiPmhException { QueryResponse response = getResponse(LIST_SETS_FROM); Mockito.when(solrClient.query(Mockito.any(SolrParams.class))).thenReturn(response); Date from = DateConverter.fromIsoDateTime(DATE_1); ListSets result = setsProvider.listSets(from, null); assertResults(result); }
@Test public void listSetsWithResumptionToken() throws IOException, SolrServerException, OaiPmhException { QueryResponse response = getResponse(LIST_SETS_WITH_RESUMPTION_TOKEN_SECOND_PAGE); Mockito.when(solrClient.query(Mockito.any(SolrParams.class))).thenReturn(response); ResumptionToken token = ResumptionTokenHelper.createResumptionToken(new Date(System.currentTimeMillis() + RESUMPTION_TOKEN_TTL), COMPLETE_LIST_SIZE, 0); ListSets result = setsProvider.listSets(token); assertResults(result); } |
### Question:
Utils { public static String getSymbol(String pSymbol) { int sep = pSymbol.indexOf('_'); if (sep > 0) { return pSymbol.substring(0, sep) + pSymbol.substring(sep + 1, pSymbol.length()); } else { return pSymbol.substring(0, pSymbol.length() - 3) + pSymbol.substring(pSymbol.length() - 3, pSymbol.length()); } } private Utils(); static String getSymbol(String pSymbol); static String getSymbol1(String pSymbol); static String getSymbol2(String pSymbol); static BigDecimal parseDecimal(String pString); static String formatDecimal(BigDecimal pDecimal); static String formatPrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scalePrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scaleQuantity(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static void sleep(long pMillis); static String iconUrl(String pSymbol); static String formatEnum(Enum pEnum); static int getQuantityScale(String pSymbol, ExchangeInfo pExchangeInfo); static int getPriceScale(String pSymbol, ExchangeInfo pExchangeInfo); }### Answer:
@Test public void testGetSymbol() { assertEquals("symbol wrong", "NEOETH", Utils.getSymbol("NEOETH")); assertEquals("symbol wrong", "IOSTETH", Utils.getSymbol("IOSTETH")); assertEquals("symbol wrong", "NEOETH", Utils.getSymbol("NEO_ETH")); assertEquals("symbol wrong", "IOSTETH", Utils.getSymbol("IOST_ETH")); assertEquals("symbol wrong", "BTCUSDT", Utils.getSymbol("BTC_USDT")); assertEquals("symbol wrong", "BTCUSDT", Utils.getSymbol("BTCUSDT")); } |
### Question:
Utils { public static String getSymbol1(String pSymbol) { int sep = pSymbol.indexOf('_'); if (sep > 0) { return pSymbol.substring(0, sep); } else { int i = pSymbol.endsWith("USDT") ? 4 : 3; return pSymbol.substring(0, pSymbol.length() - i); } } private Utils(); static String getSymbol(String pSymbol); static String getSymbol1(String pSymbol); static String getSymbol2(String pSymbol); static BigDecimal parseDecimal(String pString); static String formatDecimal(BigDecimal pDecimal); static String formatPrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scalePrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scaleQuantity(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static void sleep(long pMillis); static String iconUrl(String pSymbol); static String formatEnum(Enum pEnum); static int getQuantityScale(String pSymbol, ExchangeInfo pExchangeInfo); static int getPriceScale(String pSymbol, ExchangeInfo pExchangeInfo); }### Answer:
@Test public void testGetSymbol1() { assertEquals("symbol1 wrong", "NEO", Utils.getSymbol1("NEOETH")); assertEquals("symbol1 wrong", "IOST", Utils.getSymbol1("IOSTETH")); assertEquals("symbol1 wrong", "NEO", Utils.getSymbol1("NEO_ETH")); assertEquals("symbol1 wrong", "IOST", Utils.getSymbol1("IOST_ETH")); assertEquals("symbol1 wrong", "BTC", Utils.getSymbol1("BTC_USDT")); assertEquals("symbol1 wrong", "BTC", Utils.getSymbol1("BTCUSDT")); } |
### Question:
Utils { public static String getSymbol2(String pSymbol) { int sep = pSymbol.indexOf('_'); if (sep > 0) { return pSymbol.substring(sep + 1, pSymbol.length()); } else { int i = pSymbol.endsWith("USDT") ? 4 : 3; return pSymbol.substring(pSymbol.length() - i, pSymbol.length()); } } private Utils(); static String getSymbol(String pSymbol); static String getSymbol1(String pSymbol); static String getSymbol2(String pSymbol); static BigDecimal parseDecimal(String pString); static String formatDecimal(BigDecimal pDecimal); static String formatPrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scalePrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scaleQuantity(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static void sleep(long pMillis); static String iconUrl(String pSymbol); static String formatEnum(Enum pEnum); static int getQuantityScale(String pSymbol, ExchangeInfo pExchangeInfo); static int getPriceScale(String pSymbol, ExchangeInfo pExchangeInfo); }### Answer:
@Test public void testGetSymbol2() { assertEquals("symbol2 wrong", "ETH", Utils.getSymbol2("NEOETH")); assertEquals("symbol2 wrong", "ETH", Utils.getSymbol2("IOSTETH")); assertEquals("symbol2 wrong", "ETH", Utils.getSymbol2("NEO_ETH")); assertEquals("symbol2 wrong", "ETH", Utils.getSymbol2("IOST_ETH")); assertEquals("symbol2 wrong", "USDT", Utils.getSymbol2("BTC_USDT")); assertEquals("symbol2 wrong", "USDT", Utils.getSymbol2("BTCUSDT")); } |
### Question:
Utils { public static String formatDecimal(BigDecimal pDecimal) { if (pDecimal == null) { return "null"; } return decFmt.format(pDecimal); } private Utils(); static String getSymbol(String pSymbol); static String getSymbol1(String pSymbol); static String getSymbol2(String pSymbol); static BigDecimal parseDecimal(String pString); static String formatDecimal(BigDecimal pDecimal); static String formatPrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scalePrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scaleQuantity(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static void sleep(long pMillis); static String iconUrl(String pSymbol); static String formatEnum(Enum pEnum); static int getQuantityScale(String pSymbol, ExchangeInfo pExchangeInfo); static int getPriceScale(String pSymbol, ExchangeInfo pExchangeInfo); }### Answer:
@Test public void testFormatDecimal() { assertEquals("0.00012345", Utils.formatDecimal(BigDecimal.valueOf(0.00012345d))); assertEquals("10.00012345", Utils.formatDecimal(BigDecimal.valueOf(10.00012345d))); assertEquals("0.00012346", Utils.formatDecimal(BigDecimal.valueOf(0.000123459d))); assertEquals("10.00000000", Utils.formatDecimal(BigDecimal.valueOf(10))); } |
### Question:
Utils { protected static String roundToTickSize(BigDecimal pDecimal, String tickSize) { int precision = tickSize.indexOf('1') - 1; return priceFmt.format(pDecimal.setScale(precision, RoundingMode.FLOOR)); } private Utils(); static String getSymbol(String pSymbol); static String getSymbol1(String pSymbol); static String getSymbol2(String pSymbol); static BigDecimal parseDecimal(String pString); static String formatDecimal(BigDecimal pDecimal); static String formatPrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scalePrice(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static String formatQuantity(BigDecimal pQuantity, String pSymbol, ExchangeInfo pExchangeInfo); static BigDecimal scaleQuantity(BigDecimal pDecimal, String pSymbol, ExchangeInfo pExchangeInfo); static void sleep(long pMillis); static String iconUrl(String pSymbol); static String formatEnum(Enum pEnum); static int getQuantityScale(String pSymbol, ExchangeInfo pExchangeInfo); static int getPriceScale(String pSymbol, ExchangeInfo pExchangeInfo); }### Answer:
@Test public void testRoundToTickSize() { assertEquals("0.12345", Utils.roundToTickSize(BigDecimal.valueOf(0.123456789d), "0.00001")); assertEquals("0.12345", Utils.roundToTickSize(BigDecimal.valueOf(0.12345111d), "0.00001")); assertEquals("0.123", Utils.roundToTickSize(BigDecimal.valueOf(0.12345111d), "0.001")); } |
### Question:
Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } int evaluate(String expression); }### Answer:
@Test public void evaluatesExpression() { Calculator calculator = new Calculator(); int sum = calculator.evaluate("1+2+3"); assertEquals(6, sum); } |
### Question:
User implements Serializable { public String getUsername() { return username; } User(String username); String getUsername(); void setUsername(String username); void listenToMessages(MessageReceivedObserver observer); void receiveMessage(Message message); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void usernameTest() { assertEquals("john", john.getUsername()); } |
### Question:
User implements Serializable { public void receiveMessage(Message message) { for (MessageReceivedObserver observer : observers) { observer.onMessage(message); } } User(String username); String getUsername(); void setUsername(String username); void listenToMessages(MessageReceivedObserver observer); void receiveMessage(Message message); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void receiveMessage() { User carl = new User("carl"); when(group.getName()).thenReturn("mocked-group"); john.listenToMessages(receiver); Message message = new Message(group, carl, "Hello everybody!"); john.receiveMessage(message); Message received = receiver.get(); assertEquals(message, received); }
@Test public void receiveMessageTest() { User carl = new User("carl"); when(group.getName()).thenReturn("mocked-group"); john.listenToMessages(receiver); Message message = new Message(group, carl, "Hello everybody!"); john.receiveMessage(message); Message received = receiver.get(); assertEquals(message, received); } |
### Question:
Group implements Serializable { public void sendMessage(Message message) throws UserNotInGroupException { checkUserInGroup(message.getSender()); messages.add(message); for (User user : users) { user.receiveMessage(message); } } Group(); int size(); void sendMessage(Message message); String getName(); void setName(String name); void join(User user); void leave(User user); boolean in(User user); Set<User> users(); void observe(GroupChangeListener listener); List<Message> messages(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void sendMessage() { System.out.println(john); group.join(john); group.join(carl); group.join(mark); Message m = new Message(group, john, "hello"); group.sendMessage(m); List<Message> messages = group.messages(); List<Message> expected = Collections.singletonList(m); assertThat(messages, is(expected)); verify(john).receiveMessage(m); verify(carl).receiveMessage(m); verify(mark).receiveMessage(m); }
@Test(expected = UserNotInGroupException.class) public void testIllegalMessage() throws RemoteException { Message message = new Message(group, john, "hello"); group.sendMessage(message); } |
### Question:
ResteasyAutoConfiguration { @Bean @Qualifier("ResteasyProviderFactory") public static BeanFactoryPostProcessor springBeanProcessor() { ResteasyProviderFactory resteasyProviderFactory = ResteasyProviderFactory.newInstance(); ResourceMethodRegistry resourceMethodRegistry = new ResourceMethodRegistry(resteasyProviderFactory); SpringBeanProcessor springBeanProcessor = new SpringBeanProcessor(); springBeanProcessor.setProviderFactory(resteasyProviderFactory); springBeanProcessor.setRegistry(resourceMethodRegistry); logger.debug("SpringBeanProcessor has been created"); return springBeanProcessor; } @Bean @ConditionalOnProperty(name="resteasy.jaxrs.scan-packages") static JAXRSResourcesAndProvidersScannerPostProcessor providerScannerPostProcessor(); @Bean @Qualifier("ResteasyProviderFactory") static BeanFactoryPostProcessor springBeanProcessor(); @Bean ServletContextListener resteasyBootstrapListener(@Qualifier("ResteasyProviderFactory") final BeanFactoryPostProcessor beanFactoryPostProcessor); @Bean(name = ResteasyApplicationBuilder.BEAN_NAME) ResteasyApplicationBuilder resteasyApplicationBuilder(); @Bean static ResteasyEmbeddedServletInitializer resteasyEmbeddedServletInitializer(); }### Answer:
@Test public void springBeanProcessor() { BeanFactoryPostProcessor beanFactoryPostProcessor = new ResteasyAutoConfiguration().springBeanProcessor(); Assert.assertNotNull(beanFactoryPostProcessor); Assert.assertEquals(SpringBeanProcessor.class, beanFactoryPostProcessor.getClass()); SpringBeanProcessor springBeanProcessor = (SpringBeanProcessor) beanFactoryPostProcessor; Registry springBeanProcessorRegistry = springBeanProcessor.getRegistry(); ResteasyProviderFactory providerFactory = springBeanProcessor.getProviderFactory(); Assert.assertNotNull(springBeanProcessorRegistry); Assert.assertNotNull(providerFactory); Assert.assertEquals(ResourceMethodRegistry.class, springBeanProcessorRegistry.getClass()); } |
### Question:
PropertyUtils { @SuppressWarnings("unchecked") public static <T> T transform(Class<T> type, String value) throws IllegalArgumentException { if (!VALUE_TRANSFORMER.containsKey(type)) { throw new IllegalArgumentException("unsupported parameter type: " + type); } return (T) VALUE_TRANSFORMER.get(type).apply(value); } private PropertyUtils(); @SuppressWarnings("unchecked") static T transform(Class<T> type, String value); static void main(String[] args); }### Answer:
@Test(dataProvider = "testTransformProvider") public void testTransform(Class<?> type, String val) { Object result = transform(type, val); assertTrue(type.isAssignableFrom(result.getClass())); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testUnsupportedTypeTransform() { transform(Map.class, ""); } |
### Question:
PlaylistViewModel extends BaseViewModel { public LiveData<List<Playlist>> getPlaylists() { Disposable disposable = playlistRepository.getPlaylists() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(videos -> playlists.setValue(videos)); addToUnsubsribed(disposable); return playlists; } @Inject PlaylistViewModel(PlaylistRepository playlistRepository, PlaylistItemRepository playlistItemRepository); List<Integer> getVideoIdsToAdd(); void setVideoIdsToAdd(List<Integer> videoIdsToAdd); LiveData<List<Playlist>> getPlaylists(); void addPlayList(String title); void addVideosToPlaylist(List<Integer> videoIds, int playlistId); void deletePlayList(int playlistId); }### Answer:
@Test public void getPlaylists_shouldReturnExactListFromRepository() { List<Playlist> playlistLists = playlistViewModel.getPlaylists().getValue(); TestUtil.assertEqualsPlayLists(mockPlaylists, playlistLists); } |
### Question:
StorageUtil { public List<Video> getAllVideos(){ return readFromMediaStore(true, null); } @Inject StorageUtil(ContentResolver contentResolver); List<Video> getAllVideos(); List<Video> getVideosForIds(String[] videoIds); }### Answer:
@Test public void getAllVideos_returnsAllTheItems() throws Exception { List<Video> videoList = storageUtil.getAllVideos(); TestUtil.assertEqualsVideoLists(originalList, videoList); } |
### Question:
VideoRepository { public Observable<List<Video>> getVideoList(){ return Observable.fromCallable(() -> storageUtil.getAllVideos()); } @Inject VideoRepository(StorageUtil storageUtil, PlaylistItemDao playlistItemDao); Observable<List<Video>> getVideoList(); Observable<List<Video>> getPlaylistVideos(int playListId); }### Answer:
@Test public void getVideoList_returnsExactListFromStorageUtil() { List<Video> videoList = videoRepository.getVideoList().blockingFirst(); TestUtil.assertEqualsVideoLists(videoList, this.mockVideoList); } |
### Question:
PlaylistViewModel extends BaseViewModel { public void addPlayList(String title){ Playlist playList = new Playlist(title); playlistRepository.addPlaylist(playList) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } @Inject PlaylistViewModel(PlaylistRepository playlistRepository, PlaylistItemRepository playlistItemRepository); List<Integer> getVideoIdsToAdd(); void setVideoIdsToAdd(List<Integer> videoIdsToAdd); LiveData<List<Playlist>> getPlaylists(); void addPlayList(String title); void addVideosToPlaylist(List<Integer> videoIds, int playlistId); void deletePlayList(int playlistId); }### Answer:
@Test public void addPlayList_callsTheRepository() { playlistViewModel.addPlayList("Playlist one"); verify(playlistRepository, times(1)).addPlaylist(any()); } |
### Question:
PlaylistViewModel extends BaseViewModel { public void deletePlayList(int playlistId){ playlistRepository.deletePlayList(playlistId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } @Inject PlaylistViewModel(PlaylistRepository playlistRepository, PlaylistItemRepository playlistItemRepository); List<Integer> getVideoIdsToAdd(); void setVideoIdsToAdd(List<Integer> videoIdsToAdd); LiveData<List<Playlist>> getPlaylists(); void addPlayList(String title); void addVideosToPlaylist(List<Integer> videoIds, int playlistId); void deletePlayList(int playlistId); }### Answer:
@Test public void deletePlaylists_callsTheRepositoryOnce() { playlistViewModel.deletePlayList(2); verify(playlistRepository, times(1)).deletePlayList(2); } |
### Question:
PlaylistViewModel extends BaseViewModel { public void addVideosToPlaylist(List<Integer> videoIds, int playlistId){ playlistItemRepository.addVideoToPlayList(videoIds, playlistId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } @Inject PlaylistViewModel(PlaylistRepository playlistRepository, PlaylistItemRepository playlistItemRepository); List<Integer> getVideoIdsToAdd(); void setVideoIdsToAdd(List<Integer> videoIdsToAdd); LiveData<List<Playlist>> getPlaylists(); void addPlayList(String title); void addVideosToPlaylist(List<Integer> videoIds, int playlistId); void deletePlayList(int playlistId); }### Answer:
@Test public void addVideoToPlaylists_callsTheRepoWithExactParameters(){ List<Integer> videoIds = new ArrayList<>(); playlistViewModel.addVideosToPlaylist(videoIds, 1); verify(playlistItemRepository, times(1)).addVideoToPlayList(videoIds, 1); } |
### Question:
PlayerViewModel extends BaseViewModel { public LiveData<Video> getCurrentVideo() { if(videoId != -1 && videoList.getValue() == null){ loadVideos(); } return currentVideo; } @Inject PlayerViewModel(VideoRepository videoRepository, AudioManager audioManager); void init(int videoId); void init(int videoId, int playlistId); LiveData<Video> getCurrentVideo(); LiveData<Integer> getVolumeValue(); void volumeUp(); void volumeDown(); void next(); void prev(); }### Answer:
@Test public void dontFetchWithoutVideoId(){ viewModel.getCurrentVideo().observeForever(mock(Observer.class)); verify(videoRepository, never()).getVideoList(); } |
### Question:
PlayerViewModel extends BaseViewModel { public void volumeDown(){ audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND); setCurrentVolumeVolume(); } @Inject PlayerViewModel(VideoRepository videoRepository, AudioManager audioManager); void init(int videoId); void init(int videoId, int playlistId); LiveData<Video> getCurrentVideo(); LiveData<Integer> getVolumeValue(); void volumeUp(); void volumeDown(); void next(); void prev(); }### Answer:
@Test public void volumeDown() throws Exception { Observer observer = mock(Observer.class); viewModel.getVolumeValue().observeForever(observer); currentVolume = 5; viewModel.volumeDown(); verify(observer, times(2)).onChanged(any()); assertTrue(viewModel.getVolumeValue().getValue() == 4); } |
### Question:
PlayerViewModel extends BaseViewModel { public void next(){ if(currentIndex < videoList.getValue().size() -1) currentIndex++; else currentIndex = 0; currentVideo.setValue(videoList.getValue().get(currentIndex)); } @Inject PlayerViewModel(VideoRepository videoRepository, AudioManager audioManager); void init(int videoId); void init(int videoId, int playlistId); LiveData<Video> getCurrentVideo(); LiveData<Integer> getVolumeValue(); void volumeUp(); void volumeDown(); void next(); void prev(); }### Answer:
@Test public void next() throws Exception { final List<Video> videoList = videoRepository.getVideoList().blockingFirst(); viewModel.init(videoList.get(0).getId()); viewModel.getCurrentVideo().observeForever(mock(Observer.class)); viewModel.next(); assertEquals(viewModel.getCurrentVideo().getValue().getId(), videoList.get(1).getId()); } |
### Question:
PlayerViewModel extends BaseViewModel { public void prev(){ if(currentIndex > 0) currentIndex--; else currentIndex = videoList.getValue().size() -1; currentVideo.setValue(videoList.getValue().get(currentIndex)); } @Inject PlayerViewModel(VideoRepository videoRepository, AudioManager audioManager); void init(int videoId); void init(int videoId, int playlistId); LiveData<Video> getCurrentVideo(); LiveData<Integer> getVolumeValue(); void volumeUp(); void volumeDown(); void next(); void prev(); }### Answer:
@Test public void prev() throws Exception { final List<Video> videoList = videoRepository.getVideoList().blockingFirst(); viewModel.init(videoList.get(1).getId()); viewModel.getCurrentVideo().observeForever(mock(Observer.class)); viewModel.prev(); assertEquals(viewModel.getCurrentVideo().getValue().getId(), videoList.get(0).getId()); } |
### Question:
VideoListViewModel extends BaseVideoListViewModel { public LiveData<List<Video>> getVideoList() { return videoList; } @Inject VideoListViewModel(VideoRepository videoRepository); LiveData<List<Video>> getVideoList(); }### Answer:
@Test public void immediatelyFetchesVideos(){ verify(videoRepository, times(1)).getVideoList(); }
@Test public void getDataWhenRepoIsNotEmpty() throws Exception { List<Video> videoList = viewModel.getVideoList().getValue(); assertEquals(2, videoList.size()); TestUtil.assertEqualsVideoLists(videoList, mockVideoList); } |
### Question:
DockerPluginUtils { public static boolean isBlank(String str) { int strLen; if (str != null && (strLen = str.length()) != 0) { for (int i = 0; i < strLen; ++i) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } else { return true; } } static void printError(String msg); static List<BLangRecordLiteral.BLangRecordKeyValueField> getKeyValuePairs(BLangRecordLiteral bLangRecordLiteral); static void printDebug(String msg); static boolean isBlank(String str); static void deleteDirectory(Path pathToBeDeleted); static String resolveValue(String value); static AnnotationAttachmentNode createAnnotation(String annotationName); }### Answer:
@Test public void isBlankTest() { Assert.assertTrue(DockerPluginUtils.isBlank("")); Assert.assertTrue(DockerPluginUtils.isBlank(" ")); Assert.assertTrue(DockerPluginUtils.isBlank(null)); Assert.assertFalse(DockerPluginUtils.isBlank("value")); } |
### Question:
DockerPluginUtils { public static String resolveValue(String value) throws DockerPluginException { int startIndex; if ((startIndex = value.indexOf("$env{")) >= 0) { int endIndex = value.indexOf("}", startIndex); if (endIndex > 0) { String varName = value.substring(startIndex + 5, endIndex).trim(); String resolvedVar = Optional.ofNullable(System.getenv(varName)).orElseThrow(() -> new DockerPluginException("error resolving value: " + varName + " is not set in the environment.")); String rest = (value.length() > endIndex + 1) ? resolveValue(value.substring(endIndex + 1)) : ""; return value.substring(0, startIndex) + resolvedVar + rest; } } return value; } static void printError(String msg); static List<BLangRecordLiteral.BLangRecordKeyValueField> getKeyValuePairs(BLangRecordLiteral bLangRecordLiteral); static void printDebug(String msg); static boolean isBlank(String str); static void deleteDirectory(Path pathToBeDeleted); static String resolveValue(String value); static AnnotationAttachmentNode createAnnotation(String annotationName); }### Answer:
@Test public void resolveValueTest() throws Exception { Map<String, String> env = new HashMap<>(); env.put("DOCKER_USERNAME", "anuruddhal"); setEnv(env); try { Assert.assertEquals(DockerPluginUtils.resolveValue("$env{DOCKER_USERNAME}"), "anuruddhal"); } catch (DockerPluginException e) { Assert.fail("Unable to resolve environment variable"); } try { DockerPluginUtils.resolveValue("$env{DOCKER_PASSWORD}"); Assert.fail("Env value should be resolved"); } catch (DockerPluginException e) { Assert.assertEquals(e.getMessage(), "error resolving value: DOCKER_PASSWORD is not set in the " + "environment."); } Assert.assertEquals(DockerPluginUtils.resolveValue("demo"), "demo"); } |
### Question:
DockerPluginUtils { public static void deleteDirectory(Path pathToBeDeleted) throws DockerPluginException { if (!Files.exists(pathToBeDeleted)) { return; } try { Files.walk(pathToBeDeleted) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { throw new DockerPluginException("Unable to delete directory: " + pathToBeDeleted.toString(), e); } } static void printError(String msg); static List<BLangRecordLiteral.BLangRecordKeyValueField> getKeyValuePairs(BLangRecordLiteral bLangRecordLiteral); static void printDebug(String msg); static boolean isBlank(String str); static void deleteDirectory(Path pathToBeDeleted); static String resolveValue(String value); static AnnotationAttachmentNode createAnnotation(String annotationName); }### Answer:
@Test public void deleteDirectoryTest() throws IOException, DockerPluginException { File file = tempDirectory.resolve("myfile.txt").toFile(); Assert.assertTrue(file.createNewFile()); File directory = tempDirectory.resolve("subFolder").toFile(); Assert.assertTrue(directory.mkdirs()); DockerPluginUtils.deleteDirectory(file.toPath()); Assert.assertFalse(file.exists(), "myfile.txt not deleted"); DockerPluginUtils.deleteDirectory(directory.toPath()); Assert.assertFalse(directory.exists(), "subFolder not deleted"); } |
### Question:
KubernetesUtils { public static String getValidName(String name) { return name.toLowerCase(Locale.getDefault()).replace("_", "-").replace(".", "-"); } static void writeToFile(String context, String outputFileName); static void writeToFile(Path outputDir, String context, String fileSuffix); static byte[] readFileContent(Path targetFilePath); static void copyFileOrDirectory(String source, String destination); static void printInfo(String msg); static void printError(String msg); static void printDebug(String msg); static void printWarning(String message); static void printInstruction(String msg); static void deleteDirectory(Path path); static boolean isBlank(String str); static String resolveValue(String value); static List<String> getList(BLangExpression expr); static Map<String, String> getMap(BLangExpression expr); static boolean getBooleanValue(BLangExpression expr); static long getLongValue(BLangExpression expr); static int getIntValue(BLangExpression expr); static String getStringValue(BLangExpression expr); static String getValidName(String name); static DeploymentBuildExtension parseBuildExtension(BLangExpression buildExtensionValue); static Map<String, EnvVarValueModel> getEnvVarMap(BLangExpression envVarValues); static Set<String> getImagePullSecrets(BLangRecordLiteral.BLangRecordKeyValueField keyValue); static Set<CopyFileModel> getExternalFileMap(BLangRecordLiteral.BLangRecordKeyValueField keyValue); static List<EnvVar> populateEnvVar(Map<String, EnvVarValueModel> envMap); static List<BLangRecordLiteral.BLangRecordKeyValueField> convertRecordFields(
List<BLangRecordLiteral.RecordField> fields); static AnnotationAttachmentNode createAnnotation(String annotationName); }### Answer:
@Test public void getValidNameTest() { String testString = "HELLO_WORLD.DEMO"; Assert.assertEquals("hello-world-demo", KubernetesUtils.getValidName(testString)); } |
### Question:
PropertiesConfiguration extends EventSource { private String getProperty(String key) { return store.get(key); } PropertiesConfiguration(); PropertiesConfiguration(final String projCode); PropertiesConfiguration(final String projCode, final String profile); PropertiesConfiguration(final String projCode, final String profile, final String modules); PropertiesConfiguration(final String projCode, final String profile, String modules, String localFilePath); PropertiesConfiguration(String host, int port, final String projCode, final String profile); PropertiesConfiguration(String host, int port, final String projCode, final String profile, final String modules); PropertiesConfiguration(String host, int port, final String projCode,
final String profile, String modules,
String localFilePath); void close(); void load(String config); void load(Reader in, boolean reload); static String getHost(); static int getPort(); static String getProjCode(); static String getProfile(); static String getModules(); static String getLocalFilePath(); Properties getProperties(); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultValue); Boolean getBoolean(String key, Boolean defaultValue); byte getByte(String key); byte getByte(String key, byte defaultValue); Byte getByte(String key, Byte defaultValue); double getDouble(String key); double getDouble(String key, double defaultValue); Double getDouble(String key, Double defaultValue); float getFloat(String key); float getFloat(String key, float defaultValue); Float getFloat(String key, Float defaultValue); int getInt(String key); int getInt(String key, int defaultValue); Integer getInteger(String key, Integer defaultValue); long getLong(String key); long getLong(String key, long defaultValue); Long getLong(String key, Long defaultValue); short getShort(String key); short getShort(String key, short defaultValue); Short getShort(String key, Short defaultValue); String getString(String key); String getString(String key, String defaultValue); }### Answer:
@Test public void testSysProperties1() throws ConfigurationRuntimeException { String str = System.getProperty("java.version1"); System.out.print(str); } |
### Question:
Util { static <T, M extends T> Optional<M> tryCast(T original, Class<M> too) { if (original != null && too.isAssignableFrom(original.getClass())) { return Optional.of((M) original); } return Optional.empty(); } static InputStream emptyStream(); static boolean isNullOrEmpty(String s); }### Answer:
@Test public void canCast() { Object foo = new Foo(){}; assertEquals(foo, Util.tryCast(foo, Foo.class).get()); assertEquals(false, Util.tryCast("foo", Foo.class).isPresent()); assertEquals(false, Util.tryCast(null, Foo.class).isPresent()); assertEquals(true, Util.tryCast(new Bar(), Foo.class).isPresent()); }
@Test public void canCastAAsyncClient() { HttpAsyncClient build = HttpAsyncClientBuilder.create().build(); assertEquals(true, Util.tryCast(build, CloseableHttpAsyncClient.class).isPresent()); } |
### Question:
Config { int getMaxPerRoutes() { return maxPerRoute; } Config(); Config httpClient(HttpClient httpClient); Config httpClient(Client httpClient); Config httpClient(Function<Config, Client> httpClient); Config asyncClient(HttpAsyncClient value); Config asyncClient(AsyncClient value); Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder); Config proxy(HttpHost value); Config proxy(String host, int port); Config proxy(String host, int port, String username, String password); Config setObjectMapper(ObjectMapper om); Config connectTimeout(int inMillies); Config socketTimeout(int inMillies); Config concurrency(int total, int perRoute); Config clearDefaultHeaders(); Config setDefaultHeader(String name, String value); Config setDefaultHeader(String name, Supplier<String> value); Config addDefaultHeader(String name, String value); Config addInterceptor(HttpRequestInterceptor interceptor); Config followRedirects(boolean enable); Config enableCookieManagement(boolean enable); Config useSystemProperties(boolean value); Config setDefaultResponseEncoding(String value); Headers getDefaultHeaders(); boolean isRunning(); Config reset(); void shutDown(boolean clearOptions); Client getClient(); AsyncClient getAsyncClient(); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_MAX_CONNECTIONS; static final int DEFAULT_MAX_PER_ROUTE; static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; }### Answer:
@Test public void shouldKeepMaxPerRouteDefault(){ assertEquals(Config.DEFAULT_MAX_PER_ROUTE, config.getMaxPerRoutes()); } |
### Question:
Config { public AsyncClient getAsyncClient() { if (!asyncClientIsReady()) { buildAsyncClient(); } return asyncClient.get(); } Config(); Config httpClient(HttpClient httpClient); Config httpClient(Client httpClient); Config httpClient(Function<Config, Client> httpClient); Config asyncClient(HttpAsyncClient value); Config asyncClient(AsyncClient value); Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder); Config proxy(HttpHost value); Config proxy(String host, int port); Config proxy(String host, int port, String username, String password); Config setObjectMapper(ObjectMapper om); Config connectTimeout(int inMillies); Config socketTimeout(int inMillies); Config concurrency(int total, int perRoute); Config clearDefaultHeaders(); Config setDefaultHeader(String name, String value); Config setDefaultHeader(String name, Supplier<String> value); Config addDefaultHeader(String name, String value); Config addInterceptor(HttpRequestInterceptor interceptor); Config followRedirects(boolean enable); Config enableCookieManagement(boolean enable); Config useSystemProperties(boolean value); Config setDefaultResponseEncoding(String value); Headers getDefaultHeaders(); boolean isRunning(); Config reset(); void shutDown(boolean clearOptions); Client getClient(); AsyncClient getAsyncClient(); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_MAX_CONNECTIONS; static final int DEFAULT_MAX_PER_ROUTE; static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; }### Answer:
@Test public void willRebuildIfEmpty() { assertSame(config.getAsyncClient(), config.getAsyncClient()); } |
### Question:
JsonNode { @Override public String toString() { if (isArray()) { return jsonArray.toString(); } else { return jsonObject.toString(); } } JsonNode(String json); JSONObject getObject(); JSONArray getArray(); boolean isArray(); @Override String toString(); }### Answer:
@Test public void nullAndEmptyObjectsResultInEmptyJson() { assertEquals("{}", new JsonNode("").toString()); assertEquals("{}", new JsonNode(null).toString()); } |
### Question:
Config { int getConnectionTimeout() { return connectionTimeout; } Config(); Config httpClient(HttpClient httpClient); Config httpClient(Client httpClient); Config httpClient(Function<Config, Client> httpClient); Config asyncClient(HttpAsyncClient value); Config asyncClient(AsyncClient value); Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder); Config proxy(HttpHost value); Config proxy(String host, int port); Config proxy(String host, int port, String username, String password); Config setObjectMapper(ObjectMapper om); Config connectTimeout(int inMillies); Config socketTimeout(int inMillies); Config concurrency(int total, int perRoute); Config clearDefaultHeaders(); Config setDefaultHeader(String name, String value); Config setDefaultHeader(String name, Supplier<String> value); Config addDefaultHeader(String name, String value); Config addInterceptor(HttpRequestInterceptor interceptor); Config followRedirects(boolean enable); Config enableCookieManagement(boolean enable); Config useSystemProperties(boolean value); Config setDefaultResponseEncoding(String value); Headers getDefaultHeaders(); boolean isRunning(); Config reset(); void shutDown(boolean clearOptions); Client getClient(); AsyncClient getAsyncClient(); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_MAX_CONNECTIONS; static final int DEFAULT_MAX_PER_ROUTE; static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; }### Answer:
@Test public void shouldKeepConnectionTimeOutDefault(){ assertEquals(Config.DEFAULT_CONNECT_TIMEOUT, config.getConnectionTimeout()); } |
### Question:
Config { int getSocketTimeout() { return socketTimeout; } Config(); Config httpClient(HttpClient httpClient); Config httpClient(Client httpClient); Config httpClient(Function<Config, Client> httpClient); Config asyncClient(HttpAsyncClient value); Config asyncClient(AsyncClient value); Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder); Config proxy(HttpHost value); Config proxy(String host, int port); Config proxy(String host, int port, String username, String password); Config setObjectMapper(ObjectMapper om); Config connectTimeout(int inMillies); Config socketTimeout(int inMillies); Config concurrency(int total, int perRoute); Config clearDefaultHeaders(); Config setDefaultHeader(String name, String value); Config setDefaultHeader(String name, Supplier<String> value); Config addDefaultHeader(String name, String value); Config addInterceptor(HttpRequestInterceptor interceptor); Config followRedirects(boolean enable); Config enableCookieManagement(boolean enable); Config useSystemProperties(boolean value); Config setDefaultResponseEncoding(String value); Headers getDefaultHeaders(); boolean isRunning(); Config reset(); void shutDown(boolean clearOptions); Client getClient(); AsyncClient getAsyncClient(); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_MAX_CONNECTIONS; static final int DEFAULT_MAX_PER_ROUTE; static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; }### Answer:
@Test public void shouldKeepSocketTimeoutDefault(){ assertEquals(Config.DEFAULT_SOCKET_TIMEOUT, config.getSocketTimeout()); } |
### Question:
Config { int getMaxConnections() { return maxTotal; } Config(); Config httpClient(HttpClient httpClient); Config httpClient(Client httpClient); Config httpClient(Function<Config, Client> httpClient); Config asyncClient(HttpAsyncClient value); Config asyncClient(AsyncClient value); Config asyncClient(Function<Config, AsyncClient> asyncClientBuilder); Config proxy(HttpHost value); Config proxy(String host, int port); Config proxy(String host, int port, String username, String password); Config setObjectMapper(ObjectMapper om); Config connectTimeout(int inMillies); Config socketTimeout(int inMillies); Config concurrency(int total, int perRoute); Config clearDefaultHeaders(); Config setDefaultHeader(String name, String value); Config setDefaultHeader(String name, Supplier<String> value); Config addDefaultHeader(String name, String value); Config addInterceptor(HttpRequestInterceptor interceptor); Config followRedirects(boolean enable); Config enableCookieManagement(boolean enable); Config useSystemProperties(boolean value); Config setDefaultResponseEncoding(String value); Headers getDefaultHeaders(); boolean isRunning(); Config reset(); void shutDown(boolean clearOptions); Client getClient(); AsyncClient getAsyncClient(); static final int DEFAULT_CONNECTION_TIMEOUT; static final int DEFAULT_MAX_CONNECTIONS; static final int DEFAULT_MAX_PER_ROUTE; static final int DEFAULT_CONNECT_TIMEOUT; static final int DEFAULT_SOCKET_TIMEOUT; }### Answer:
@Test public void shouldKeepMaxTotalDefault(){ assertEquals(Config.DEFAULT_MAX_CONNECTIONS, config.getMaxConnections()); } |
### Question:
RxBackoff { public static RxBackoff fixed(long interval, int maxRetryCount) { return new RxBackoff(new Backoff.Builder() .setAlgorithm(new FixedIntervalAlgorithm(interval, TimeUnit.MILLISECONDS)) .setMaxRetryCount(maxRetryCount) .build()); } RxBackoff(@NonNull Backoff backoff); RxBackoff(@NonNull Backoff backoff, @NonNull Scheduler intervalScheduler); static RxBackoff exponential(double multiplier, int maxRetryCount); static RxBackoff fixed(long interval, int maxRetryCount); static RxBackoff random(long lowInterval, long highInterval, int maxRetryCount); static RxBackoff of(BackoffAlgorithm algorithm, int maxRetryCount); RxBackoff filter(@NonNull Predicate<Throwable> predicate); RxBackoff doOnRetry(@NonNull BiConsumer<Throwable, Integer> onRetry); RxBackoff doOnAbort(@NonNull Consumer<Throwable> onAbort); Function<Observable<Throwable>, ObservableSource<?>> observable(); Function<Flowable<Throwable>, Publisher<?>> flowable(); }### Answer:
@Test public void fixed() { final AtomicInteger count = new AtomicInteger(0); final TestScheduler scheduler = new TestScheduler(); final RxBackoff backoff = new RxBackoff( new Backoff.Builder() .setAlgorithm(new FixedIntervalAlgorithm()) .setMaxRetryCount(5) .build(), scheduler); final TestObserver observer = Observable .fromCallable(new Callable<Integer>() { @Override public Integer call() throws Exception { throw new Exception("error " + count.incrementAndGet()); } }) .retryWhen(backoff.observable()) .subscribeOn(scheduler) .test(); scheduler.advanceTimeTo(90_0000L, TimeUnit.MILLISECONDS); scheduler.triggerActions(); observer.awaitTerminalEvent(1000L, TimeUnit.MILLISECONDS); observer.assertError(Exception.class); assertThat(count.get()).isEqualTo(6); } |
### Question:
KnowledgeBase implements Iterable<Statement> { public String getBaseIri() { return this.prefixDeclarationRegistry.getBaseIri(); } void addListener(final KnowledgeBaseListener listener); void deleteListener(final KnowledgeBaseListener listener); void addStatement(final Statement statement); void addStatements(final Collection<? extends Statement> statements); void addStatements(final Statement... statements); int removeStatement(final Statement statement); int removeStatements(final Collection<? extends Statement> statements); int removeStatements(final Statement... statements); List<Rule> getRules(); List<Fact> getFacts(); List<DataSourceDeclaration> getDataSourceDeclarations(); Collection<Statement> getStatements(); @Override Iterator<Statement> iterator(); void importRulesFile(File file, AdditionalInputParser parseFunction); void mergePrefixDeclarations(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); String getBaseIri(); Iterator<Entry<String, String>> getPrefixes(); String getPrefixIri(String prefixName); String resolvePrefixedName(String prefixedName); String unresolveAbsoluteIri(String iri); void writeKnowledgeBase(Writer writer); @Deprecated void writeKnowledgeBase(String filePath); }### Answer:
@Test public void getBase_default_hasEmptyBase() { assertEquals("", this.kb.getBaseIri()); } |
### Question:
ParserConfiguration { public KnowledgeBase parseDirectiveStatement(String name, List<Argument> arguments, SubParserFactory subParserFactory) throws ParsingException { final DirectiveHandler<KnowledgeBase> handler = this.directives.get(name); if (handler == null) { throw new ParsingException("Directive \"" + name + "\" is not known."); } return handler.handleDirective(arguments, subParserFactory); } ParserConfiguration(); ParserConfiguration(ParserConfiguration other); ParserConfiguration registerDataSource(final String name, final DataSourceDeclarationHandler handler); DataSource parseDataSourceSpecificPartOfDataSourceDeclaration(PositiveLiteral declaration); Constant parseDatatypeConstant(final String lexicalForm, final String datatype,
final TermFactory termFactory); boolean isConfigurableLiteralRegistered(ConfigurableLiteralDelimiter delimiter); Term parseConfigurableLiteral(ConfigurableLiteralDelimiter delimiter, String syntacticForm,
final SubParserFactory subParserFactory); ParserConfiguration registerDatatype(final String name, final DatatypeConstantHandler handler); ParserConfiguration registerLiteral(ConfigurableLiteralDelimiter delimiter,
ConfigurableLiteralHandler handler); ParserConfiguration registerDirective(String name, DirectiveHandler<KnowledgeBase> handler); KnowledgeBase parseDirectiveStatement(String name, List<Argument> arguments,
SubParserFactory subParserFactory); ParserConfiguration setNamedNulls(boolean allow); ParserConfiguration allowNamedNulls(); ParserConfiguration disallowNamedNulls(); boolean isParsingOfNamedNullsAllowed(); String getImportBasePath(); ParserConfiguration setImportBasePath(String importBasePath); static final List<String> RESERVED_DIRECTIVE_NAMES; }### Answer:
@Test(expected = ParsingException.class) public void parseDirectiveStatement_unregisteredDirective_throws() throws ParsingException { parserConfiguration.parseDirectiveStatement(DIRECTIVE_NAME, new ArrayList<>(), subParserFactory); } |
### Question:
Skolemization { public AbstractConstant getSkolemConstant(String name, TermFactory termFactory) { return termFactory.makeAbstractConstant(getSkolemConstantName(name)); } RenamedNamedNull getRenamedNamedNull(String name); AbstractConstant getSkolemConstant(String name, TermFactory termFactory); AbstractConstant getSkolemConstant(NamedNull namedNull, TermFactory termFactory); String getSkolemConstantName(String name); String getSkolemConstantName(NamedNull namedNull); UUID getFreshName(String name); final static String SKOLEM_IRI_PREFIX; }### Answer:
@Test public void skolemConstant_succeeds() { TermFactory termFactory = new TermFactory(); AbstractConstant skolem = skolemization.getSkolemConstant(name1, termFactory); assertTrue(skolem.getName().startsWith(Skolemization.SKOLEM_IRI_PREFIX)); }
@Test public void skolemConstantFromNamedNull_succeeds() { TermFactory termFactory = new TermFactory(); NamedNull null1 = new NamedNullImpl(name1); AbstractConstant skolem1 = skolemization.getSkolemConstant(null1, termFactory); AbstractConstant skolem2 = skolemization.getSkolemConstant(name1, termFactory); assertEquals(skolem2, skolem1); } |
### Question:
PredicateImpl implements Predicate { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Predicate)) { return false; } final Predicate other = (Predicate) obj; return this.arity == other.getArity() && this.name.equals(other.getName()); } PredicateImpl(final String name, int arity); @Override String getName(); @Override int getArity(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { final Predicate p1 = new PredicateImpl("p", 1); final Predicate p1too = Expressions.makePredicate("p", 1); final Predicate p2 = new PredicateImpl("p", 2); final Predicate q1 = new PredicateImpl("q", 1); assertEquals(p1, p1); assertEquals(p1too, p1); assertNotEquals(p2, p1); assertNotEquals(q1, p1); assertNotEquals(p2.hashCode(), p1.hashCode()); assertNotEquals(q1.hashCode(), p1.hashCode()); assertFalse(p1.equals(null)); assertFalse(p1.equals("p")); } |
### Question:
PredicateImpl implements Predicate { @Override public String toString() { return Serializer.getSerialization(serializer -> serializer.writePredicate(this)); } PredicateImpl(final String name, int arity); @Override String getName(); @Override int getArity(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void predicateToStringTest() { final Predicate p1 = new PredicateImpl("p", 1); assertEquals("p[1]", p1.toString()); } |
### Question:
JavaCCParserBase { AbstractConstant createConstant(String lexicalForm) throws ParseException { String absoluteIri; try { absoluteIri = absolutizeIri(lexicalForm); } catch (PrefixDeclarationException e) { throw makeParseExceptionWithCause("Failed to parse IRI", e); } return termFactory.makeAbstractConstant(absoluteIri); } JavaCCParserBase(); void setKnowledgeBase(KnowledgeBase knowledgeBase); KnowledgeBase getKnowledgeBase(); void setParserConfiguration(ParserConfiguration parserConfiguration); ParserConfiguration getParserConfiguration(); void setPrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); }### Answer:
@Test public void createConstant_undeclaredPrefix_throws() throws ParseException { exceptionRule.expect(ParseException.class); exceptionRule.expectMessage("Failed to parse IRI"); parserBase.createConstant("ïnvälid: } |
### Question:
JavaCCParserBase { static String unescapeStr(String s, int line, int column) throws ParseException { return unescape(s, '\\', line, column); } JavaCCParserBase(); void setKnowledgeBase(KnowledgeBase knowledgeBase); KnowledgeBase getKnowledgeBase(); void setParserConfiguration(ParserConfiguration parserConfiguration); ParserConfiguration getParserConfiguration(); void setPrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); }### Answer:
@Test public void unescapeStr_escapeChars_succeeds() throws ParseException { String input = "\\\\test\r\ntest: \\n\\t\\r\\b\\f\\'\\\"\\\\"; String expected = "\\test\r\ntest: \n\t\r\b\f\'\"\\"; String result = JavaCCParserBase.unescapeStr(input, 0, 0); assertEquals(result, expected); }
@Test public void unescapeStr_illegalEscapeAtEndOfString_throws() throws ParseException { exceptionRule.expect(ParseException.class); exceptionRule.expectMessage("Illegal escape at end of string"); JavaCCParserBase.unescapeStr("\\", 0, 0); }
@Test public void unescapeStr_unknownEscapeSequence_throws() throws ParseException { exceptionRule.expect(ParseException.class); exceptionRule.expectMessage("Unknown escape"); JavaCCParserBase.unescapeStr("\\y", 0, 0); } |
### Question:
JavaCCParserBase { void setBase(String baseIri) throws PrefixDeclarationException { prefixDeclarationRegistry.setBaseIri(baseIri); } JavaCCParserBase(); void setKnowledgeBase(KnowledgeBase knowledgeBase); KnowledgeBase getKnowledgeBase(); void setParserConfiguration(ParserConfiguration parserConfiguration); ParserConfiguration getParserConfiguration(); void setPrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); }### Answer:
@Test public void setBase_changingBase_throws() throws PrefixDeclarationException { exceptionRule.expect(PrefixDeclarationException.class); exceptionRule.expectMessage("Base is already defined as"); parserBase.setBase("https: parserBase.setBase("https: } |
### Question:
VLogKnowledgeBase { boolean hasData() { return !this.edbPredicates.isEmpty() || !this.aliasedEdbPredicates.isEmpty(); } VLogKnowledgeBase(final KnowledgeBase knowledgeBase); boolean hasRules(); }### Answer:
@Test public void hasData_noData_returnsFalse() { VLogKnowledgeBase vKB = new VLogKnowledgeBase(knowledgeBase); assertFalse(vKB.hasData()); }
@Test public void hasData_noAliasedPredicates_returnsTrue() { knowledgeBase.addStatement(fact); VLogKnowledgeBase vKB = new VLogKnowledgeBase(knowledgeBase); assertTrue(vKB.hasData()); }
@Test public void hasData_onlyAliasedPredicates_returnsTrue() { knowledgeBase.addStatement(rule); knowledgeBase.addStatement(fact); VLogKnowledgeBase vKB = new VLogKnowledgeBase(knowledgeBase); assertTrue(vKB.hasData()); }
@Test public void hasData_bothUnaliasedAndAliasedPredicates_returnsTrue() { knowledgeBase.addStatement(Expressions.makeFact(q, c)); knowledgeBase.addStatement(rule); knowledgeBase.addStatement(fact); VLogKnowledgeBase vKB = new VLogKnowledgeBase(knowledgeBase); assertTrue(vKB.hasData()); } |
### Question:
MergingPrefixDeclarationRegistry extends AbstractPrefixDeclarationRegistry { @Override public void setBaseIri(String baseIri) { Validate.notNull(baseIri, "baseIri must not be null"); if (baseIri == this.baseIri) { return; } if (this.baseIri == null) { this.baseIri = baseIri; } else if (this.baseIri == PrefixDeclarationRegistry.EMPTY_BASE) { prefixes.put(getFreshPrefix(), baseIri); } else { prefixes.put(getFreshPrefix(), this.baseIri); this.baseIri = baseIri; } } MergingPrefixDeclarationRegistry(); MergingPrefixDeclarationRegistry(final PrefixDeclarationRegistry prefixDeclarations); @Override void setBaseIri(String baseIri); @Override void setPrefixIri(String prefixName, String prefixIri); void mergePrefixDeclarations(final PrefixDeclarationRegistry other); }### Answer:
@Test public void setBaseIri_changingBase_succeeds() { prefixDeclarations.setBaseIri(BASE); assertEquals(BASE, prefixDeclarations.getBaseIri()); prefixDeclarations.setBaseIri(MORE_SPECIFIC); assertEquals(MORE_SPECIFIC, prefixDeclarations.getBaseIri()); }
@Test public void setBaseIri_redeclareSameBase_succeeds() { prefixDeclarations.setBaseIri(BASE); assertEquals(BASE, prefixDeclarations.getBaseIri()); prefixDeclarations.setBaseIri(BASE); assertEquals(BASE, prefixDeclarations.getBaseIri()); }
@Test public void absolutizeIri_base_absoluteIri() throws PrefixDeclarationException { prefixDeclarations.setBaseIri(BASE); assertEquals(BASE + RELATIVE, prefixDeclarations.absolutizeIri(RELATIVE)); } |
### Question:
VLogDataSourceConfigurationVisitor implements DataSourceConfigurationVisitor { String getDirCanonicalPath(FileDataSource dataSource) throws IOException { return Paths.get(dataSource.getFile().getCanonicalPath()).getParent().toString(); } String getConfigString(); @Override void visit(CsvFileDataSource dataSource); @Override void visit(RdfFileDataSource dataSource); @Override void visit(SparqlQueryResultDataSource dataSource); @Override void visit(TridentDataSource dataSource); @Override void visit(InMemoryDataSource dataSource); }### Answer:
@Test public void getDirCanonicalPath_relativePath_succeeds() throws IOException { final VLogDataSourceConfigurationVisitor visitor = new VLogDataSourceConfigurationVisitor(); final FileDataSource fileDataSource = new CsvFileDataSource("file.csv"); final String currentFolder = new File(".").getCanonicalPath(); assertEquals(currentFolder, visitor.getDirCanonicalPath(fileDataSource)); }
@Test public void getDirCanonicalPath_nonNormalisedPath_succeeds() throws IOException { final VLogDataSourceConfigurationVisitor visitor = new VLogDataSourceConfigurationVisitor(); final FileDataSource fileDataSource = new CsvFileDataSource("./././file.csv"); final String currentFolder = new File(".").getCanonicalPath(); assertEquals(currentFolder, visitor.getDirCanonicalPath(fileDataSource)); } |
### Question:
ModelToVLogConverter { static String[][] toVLogFactTuples(final Collection<Fact> facts) { final String[][] tuples = new String[facts.size()][]; int i = 0; for (final Fact fact : facts) { final String[] vLogFactTuple = ModelToVLogConverter.toVLogFactTuple(fact); tuples[i] = vLogFactTuple; i++; } return tuples; } private ModelToVLogConverter(); static final String PREDICATE_ARITY_SUFFIX_SEPARATOR; }### Answer:
@Test public void testToVLogFactTuples() { final Constant c1 = Expressions.makeAbstractConstant("1"); final Constant c2 = Expressions.makeAbstractConstant("2"); final Constant c3 = Expressions.makeAbstractConstant("3"); final Fact atom1 = Expressions.makeFact("p1", Arrays.asList(c1)); final Fact atom2 = Expressions.makeFact("p2", Arrays.asList(c2, c3)); final String[][] vLogTuples = ModelToVLogConverter.toVLogFactTuples(Arrays.asList(atom1, atom2)); final String[][] expectedTuples = { { "1" }, { "2", "3" } }; assertArrayEquals(expectedTuples, vLogTuples); } |
### Question:
KnowledgeBase implements Iterable<Statement> { public String getPrefixIri(String prefixName) throws PrefixDeclarationException { return this.prefixDeclarationRegistry.getPrefixIri(prefixName); } void addListener(final KnowledgeBaseListener listener); void deleteListener(final KnowledgeBaseListener listener); void addStatement(final Statement statement); void addStatements(final Collection<? extends Statement> statements); void addStatements(final Statement... statements); int removeStatement(final Statement statement); int removeStatements(final Collection<? extends Statement> statements); int removeStatements(final Statement... statements); List<Rule> getRules(); List<Fact> getFacts(); List<DataSourceDeclaration> getDataSourceDeclarations(); Collection<Statement> getStatements(); @Override Iterator<Statement> iterator(); void importRulesFile(File file, AdditionalInputParser parseFunction); void mergePrefixDeclarations(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); String getBaseIri(); Iterator<Entry<String, String>> getPrefixes(); String getPrefixIri(String prefixName); String resolvePrefixedName(String prefixedName); String unresolveAbsoluteIri(String iri); void writeKnowledgeBase(Writer writer); @Deprecated void writeKnowledgeBase(String filePath); }### Answer:
@Test(expected = PrefixDeclarationException.class) public void getPrefix_defaultUndeclaredPrefix_throws() throws PrefixDeclarationException { this.kb.getPrefixIri("ex:"); } |
### Question:
ModelToVLogConverter { static String toVLogPredicate(Predicate predicate) { final String vLogPredicate = predicate.getName() + PREDICATE_ARITY_SUFFIX_SEPARATOR + predicate.getArity(); return vLogPredicate; } private ModelToVLogConverter(); static final String PREDICATE_ARITY_SUFFIX_SEPARATOR; }### Answer:
@Test public void testToVLogPredicate() { final Predicate predicate = Expressions.makePredicate("pred", 1); final String vLogPredicate = ModelToVLogConverter.toVLogPredicate(predicate); assertEquals("pred-1", vLogPredicate); } |
### Question:
ModelToVLogConverter { static karmaresearch.vlog.Atom toVLogAtom(final Literal literal) { final karmaresearch.vlog.Term[] vLogTerms = toVLogTermArray(literal.getArguments()); final String vLogPredicate = toVLogPredicate(literal.getPredicate()); final karmaresearch.vlog.Atom vLogAtom = new karmaresearch.vlog.Atom(vLogPredicate, literal.isNegated(), vLogTerms); return vLogAtom; } private ModelToVLogConverter(); static final String PREDICATE_ARITY_SUFFIX_SEPARATOR; }### Answer:
@Test public void testToVLogAtom() { final Constant c = Expressions.makeAbstractConstant("c"); final Variable x = Expressions.makeUniversalVariable("x"); final NamedNull b = new NamedNullImpl("_:b"); final PositiveLiteral atom = Expressions.makePositiveLiteral("pred", c, x, b); final karmaresearch.vlog.Term expectedC = new karmaresearch.vlog.Term(karmaresearch.vlog.Term.TermType.CONSTANT, "c"); final karmaresearch.vlog.Term expectedX = new karmaresearch.vlog.Term(karmaresearch.vlog.Term.TermType.VARIABLE, "x"); final karmaresearch.vlog.Term expectedB = new karmaresearch.vlog.Term(karmaresearch.vlog.Term.TermType.BLANK, "_:b"); final String expectedPredicateName = "pred" + ModelToVLogConverter.PREDICATE_ARITY_SUFFIX_SEPARATOR + 3; final karmaresearch.vlog.Term[] expectedTerms = { expectedC, expectedX, expectedB }; final karmaresearch.vlog.Atom expectedAtom = new karmaresearch.vlog.Atom(expectedPredicateName, expectedTerms); final karmaresearch.vlog.Atom vLogAtom = ModelToVLogConverter.toVLogAtom(atom); assertEquals(expectedAtom, vLogAtom); } |
### Question:
ModelToVLogConverter { static karmaresearch.vlog.VLog.RuleRewriteStrategy toVLogRuleRewriteStrategy( final RuleRewriteStrategy ruleRewriteStrategy) { switch (ruleRewriteStrategy) { case SPLIT_HEAD_PIECES: return karmaresearch.vlog.VLog.RuleRewriteStrategy.AGGRESSIVE; case NONE: default: return karmaresearch.vlog.VLog.RuleRewriteStrategy.NONE; } } private ModelToVLogConverter(); static final String PREDICATE_ARITY_SUFFIX_SEPARATOR; }### Answer:
@Test public void testVLogRuleRewritingStrategy() { assertEquals(karmaresearch.vlog.VLog.RuleRewriteStrategy.NONE, ModelToVLogConverter.toVLogRuleRewriteStrategy(RuleRewriteStrategy.NONE)); assertEquals(karmaresearch.vlog.VLog.RuleRewriteStrategy.AGGRESSIVE, ModelToVLogConverter.toVLogRuleRewriteStrategy(RuleRewriteStrategy.SPLIT_HEAD_PIECES)); } |
### Question:
InteractiveShellClient { Interpreter initializeInterpreter(final Terminal terminal) { final ParserConfiguration parserConfiguration = new DefaultParserConfiguration(); final Interpreter interpreter = new Interpreter(Interpreter.EMPTY_KNOWLEDGE_BASE_PROVIDER, (knowledgeBase) -> new VLogReasoner(knowledgeBase), new TerminalStyledPrinter(terminal), parserConfiguration); return interpreter; } void launchShell(final ShellConfiguration configuration); }### Answer:
@Test public void initializeInterpreter() { final Terminal terminal = Mockito.mock(Terminal.class); final PrintWriter writer = Mockito.mock(PrintWriter.class); Mockito.when(terminal.writer()).thenReturn(writer); final InteractiveShellClient interactiveShell = new InteractiveShellClient(); final Interpreter interpreter = interactiveShell.initializeInterpreter(terminal); assertTrue(interpreter.getParserConfiguration() instanceof DefaultParserConfiguration); assertTrue(interpreter.getKnowledgeBase().getStatements().isEmpty()); assertEquals(writer, interpreter.getWriter()); } |
### Question:
InteractiveShellClient { public void launchShell(final ShellConfiguration configuration) throws IOException { final Terminal terminal = configuration.buildTerminal(); try (Interpreter interpreter = this.initializeInterpreter(terminal)) { final Shell shell = new Shell(interpreter); final LineReader lineReader = configuration.buildLineReader(terminal, shell.getCommands()); final String prompt = configuration.buildPrompt(terminal); shell.run(lineReader, prompt); } } void launchShell(final ShellConfiguration configuration); }### Answer:
@Test public void run_mockConfiguration() throws IOException { final ShellConfiguration configuration = Mockito.mock(ShellConfiguration.class); final Terminal terminal = Mockito.mock(DumbTerminal.class); final StringWriter output = new StringWriter(); final PrintWriter printWriter = new PrintWriter(output); Mockito.when(terminal.writer()).thenReturn(printWriter); final LineReader lineReader = Mockito.mock(LineReader.class); Mockito.when(lineReader.readLine("prompt")).thenReturn("help", "exit"); Mockito.when(configuration.buildTerminal()).thenReturn(terminal); Mockito.when(configuration.buildPrompt(terminal)).thenReturn("prompt"); Mockito.when(configuration.buildLineReader(Mockito.eq(terminal), ArgumentMatchers.anyCollection())) .thenReturn(lineReader); final InteractiveShellClient shellClient = new InteractiveShellClient(); shellClient.launchShell(configuration); assertTrue(output.toString().contains("Welcome to the Rulewerk interactive shell.")); assertTrue(output.toString().contains("Available commands:")); assertTrue(output.toString().contains("Exiting Rulewerk")); } |
### Question:
ExitCommandInterpreter implements CommandInterpreter { @Override public void run(final Command command, final org.semanticweb.rulewerk.commands.Interpreter interpreter) throws CommandExecutionException { this.shell.exitShell(); } ExitCommandInterpreter(final Shell shell); @Override void printHelp(final String commandName, final Interpreter interpreter); @Override String getSynopsis(); @Override void run(final Command command, final org.semanticweb.rulewerk.commands.Interpreter interpreter); static final Command EXIT_COMMAND; }### Answer:
@Test public void exitShell_succeeds() throws CommandExecutionException { final Interpreter interpreterMock = Mockito.mock(Interpreter.class); final Shell shell = new Shell(interpreterMock); final Shell shellSpy = Mockito.spy(shell); final ExitCommandInterpreter commandInterpreter = new ExitCommandInterpreter(shellSpy); commandInterpreter.run(Mockito.mock(Command.class), interpreterMock); Mockito.verify(shellSpy).exitShell(); } |
### Question:
ExitCommandInterpreter implements CommandInterpreter { @Override public void printHelp(final String commandName, final Interpreter interpreter) { interpreter.printNormal("Usage: @" + commandName + " .\n"); } ExitCommandInterpreter(final Shell shell); @Override void printHelp(final String commandName, final Interpreter interpreter); @Override String getSynopsis(); @Override void run(final Command command, final org.semanticweb.rulewerk.commands.Interpreter interpreter); static final Command EXIT_COMMAND; }### Answer:
@Test public void help_succeeds() throws ParsingException, CommandExecutionException { final Shell shellMock = Mockito.mock(Shell.class); final ExitCommandInterpreter commandInterpreter = new ExitCommandInterpreter(shellMock); final StringWriter writer = new StringWriter(); final Interpreter interpreter = ShellTestUtils.getMockInterpreter(writer); final Interpreter interpreterSpy = Mockito.spy(interpreter); commandInterpreter.printHelp("commandname", interpreterSpy); Mockito.verify(interpreterSpy).printNormal("Usage: @commandname .\n"); final String result = writer.toString(); assertEquals("Usage: @commandname .\n", result); } |
### Question:
ExitCommandInterpreter implements CommandInterpreter { @Override public String getSynopsis() { return "exit Rulewerk shell"; } ExitCommandInterpreter(final Shell shell); @Override void printHelp(final String commandName, final Interpreter interpreter); @Override String getSynopsis(); @Override void run(final Command command, final org.semanticweb.rulewerk.commands.Interpreter interpreter); static final Command EXIT_COMMAND; }### Answer:
@Test public void synopsis_succeeds() throws ParsingException, CommandExecutionException { final Shell shellMock = Mockito.mock(Shell.class); final CommandInterpreter commandInterpreter = new ExitCommandInterpreter(shellMock); final String synopsis = commandInterpreter.getSynopsis(); assertTrue(synopsis.length() < 70); } |
### Question:
DefaultShellConfiguration implements ShellConfiguration { AttributedString getDefaultPromptStyle() { final AttributedStyle promptStyle = AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW); return new AttributedString(PROMPT_STRING, promptStyle); } @Override LineReader buildLineReader(final Terminal terminal, final Collection<String> registeredCommands); @Override Terminal buildTerminal(); @Override String buildPrompt(final Terminal terminal); static final String PROMPT_STRING; }### Answer:
@Test public void buildPromptProvider() { final AttributedString promptProvider = new DefaultShellConfiguration().getDefaultPromptStyle(); assertEquals("rulewerk> ", promptProvider.toString()); } |
### Question:
DefaultShellConfiguration implements ShellConfiguration { @Override public String buildPrompt(final Terminal terminal) { return this.getDefaultPromptStyle().toAnsi(terminal); } @Override LineReader buildLineReader(final Terminal terminal, final Collection<String> registeredCommands); @Override Terminal buildTerminal(); @Override String buildPrompt(final Terminal terminal); static final String PROMPT_STRING; }### Answer:
@Test public void buildPrompt() { final Terminal terminal = Mockito.mock(Terminal.class); Mockito.when(terminal.getType()).thenReturn(Terminal.TYPE_DUMB); final String string = new DefaultShellConfiguration().buildPrompt(terminal); assertTrue(string.length() >= 10); } |
### Question:
Shell { String processReadLine(final String readLine) { String result = readLine.trim(); if (!result.isEmpty()) { if (result.charAt(0) != '@') { result = "@" + result; } if (result.charAt(result.length() - 1) != '.') { result = result + " ."; } } return result; } Shell(final Interpreter interpreter); void run(final LineReader lineReader, final String prompt); Command readCommand(final LineReader lineReader, final String prompt); void exitShell(); Set<String> getCommands(); }### Answer:
@Test public void processReadLine_blank() { final Shell shell = new Shell(Mockito.mock(Interpreter.class)); final String processedReadLine = shell.processReadLine(" "); assertEquals("", processedReadLine); }
@Test public void processReadLine_startsWithAt() { final Shell shell = new Shell(Mockito.mock(Interpreter.class)); final String processedReadLine = shell.processReadLine(" @ "); assertEquals("@ .", processedReadLine); }
@Test public void processReadLine_endsWithStop() { final Shell shell = new Shell(Mockito.mock(Interpreter.class)); final String processedReadLine = shell.processReadLine(" . "); assertEquals("@.", processedReadLine); }
@Test public void processReadLine_startsWithAtEndsWithStop() { final Shell shell = new Shell(Mockito.mock(Interpreter.class)); final String processedReadLine = shell.processReadLine(" @. "); assertEquals("@.", processedReadLine); }
@Test public void processReadLine_doesNotStartWithAt_DoesNotEndWithStop() { final Shell shell = new Shell(Mockito.mock(Interpreter.class)); final String processedReadLine = shell.processReadLine(" .@ "); assertEquals("@.@ .", processedReadLine); } |
### Question:
SaveModel { public boolean isConfigurationValid() { return !this.saveModel || ((this.outputModelDirectory != null) && !this.outputModelDirectory.isEmpty()); } SaveModel(); SaveModel(final boolean saveModel, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); void printConfiguration(); boolean isSaveModel(); void setSaveModel(final boolean saveModel); String getOutputModelDirectory(); void setOutputModelDirectory(final String outputModelDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isConfigurationValid_saveTrueDefaultDir_valid() { assertTrue(saveTrueDefaultDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveTrueEmptyDir_nonValid() { assertFalse(saveTrueEmptyDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveTrueNullDir_nonValid() { assertFalse(saveTrueNullDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseDefaultDir_valid() { assertTrue(saveFalseDefaultDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseEmptyDir_valid() { assertTrue(saveFalseEmptyDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseNullDir_valid() { assertTrue(saveFalseNullDir.isConfigurationValid()); } |
### Question:
SaveModel { public boolean isDirectoryValid() { final File file = new File(this.outputModelDirectory); return !file.exists() || file.isDirectory(); } SaveModel(); SaveModel(final boolean saveModel, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); void printConfiguration(); boolean isSaveModel(); void setSaveModel(final boolean saveModel); String getOutputModelDirectory(); void setOutputModelDirectory(final String outputModelDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isDirectoryValid_nonExistingDirectory_valid() throws IOException { File nonExistingDirectory = tempFolder.newFolder("folderPath"); nonExistingDirectory.delete(); SaveModel temp = new SaveModel(true, nonExistingDirectory.getAbsolutePath()); assertTrue(temp.isDirectoryValid()); }
@Test public void isDirectoryValid_existingFile_nonValid() throws IOException { File existingFile = tempFolder.newFile("filePath"); existingFile.createNewFile(); SaveModel temp = new SaveModel(true, existingFile.getAbsolutePath()); assertFalse(temp.isDirectoryValid()); } |
### Question:
SaveModel { void mkdir() { if (this.saveModel) { final File file = new File(this.outputModelDirectory); if (!file.exists()) { file.mkdirs(); } } } SaveModel(); SaveModel(final boolean saveModel, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); void printConfiguration(); boolean isSaveModel(); void setSaveModel(final boolean saveModel); String getOutputModelDirectory(); void setOutputModelDirectory(final String outputModelDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void mkdir_saveTrueNonExistingDirectory() throws IOException { File subDirectory = tempFolder.newFolder("folderPath", "subFolder"); subDirectory.delete(); SaveModel temp = new SaveModel(true, subDirectory.getAbsolutePath()); temp.mkdir(); assertTrue(subDirectory.isDirectory()); }
@Test public void mkdir_saveTrueExistingDirectory() throws IOException { File subDirectory = tempFolder.newFolder("folderPath", "subFolder"); subDirectory.mkdirs(); SaveModel temp = new SaveModel(true, subDirectory.getAbsolutePath()); temp.mkdir(); assertTrue(subDirectory.isDirectory()); }
@Test public void mkdir_saveFalse() throws IOException { File folder = tempFolder.newFile("validNonExistingFolder"); folder.delete(); SaveModel temp = new SaveModel(false, folder.getAbsolutePath()); temp.mkdir(); assertFalse(folder.exists()); } |
### Question:
SaveModel { public boolean isSaveModel() { return this.saveModel; } SaveModel(); SaveModel(final boolean saveModel, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); void printConfiguration(); boolean isSaveModel(); void setSaveModel(final boolean saveModel); String getOutputModelDirectory(); void setOutputModelDirectory(final String outputModelDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isSaveModel_saveTrueDefaultDir() { assertTrue(saveTrueDefaultDir.isSaveModel()); }
@Test public void isSaveModel_saveTrueEmptyDir() { assertTrue(saveTrueEmptyDir.isSaveModel()); }
@Test public void isSaveModel_saveTrueNullDir() { assertTrue(saveTrueNullDir.isSaveModel()); }
@Test public void isSaveModel_saveFalseDefaultDir() { assertFalse(saveFalseDefaultDir.isSaveModel()); }
@Test public void isSaveModel_saveFalseEmptyDir() { assertFalse(saveFalseEmptyDir.isSaveModel()); }
@Test public void isSaveModel_saveFalseNullDir() { assertFalse(saveFalseNullDir.isSaveModel()); } |
### Question:
SaveModel { public String getOutputModelDirectory() { return this.outputModelDirectory; } SaveModel(); SaveModel(final boolean saveModel, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); void printConfiguration(); boolean isSaveModel(); void setSaveModel(final boolean saveModel); String getOutputModelDirectory(); void setOutputModelDirectory(final String outputModelDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void getOutputModelDirectory_saveTrueDefaultDir() { assertEquals(SaveModel.DEFAULT_OUTPUT_DIR_NAME, saveTrueDefaultDir.getOutputModelDirectory()); }
@Test public void getOutputModelDirectory_saveTrueEmptyDir() { assertEquals(StringUtils.EMPTY, saveTrueEmptyDir.getOutputModelDirectory()); }
@Test public void getOutputModelDirectory_saveTrueNullDir() { assertNull(saveTrueNullDir.getOutputModelDirectory()); }
@Test public void getOutputModelDirectory_saveFalseDefaultDir() { assertEquals(SaveModel.DEFAULT_OUTPUT_DIR_NAME, saveFalseDefaultDir.getOutputModelDirectory()); }
@Test public void getOutputModelDirectory_saveFalseEmptyDir() { assertEquals(StringUtils.EMPTY, saveFalseEmptyDir.getOutputModelDirectory()); }
@Test public void getOutputModelDirectory_saveFalseNullDir() { assertNull(saveFalseNullDir.getOutputModelDirectory()); } |
### Question:
SaveQueryResults { public boolean isConfigurationValid() { return !this.saveResults || ((this.outputQueryResultDirectory != null) && !this.outputQueryResultDirectory.isEmpty()); } SaveQueryResults(); SaveQueryResults(final boolean saveResults, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); boolean isSaveResults(); void setSaveResults(final boolean saveResults); String getOutputQueryResultDirectory(); void setOutputQueryResultDirectory(final String outputQueryResultDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isConfigurationValid_saveTrueDefaultDir_valid() { assertTrue(saveTrueDefaultDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveTrueEmptyDir_notValid() { assertFalse(saveTrueEmptyDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveTrueNullDir_notValid() { assertFalse(saveTrueNullDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseDefaultDir_valid() { assertTrue(saveFalseDefaultDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseEmptyDir_valid() { assertTrue(saveFalseEmptyDir.isConfigurationValid()); }
@Test public void isConfigurationValid_saveFalseNullDir_valid() { assertTrue(saveFalseNullDir.isConfigurationValid()); } |
### Question:
SaveQueryResults { public boolean isDirectoryValid() { final File file = new File(this.outputQueryResultDirectory); return !file.exists() || file.isDirectory(); } SaveQueryResults(); SaveQueryResults(final boolean saveResults, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); boolean isSaveResults(); void setSaveResults(final boolean saveResults); String getOutputQueryResultDirectory(); void setOutputQueryResultDirectory(final String outputQueryResultDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isDirectoryValid_nonExistingDirectory_valid() throws IOException { File nonExistingDirectory = tempFolder.newFolder("folderPath"); nonExistingDirectory.delete(); SaveQueryResults temp = new SaveQueryResults(true, nonExistingDirectory.getAbsolutePath()); assertTrue(temp.isDirectoryValid()); }
@Test public void isDirectoryValid_existingFile_nonValid() throws IOException { File existingFile = tempFolder.newFile("filePath"); existingFile.createNewFile(); SaveQueryResults temp = new SaveQueryResults(true, existingFile.getAbsolutePath()); assertFalse(temp.isDirectoryValid()); } |
### Question:
SaveQueryResults { void mkdir() { if (this.saveResults) { final File file = new File(this.outputQueryResultDirectory); if (!file.exists()) { file.mkdirs(); } } } SaveQueryResults(); SaveQueryResults(final boolean saveResults, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); boolean isSaveResults(); void setSaveResults(final boolean saveResults); String getOutputQueryResultDirectory(); void setOutputQueryResultDirectory(final String outputQueryResultDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void mkdir_saveTrueNonExistingDirectory() throws IOException { File subDirectory = tempFolder.newFolder("folderPath", "subFolder"); subDirectory.delete(); SaveQueryResults temp = new SaveQueryResults(true, subDirectory.getAbsolutePath()); temp.mkdir(); assertTrue(subDirectory.isDirectory()); }
@Test public void mkdir_saveTrueExistingDirectory() throws IOException { File subDirectory = tempFolder.newFolder("folderPath", "subFolder"); subDirectory.mkdirs(); SaveQueryResults temp = new SaveQueryResults(true, subDirectory.getAbsolutePath()); temp.mkdir(); assertTrue(subDirectory.isDirectory()); }
@Test public void mkdir_saveFalse() throws IOException { File folder = tempFolder.newFile("validNonExistingFolder"); folder.delete(); SaveQueryResults temp = new SaveQueryResults(false, folder.getAbsolutePath()); temp.mkdir(); assertFalse(folder.exists()); } |
### Question:
SaveQueryResults { public boolean isSaveResults() { return this.saveResults; } SaveQueryResults(); SaveQueryResults(final boolean saveResults, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); boolean isSaveResults(); void setSaveResults(final boolean saveResults); String getOutputQueryResultDirectory(); void setOutputQueryResultDirectory(final String outputQueryResultDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void isSaveResultsl_saveFalseDefaultDir() { assertFalse(saveFalseDefaultDir.isSaveResults()); } |
### Question:
SaveQueryResults { public String getOutputQueryResultDirectory() { return this.outputQueryResultDirectory; } SaveQueryResults(); SaveQueryResults(final boolean saveResults, final String outputDir); boolean isConfigurationValid(); boolean isDirectoryValid(); boolean isSaveResults(); void setSaveResults(final boolean saveResults); String getOutputQueryResultDirectory(); void setOutputQueryResultDirectory(final String outputQueryResultDirectory); static final String DEFAULT_OUTPUT_DIR_NAME; }### Answer:
@Test public void getOutputQueryResultDirectory_saveFalseDefaultDir() { assertEquals(SaveQueryResults.DEFAULT_OUTPUT_DIR_NAME, saveFalseDefaultDir.getOutputQueryResultDirectory()); } |
### Question:
PrintQueryResults { public boolean isValid() { return !this.sizeOnly || !this.complete; } PrintQueryResults(); PrintQueryResults(final boolean sizeOnly, final boolean complete); boolean isValid(); boolean isSizeOnly(); void setSizeOnly(final boolean sizeOnly); boolean isComplete(); void setComplete(final boolean complete); }### Answer:
@Test public void isValid_sizeTrueCompleteFalse_valid() { assertTrue(sizeTrueCompleteFalse.isValid()); }
@Test public void isValid_sizeTrueCompleteTrue_notValid() { assertFalse(sizeTrueCompleteTrue.isValid()); }
@Test public void isValid_sizeFalseCompleteTrue_valid() { assertTrue(sizeFalseCompleteTrue.isValid()); }
@Test public void isValid_sizeFalseCompleteFalse_valid() { assertTrue(sizeFalseCompleteFalse.isValid()); } |
### Question:
PrintQueryResults { public boolean isSizeOnly() { return this.sizeOnly; } PrintQueryResults(); PrintQueryResults(final boolean sizeOnly, final boolean complete); boolean isValid(); boolean isSizeOnly(); void setSizeOnly(final boolean sizeOnly); boolean isComplete(); void setComplete(final boolean complete); }### Answer:
@Test public void isSizeOnly_sizeFalseCompleteTrue() { assertFalse(sizeFalseCompleteTrue.isSizeOnly()); }
@Test public void isSizeOnly_sizeTrueCompleteTrue() { assertTrue(sizeTrueCompleteTrue.isSizeOnly()); }
@Test public void isSizeOnly_sizeTrueCompleteFalse() { assertTrue(sizeTrueCompleteFalse.isSizeOnly()); }
@Test public void isSizeOnly_sizeFalseCompleteFalse() { assertFalse(sizeFalseCompleteFalse.isSizeOnly()); } |
### Question:
PrintQueryResults { public boolean isComplete() { return this.complete; } PrintQueryResults(); PrintQueryResults(final boolean sizeOnly, final boolean complete); boolean isValid(); boolean isSizeOnly(); void setSizeOnly(final boolean sizeOnly); boolean isComplete(); void setComplete(final boolean complete); }### Answer:
@Test public void isComplete_sizeTrueCompleteFalse() { assertFalse(sizeTrueCompleteFalse.isComplete()); }
@Test public void isComplete_sizeTrueCompleteTrue() { assertTrue(sizeTrueCompleteTrue.isComplete()); }
@Test public void isComplete_sizeFalseCompleteTrue() { assertTrue(sizeFalseCompleteTrue.isComplete()); }
@Test public void isComplete_sizeFalseCompleteFalse() { assertFalse(sizeFalseCompleteFalse.isComplete()); } |
### Question:
KnowledgeBase implements Iterable<Statement> { public String resolvePrefixedName(String prefixedName) throws PrefixDeclarationException { return this.prefixDeclarationRegistry.resolvePrefixedName(prefixedName); } void addListener(final KnowledgeBaseListener listener); void deleteListener(final KnowledgeBaseListener listener); void addStatement(final Statement statement); void addStatements(final Collection<? extends Statement> statements); void addStatements(final Statement... statements); int removeStatement(final Statement statement); int removeStatements(final Collection<? extends Statement> statements); int removeStatements(final Statement... statements); List<Rule> getRules(); List<Fact> getFacts(); List<DataSourceDeclaration> getDataSourceDeclarations(); Collection<Statement> getStatements(); @Override Iterator<Statement> iterator(); void importRulesFile(File file, AdditionalInputParser parseFunction); void mergePrefixDeclarations(PrefixDeclarationRegistry prefixDeclarationRegistry); PrefixDeclarationRegistry getPrefixDeclarationRegistry(); String getBaseIri(); Iterator<Entry<String, String>> getPrefixes(); String getPrefixIri(String prefixName); String resolvePrefixedName(String prefixedName); String unresolveAbsoluteIri(String iri); void writeKnowledgeBase(Writer writer); @Deprecated void writeKnowledgeBase(String filePath); }### Answer:
@Test(expected = PrefixDeclarationException.class) public void resolvePrefixedName_defaultUndeclaredPrefix_throws() throws PrefixDeclarationException { this.kb.resolvePrefixedName("ex:test"); } |
### Question:
Serializer { public void writeLiteral(Literal literal) throws IOException { if (literal.isNegated()) { writer.write("~"); } writePositiveLiteral(literal.getPredicate(), literal.getArguments()); } Serializer(final Writer writer, final Function<String, String> iriTransformer); Serializer(final Writer writer); Serializer(final Writer writer, PrefixDeclarationRegistry prefixDeclarationRegistry); void writeStatement(Statement statement); void writeFact(Fact fact); void writeRule(Rule rule); void writeDataSourceDeclaration(DataSourceDeclaration dataSourceDeclaration); void writeLiteral(Literal literal); void writePositiveLiteral(Predicate predicate, List<Term> arguments); void writeLiteralConjunction(final Conjunction<? extends Literal> literals); void writePredicate(Predicate predicate); void writeTerm(Term term); void writeAbstractConstant(AbstractConstant abstractConstant); void writeDatatypeConstant(DatatypeConstant datatypeConstant); void writeDatatypeConstantNoAbbreviations(DatatypeConstant datatypeConstant); void writeUniversalVariable(UniversalVariable universalVariable); void writeExistentialVariable(ExistentialVariable existentialVariable); void writeNamedNull(NamedNull namedNull); boolean writePrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); void writeLanguageStringConstant(LanguageStringConstant languageStringConstant); void writeCommand(Command command); static String getSerialization(SerializationWriter writeAction); static final String STATEMENT_END; static final Function<String, String> identityIriSerializer; }### Answer:
@Test public void serializePositiveLiteral() throws IOException { serializer.writeLiteral(l1); assertEquals("p1(?X)", writer.toString()); }
@Test public void serializeNegativeLiteral() throws IOException { serializer.writeLiteral(ln1); assertEquals("~p1(!X)", writer.toString()); } |
### Question:
Serializer { public void writePositiveLiteral(Predicate predicate, List<Term> arguments) throws IOException { writer.write(getIri(predicate.getName())); writer.write("("); boolean first = true; for (final Term term : arguments) { if (first) { first = false; } else { writer.write(", "); } writeTerm(term); } writer.write(")"); } Serializer(final Writer writer, final Function<String, String> iriTransformer); Serializer(final Writer writer); Serializer(final Writer writer, PrefixDeclarationRegistry prefixDeclarationRegistry); void writeStatement(Statement statement); void writeFact(Fact fact); void writeRule(Rule rule); void writeDataSourceDeclaration(DataSourceDeclaration dataSourceDeclaration); void writeLiteral(Literal literal); void writePositiveLiteral(Predicate predicate, List<Term> arguments); void writeLiteralConjunction(final Conjunction<? extends Literal> literals); void writePredicate(Predicate predicate); void writeTerm(Term term); void writeAbstractConstant(AbstractConstant abstractConstant); void writeDatatypeConstant(DatatypeConstant datatypeConstant); void writeDatatypeConstantNoAbbreviations(DatatypeConstant datatypeConstant); void writeUniversalVariable(UniversalVariable universalVariable); void writeExistentialVariable(ExistentialVariable existentialVariable); void writeNamedNull(NamedNull namedNull); boolean writePrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); void writeLanguageStringConstant(LanguageStringConstant languageStringConstant); void writeCommand(Command command); static String getSerialization(SerializationWriter writeAction); static final String STATEMENT_END; static final Function<String, String> identityIriSerializer; }### Answer:
@Test public void serializePositiveLiteralFromTerms() throws IOException { serializer.writePositiveLiteral(l1.getPredicate(), l1.getArguments()); assertEquals("p1(?X)", writer.toString()); } |
### Question:
TridentDataSource implements ReasonerDataSource { public String getPath() { return this.filePath; } TridentDataSource(final String filePath); String getPath(); String getName(); @Override Fact getDeclarationFact(); @Override String toString(); @Override void accept(DataSourceConfigurationVisitor visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final String declarationPredicateName; }### Answer:
@Test public void get_succeeds() throws IOException { final TridentDataSource tridentDataSource = new TridentDataSource("trident/path"); assertEquals("trident/path", tridentDataSource.getPath()); } |
### Question:
Serializer { public void writeCommand(Command command) throws IOException { writer.write("@"); writer.write(command.getName()); for (Argument argument : command.getArguments()) { writer.write(" "); if (argument.fromRule().isPresent()) { writeRuleNoStatment(argument.fromRule().get()); } else if (argument.fromPositiveLiteral().isPresent()) { writeLiteral(argument.fromPositiveLiteral().get()); } else { writeTerm(argument.fromTerm().get()); } } writer.write(STATEMENT_END); } Serializer(final Writer writer, final Function<String, String> iriTransformer); Serializer(final Writer writer); Serializer(final Writer writer, PrefixDeclarationRegistry prefixDeclarationRegistry); void writeStatement(Statement statement); void writeFact(Fact fact); void writeRule(Rule rule); void writeDataSourceDeclaration(DataSourceDeclaration dataSourceDeclaration); void writeLiteral(Literal literal); void writePositiveLiteral(Predicate predicate, List<Term> arguments); void writeLiteralConjunction(final Conjunction<? extends Literal> literals); void writePredicate(Predicate predicate); void writeTerm(Term term); void writeAbstractConstant(AbstractConstant abstractConstant); void writeDatatypeConstant(DatatypeConstant datatypeConstant); void writeDatatypeConstantNoAbbreviations(DatatypeConstant datatypeConstant); void writeUniversalVariable(UniversalVariable universalVariable); void writeExistentialVariable(ExistentialVariable existentialVariable); void writeNamedNull(NamedNull namedNull); boolean writePrefixDeclarationRegistry(PrefixDeclarationRegistry prefixDeclarationRegistry); void writeLanguageStringConstant(LanguageStringConstant languageStringConstant); void writeCommand(Command command); static String getSerialization(SerializationWriter writeAction); static final String STATEMENT_END; static final Function<String, String> identityIriSerializer; }### Answer:
@Test public void serializeCommand() throws IOException { ArrayList<Argument> arguments = new ArrayList<>(); arguments.add(Argument.term(abstractConstant)); arguments.add(Argument.positiveLiteral(fact)); arguments.add(Argument.rule(rule)); Command command = new Command("command", arguments); serializer.writeCommand(command); assertEquals("@command <http: } |
### Question:
TridentDataSource implements ReasonerDataSource { @Override public void accept(DataSourceConfigurationVisitor visitor) throws IOException { visitor.visit(this); } TridentDataSource(final String filePath); String getPath(); String getName(); @Override Fact getDeclarationFact(); @Override String toString(); @Override void accept(DataSourceConfigurationVisitor visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final String declarationPredicateName; }### Answer:
@Test public void visit_succeeds() throws IOException { final DataSourceConfigurationVisitor visitor = Mockito.spy(DataSourceConfigurationVisitor.class); final TridentDataSource tridentDataSource = new TridentDataSource("trident/path"); tridentDataSource.accept(visitor); Mockito.verify(visitor).visit(tridentDataSource); } |
### Question:
TermFactory { public UniversalVariable makeUniversalVariable(String name) { if (universalVariables.containsKey(name)) { return universalVariables.get(name); } else { UniversalVariable result = new UniversalVariableImpl(name); universalVariables.put(name, result); return result; } } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void universalVariable_reused() { TermFactory termFactory = new TermFactory(); Term term1 = termFactory.makeUniversalVariable("X"); Term term2 = termFactory.makeUniversalVariable("Y"); Term term3 = termFactory.makeUniversalVariable("X"); Term term4 = new UniversalVariableImpl("X"); assertNotEquals(term1, term2); assertTrue(term1 == term3); assertEquals(term1, term4); } |
### Question:
TermFactory { public ExistentialVariable makeExistentialVariable(String name) { if (existentialVariables.containsKey(name)) { return existentialVariables.get(name); } else { ExistentialVariable result = new ExistentialVariableImpl(name); existentialVariables.put(name, result); return result; } } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void existentialVariable_reused() { TermFactory termFactory = new TermFactory(); Term term1 = termFactory.makeExistentialVariable("X"); Term term2 = termFactory.makeExistentialVariable("Y"); Term term3 = termFactory.makeExistentialVariable("X"); Term term4 = new ExistentialVariableImpl("X"); assertNotEquals(term1, term2); assertTrue(term1 == term3); assertEquals(term1, term4); } |
### Question:
TermFactory { public AbstractConstant makeAbstractConstant(String name) { if (abstractConstants.containsKey(name)) { return abstractConstants.get(name); } else { AbstractConstant result = new AbstractConstantImpl(name); abstractConstants.put(name, result); return result; } } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void abstractConstant_reused() { TermFactory termFactory = new TermFactory(); Term term1 = termFactory.makeAbstractConstant("X"); Term term2 = termFactory.makeAbstractConstant("Y"); Term term3 = termFactory.makeAbstractConstant("X"); Term term4 = new AbstractConstantImpl("X"); assertNotEquals(term1, term2); assertTrue(term1 == term3); assertEquals(term1, term4); } |
### Question:
TermFactory { public Predicate makePredicate(String name, int arity) { String key = name + "#" + String.valueOf(arity); if (predicates.containsKey(key)) { return predicates.get(key); } else { Predicate result = new PredicateImpl(name, arity); predicates.put(key, result); return result; } } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void predicate_reused() { TermFactory termFactory = new TermFactory(); Predicate pred1 = termFactory.makePredicate("p", 1); Predicate pred2 = termFactory.makePredicate("q", 1); Predicate pred3 = termFactory.makePredicate("p", 2); Predicate pred4 = termFactory.makePredicate("p", 1); assertNotEquals(pred1, pred2); assertNotEquals(pred1, pred3); assertTrue(pred1 == pred4); } |
### Question:
TermFactory { public DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri) { return new DatatypeConstantImpl(lexicalValue, datatypeIri); } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void datatypeConstant_succeeds() { TermFactory termFactory = new TermFactory(); Term term1 = termFactory.makeDatatypeConstant("abc", "http: Term term2 = new DatatypeConstantImpl("abc", "http: assertEquals(term1, term2); } |
### Question:
TermFactory { public LanguageStringConstant makeLanguageStringConstant(String string, String languageTag) { return new LanguageStringConstantImpl(string, languageTag); } TermFactory(); TermFactory(int cacheSize); UniversalVariable makeUniversalVariable(String name); ExistentialVariable makeExistentialVariable(String name); AbstractConstant makeAbstractConstant(String name); DatatypeConstant makeDatatypeConstant(String lexicalValue, String datatypeIri); LanguageStringConstant makeLanguageStringConstant(String string, String languageTag); Predicate makePredicate(String name, int arity); }### Answer:
@Test public void languageConstant_succeeds() { TermFactory termFactory = new TermFactory(); Term term1 = termFactory.makeLanguageStringConstant("abc", "de"); Term term2 = new LanguageStringConstantImpl("abc", "de"); assertEquals(term1, term2); } |
### Question:
ConjunctionImpl implements Conjunction<T> { @Override public List<T> getLiterals() { return Collections.unmodifiableList(this.literals); } ConjunctionImpl(List<? extends T> literals); @Override List<T> getLiterals(); @Override Stream<Term> getTerms(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<T> iterator(); @Override String toString(); }### Answer:
@Test public void testGettersLiterals() { final Variable x = Expressions.makeUniversalVariable("X"); final Variable y = Expressions.makeUniversalVariable("Y"); final Variable z = Expressions.makeExistentialVariable("Z"); final Constant c = Expressions.makeAbstractConstant("c"); final Constant d = Expressions.makeAbstractConstant("d"); final Literal positiveLiteral1 = Expressions.makePositiveLiteral("p", x, c); final NegativeLiteral negativeLiteral2 = Expressions.makeNegativeLiteral("p", y, x); final Literal positiveLiteral3 = Expressions.makePositiveLiteral("q", x, d); final Literal positiveLiteral4 = Expressions.makePositiveLiteral("q", y, d, z); final List<Literal> literalList = Arrays.asList(positiveLiteral1, negativeLiteral2, positiveLiteral3, positiveLiteral4); final Conjunction<Literal> conjunction = new ConjunctionImpl<>(literalList); assertEquals(literalList, conjunction.getLiterals()); assertEquals(Sets.newSet(x, y, z), conjunction.getVariables().collect(Collectors.toSet())); assertEquals(Sets.newSet(x, y), conjunction.getUniversalVariables().collect(Collectors.toSet())); assertEquals(Sets.newSet(z), conjunction.getExistentialVariables().collect(Collectors.toSet())); assertEquals(Sets.newSet(), conjunction.getNamedNulls().collect(Collectors.toSet())); assertEquals(Sets.newSet(c, d), conjunction.getAbstractConstants().collect(Collectors.toSet())); } |
### Question:
ConjunctionImpl implements Conjunction<T> { @Override public int hashCode() { return this.literals.hashCode(); } ConjunctionImpl(List<? extends T> literals); @Override List<T> getLiterals(); @Override Stream<Term> getTerms(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<T> iterator(); @Override String toString(); }### Answer:
@Test public void testEqualsLiterals() { final Variable x = Expressions.makeUniversalVariable("X"); final Constant c = Expressions.makeAbstractConstant("c"); final PositiveLiteral positiveLiteral1 = Expressions.makePositiveLiteral("p", x, c); final NegativeLiteral negativeLiteral1 = Expressions.makeNegativeLiteral("p", x, c); final ConjunctionImpl<Literal> conjunction1 = new ConjunctionImpl<>( Arrays.asList(positiveLiteral1, negativeLiteral1)); final Literal positiveLiteral2 = Expressions.makePositiveLiteral("p", x, c); final Literal negativeLiteral2 = Expressions.makeNegativeLiteral("p", x, c); final ConjunctionImpl<Literal> conjunction2 = new ConjunctionImpl<>( Arrays.asList(positiveLiteral2, negativeLiteral2)); assertEquals(conjunction1, conjunction1); assertEquals(conjunction2, conjunction1); assertEquals(conjunction2.hashCode(), conjunction1.hashCode()); } |
### Question:
QueryResultImpl implements QueryResult { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof QueryResult)) { return false; } final QueryResult other = (QueryResult) obj; if (this.terms == null) { return other.getTerms() == null; } else { return this.terms.equals(other.getTerms()); } } QueryResultImpl(List<Term> terms); @Override List<Term> getTerms(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }### Answer:
@Test public void testEquals() { final Constant c1 = Expressions.makeAbstractConstant("C"); final Constant c2 = Expressions.makeAbstractConstant("ddd"); final List<Term> constantList = Arrays.asList(c1, c1, c2); final QueryResult queryResult1 = new QueryResultImpl(constantList); final QueryResult queryResult2 = new QueryResultImpl(Arrays.asList(c1, c1, c2)); final QueryResult queryResult3 = new QueryResultImpl(Arrays.asList(c1, c2, c1)); assertEquals(queryResult1, queryResult1); assertEquals(queryResult2, queryResult1); assertEquals(queryResult2.hashCode(), queryResult1.hashCode()); assertNotEquals(queryResult3, queryResult1); assertNotEquals(queryResult3.hashCode(), queryResult1.hashCode()); assertNotEquals(new QueryResultImpl(null), queryResult1); assertEquals(new QueryResultImpl(null), new QueryResultImpl(null)); assertFalse(queryResult1.equals(null)); assertFalse(queryResult1.equals(constantList)); } |
### Question:
ConjunctionImpl implements Conjunction<T> { @Override public String toString() { return Serializer.getSerialization(serializer -> serializer.writeLiteralConjunction(this)); } ConjunctionImpl(List<? extends T> literals); @Override List<T> getLiterals(); @Override Stream<Term> getTerms(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Iterator<T> iterator(); @Override String toString(); }### Answer:
@Test public void conjunctionToStringTest() { final Variable x = Expressions.makeUniversalVariable("X"); final Variable y = Expressions.makeUniversalVariable("Y"); final Constant c = Expressions.makeAbstractConstant("c"); final Constant d = Expressions.makeAbstractConstant("d"); final PositiveLiteral positiveLiteral1 = Expressions.makePositiveLiteral("p", x, c); final PositiveLiteral positiveLiteral2 = Expressions.makePositiveLiteral("p", y, x); final PositiveLiteral positiveLiteral3 = Expressions.makePositiveLiteral("q", x, d); final NegativeLiteral NegativeLiteral = Expressions.makeNegativeLiteral("r", x, d); final PositiveLiteral PositiveLiteral4 = Expressions.makePositiveLiteral("s", c, d); final List<Literal> LiteralList = Arrays.asList(positiveLiteral1, positiveLiteral2, positiveLiteral3, NegativeLiteral, PositiveLiteral4); final Conjunction<Literal> conjunction1 = new ConjunctionImpl<>(LiteralList); assertEquals("p(?X, c), p(?Y, ?X), q(?X, d), ~r(?X, d), s(c, d)", conjunction1.toString()); } |
### Question:
RdfValueToTermConverter { public Predicate convertUriToPredicate(final URI uri, int arity) { final String escapedURIString = NTriplesUtil.escapeString(uri.toString()); return termFactory.makePredicate(escapedURIString, arity); } RdfValueToTermConverter(boolean skolemize); Term convertValue(final Value value); Term convertBlankNode(final BNode bNode); Term convertUri(final URI uri); Term convertLiteral(final Literal literal); Predicate convertUriToPredicate(final URI uri, int arity); }### Answer:
@Test public void convertUriToPredicate_succeeds() { URI uri = new URIImpl("http: RdfValueToTermConverter converter = new RdfValueToTermConverter(true); Predicate predicate = converter.convertUriToPredicate(uri, 2); assertEquals("http: assertEquals(2, predicate.getArity()); } |
### Question:
RdfModelConverter { public void addAll(KnowledgeBase knowledgeBase, Model model) { addPrefixes(knowledgeBase, model); addFacts(knowledgeBase, model); } RdfModelConverter(); RdfModelConverter(boolean skolemize, String triplePredicateName); Set<Fact> rdfModelToFacts(final Model model); void addAll(KnowledgeBase knowledgeBase, Model model); void addFacts(KnowledgeBase knowledgeBase, Model model); void addPrefixes(KnowledgeBase knowledgeBase, Model model); static final String RDF_TRIPLE_PREDICATE_NAME; }### Answer:
@Test public void addToKnowledgeBase_succeeds() throws RDFParseException, RDFHandlerException, IOException, PrefixDeclarationException { RdfModelConverter rdfModelConverter = new RdfModelConverter(); Model model = RdfTestUtils.parseFile(new File(RdfTestUtils.INPUT_FOLDER + "test-turtle.ttl"), RDFFormat.TURTLE); KnowledgeBase knowledgeBase = new KnowledgeBase(); Predicate predicate = Expressions.makePredicate("TRIPLE", 3); Term terma = Expressions.makeAbstractConstant("http: Term termb = Expressions.makeAbstractConstant("http: Term termc = Expressions.makeAbstractConstant("http: Fact fact = Expressions.makeFact(predicate, terma, termb, termc); rdfModelConverter.addAll(knowledgeBase, model); assertEquals(Arrays.asList(fact), knowledgeBase.getFacts()); assertEquals("http: } |
### Question:
RdfModelConverter { public Set<Fact> rdfModelToFacts(final Model model) { return model.stream().map((statement) -> rdfStatementToFact(statement)).collect(Collectors.toSet()); } RdfModelConverter(); RdfModelConverter(boolean skolemize, String triplePredicateName); Set<Fact> rdfModelToFacts(final Model model); void addAll(KnowledgeBase knowledgeBase, Model model); void addFacts(KnowledgeBase knowledgeBase, Model model); void addPrefixes(KnowledgeBase knowledgeBase, Model model); static final String RDF_TRIPLE_PREDICATE_NAME; }### Answer:
@Test public void getFactSet_succeeds() throws RDFParseException, RDFHandlerException, IOException, PrefixDeclarationException { RdfModelConverter rdfModelConverter = new RdfModelConverter(); Model model = RdfTestUtils.parseFile(new File(RdfTestUtils.INPUT_FOLDER + "test-turtle.ttl"), RDFFormat.TURTLE); Predicate predicate = Expressions.makePredicate("TRIPLE", 3); Term terma = Expressions.makeAbstractConstant("http: Term termb = Expressions.makeAbstractConstant("http: Term termc = Expressions.makeAbstractConstant("http: Fact fact = Expressions.makeFact(predicate, terma, termb, termc); Set<Fact> expected = new HashSet<Fact>(); expected.add(fact); Set<Fact> facts = rdfModelConverter.rdfModelToFacts(model); assertEquals(expected, facts); } |
### Question:
GraalToRulewerkModelConverter { public static Fact convertAtomToFact(final fr.lirmm.graphik.graal.api.core.Atom atom) { final Predicate predicate = convertPredicate(atom.getPredicate()); final List<Term> terms = convertTerms(atom.getTerms(), Collections.emptySet()); return Expressions.makeFact(predicate, terms); } private GraalToRulewerkModelConverter(); static PositiveLiteral convertAtom(final fr.lirmm.graphik.graal.api.core.Atom atom,
final Set<fr.lirmm.graphik.graal.api.core.Variable> existentialVariables); static Fact convertAtomToFact(final fr.lirmm.graphik.graal.api.core.Atom atom); static List<PositiveLiteral> convertAtoms(final List<fr.lirmm.graphik.graal.api.core.Atom> atoms); static List<Fact> convertAtomsToFacts(final List<fr.lirmm.graphik.graal.api.core.Atom> atoms); static GraalConjunctiveQueryToRule convertQuery(final String ruleHeadPredicateName,
final ConjunctiveQuery conjunctiveQuery); static Rule convertRule(final fr.lirmm.graphik.graal.api.core.Rule rule); static List<Rule> convertRules(final List<fr.lirmm.graphik.graal.api.core.Rule> rules); }### Answer:
@Test public void testConvertFact() throws ParseException { final Fact rulewerk_atom = Expressions.makeFact(this.rulewerk_human, Arrays.asList(this.rulewerk_socrate)); final fr.lirmm.graphik.graal.api.core.Atom graal_atom = new DefaultAtom(this.graal_human, this.graal_socrate); assertEquals(rulewerk_atom, GraalToRulewerkModelConverter.convertAtomToFact(graal_atom)); } |
### Question:
ParserConfiguration { public ParserConfiguration registerDataSource(final String name, final DataSourceDeclarationHandler handler) throws IllegalArgumentException { Validate.isTrue(!this.dataSources.containsKey(name), "The Data Source \"%s\" is already registered.", name); this.dataSources.put(name, handler); return this; } ParserConfiguration(); ParserConfiguration(ParserConfiguration other); ParserConfiguration registerDataSource(final String name, final DataSourceDeclarationHandler handler); DataSource parseDataSourceSpecificPartOfDataSourceDeclaration(PositiveLiteral declaration); Constant parseDatatypeConstant(final String lexicalForm, final String datatype,
final TermFactory termFactory); boolean isConfigurableLiteralRegistered(ConfigurableLiteralDelimiter delimiter); Term parseConfigurableLiteral(ConfigurableLiteralDelimiter delimiter, String syntacticForm,
final SubParserFactory subParserFactory); ParserConfiguration registerDatatype(final String name, final DatatypeConstantHandler handler); ParserConfiguration registerLiteral(ConfigurableLiteralDelimiter delimiter,
ConfigurableLiteralHandler handler); ParserConfiguration registerDirective(String name, DirectiveHandler<KnowledgeBase> handler); KnowledgeBase parseDirectiveStatement(String name, List<Argument> arguments,
SubParserFactory subParserFactory); ParserConfiguration setNamedNulls(boolean allow); ParserConfiguration allowNamedNulls(); ParserConfiguration disallowNamedNulls(); boolean isParsingOfNamedNullsAllowed(); String getImportBasePath(); ParserConfiguration setImportBasePath(String importBasePath); static final List<String> RESERVED_DIRECTIVE_NAMES; }### Answer:
@Test(expected = IllegalArgumentException.class) public void registerDataSource_duplicateName_throws() { parserConfiguration.registerDataSource(SOURCE_NAME, dataSourceDeclarationHandler) .registerDataSource(SOURCE_NAME, dataSourceDeclarationHandler); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.