src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
CurrentDatetime { public void forget() { constructionDateTime = LocalDateTime.now(); constructionNanos = System.nanoTime(); currentDateTime = null; currentDate = null; currentTime = null; currentTimestamp = null; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void fo... | @Test public void testForget() throws InterruptedException { Timestamp timestamp = cut.getCurrentTimestamp(); TimeUnit.MILLISECONDS.sleep(10); Timestamp sameTimestamp = cut.getCurrentTimestamp(); assertEquals(timestamp, sameTimestamp); TimeUnit.MILLISECONDS.sleep(10); cut.forget(); Timestamp newTimestamp = cut.getCurre... |
HLC { public long sendOrLocalEvent() { long currentHLC; long returnHLC; while (true) { currentHLC = atomicHLC.get(); long[] hlc = HLCToPhysicalAndLogical(currentHLC); long logical = Math.max(hlc[0], System.currentTimeMillis()); if (logical == hlc[0]) hlc[1]++; else { hlc[0] = logical; hlc[1] = 0l; } returnHLC = physica... | @Test public void alwaysIncreasingLocalEvent() { HLC hlc = new HLC(); long value = 0; for (int i = 0; i< 1000000; i++) { long comparison = hlc.sendOrLocalEvent(); Assert.assertTrue("went backwards, catastophic",value<comparison); value = comparison; } } |
SimpleTxnFilter implements TxnFilter { @Override public DataFilter.ReturnCode filterCell(DataCell keyValue) throws IOException{ CellType type=keyValue.dataType(); switch (type) { case COMMIT_TIMESTAMP: ensureTransactionIsCached(keyValue); return DataFilter.ReturnCode.SKIP; case FOREIGN_KEY_COUNTER: case FIRST_WRITE_TOK... | @Test public void testCanSeeCommittedRowSnapshotIsolation() throws Exception{ TxnSupplier baseStore=txnStore; TxnView committed=new CommittedTxn(0x100l,0x200l); baseStore.cache(committed); ReadResolver noopResolver=NoOpReadResolver.INSTANCE; TxnView myTxn=new InheritingTxnView(Txn.ROOT_TRANSACTION,0x300l,0x300l,Txn.Iso... |
EntryDecoder implements Supplier<MultiFieldDecoder> { public BitIndex getCurrentIndex() { return bitIndex; } EntryDecoder(); EntryDecoder(byte[] bytes); EntryDecoder(byte[] bytes, int offset, int length); void set(byte[] bytes); void set(byte[] bytes, int offset, int length); boolean isSet(int position); boolean next... | @Test public void getCurrentIndex_returnsIndexWithCardinalityOfNonNullFields() throws IOException { byte[] value = new byte[]{-126, -128, 0, 69}; EntryDecoder entryDecoder = new EntryDecoder(value); BitIndex bitIndex = entryDecoder.getCurrentIndex(); assertEquals("Note that the cardinality only indicates number of non-... |
SagaInterestMatcher { public boolean matches(NewtonEvent event, SagaInterest interests) { final Method[] methods = event.getClass().getDeclaredMethods(); boolean matches = false; for (Method method : methods) { if (method.getName().startsWith("get")) { PropertyDescriptor ed = BeanUtils.findPropertyForMethod(method); if... | @Test public void matchesSuccess() throws Exception { SagaInterestMatcher matcher = new SagaInterestMatcher(); final TestEvent testEvent = new TestEvent("hello world"); final SagaInterest sagaInterest = new SagaInterest( TestSaga.class.getName(), TestEvent.class.getCanonicalName(), "saga-id", "some-id", "myId", "hello ... |
DynamicInvokeEventAdaptor implements Function<NewtonEvent, Boolean>, Consumer<NewtonEvent> { @Override public void accept(NewtonEvent event) { apply(event); } DynamicInvokeEventAdaptor(Object target, Class<? extends Annotation> annotation); @Override void accept(NewtonEvent event); @Override Boolean apply(NewtonEvent e... | @Test public void matchesAgainstParamInterfaceType() throws Exception { ParentHandler handler = new ParentHandler(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new EventWithParent()); assertTrue(handler.event instanceof EventWithParent); }
@Test public void canInvokeClassHandler() throws Exceptio... |
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public A load(Object aggregateIdentifier) { try { AggregateRoot aggregate = snapshotRepository.getLatestSnapshot(aggregateIdentifier).orElseGet(() -> { try { AggregateRoot ag = aggregateType.newInstance(); replayEvents(aggregateIdentifier).forEac... | @Test public void load() throws Exception { String id = "simple-id"; client.publishDomainEvents(id.toString(), TestAggregate.class, Collections.singletonList( new TestAggregateCreated(id) ), null); TestAggregate aggregate = repository.load(id); assertNotNull(aggregate); assertEquals(id, aggregate.getId()); }
@DirtiesCo... |
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public CompletableFuture<A> loadAsync(Object aggregateIdentifier) { return CompletableFuture.supplyAsync(() -> load(aggregateIdentifier)); } MuonEventSourceRepository(Class<A> type,
AggregateRootSnapshotReposito... | @Test public void loadAsync() throws Exception { String id = "simple-id"; client.publishDomainEvents(id.toString(), TestAggregate.class, Collections.singletonList( new TestAggregateCreated(id) ), null); TestAggregate aggregate = repository.loadAsync(id).get(); assertNotNull(aggregate); assertEquals(id, aggregate.getId(... |
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public List<NewtonEvent> save(A aggregate) { emitForAggregatePersistence(aggregate); emitForStreamProcessing(aggregate); List<NewtonEvent> events = new ArrayList<>(aggregate.getNewOperations()); aggregate.getNewOperations().clear(); snapshotRepos... | @Test public void save() throws Exception { String id = UUID.randomUUID().toString(); TestAggregate customer = new TestAggregate(id); repository.save(customer); List<Event> events = client.loadAggregateRoot(id.toString(), TestAggregate.class).get(); assertEquals(1, events.size()); assertEquals(TestAggregateCreated.clas... |
SagaStreamManager { public void processSaga(Class<? extends Saga> saga) { SagaStreamConfig[] s = saga.getAnnotationsByType(SagaStreamConfig.class); if (s.length == 0) throw new IllegalStateException("Saga does not have @SagaStreamConfig: " + saga); recordSagaCreatedByEvent(saga); List<String> streams = new ArrayList<>(... | @Test(expected = IllegalStateException.class) public void badlyConfiguredSagaBreaks() throws Exception { SagaStreamManager manager = streamManager(); manager.processSaga(NoAnnotationSaga.class); }
@Test public void sagaConfigOpensStreamSubscriptions() throws Exception { SagaStreamManager manager = streamManager(); mana... |
AggregateRoot { protected void raiseEvent(NewtonEvent event) { newOperations.add(event); handleEvent(event); } abstract T getId(); long getVersion(); List<NewtonEvent> getNewOperations(); void handleEvent(NewtonEvent event); void delete(); } | @Test public void raiseEvent() throws Exception { TestAggregateRoot testAggregate = new TestAggregateRoot(); testAggregate.doA("ZZZ"); assertEquals("A event raised and handled", "ZZZ", testAggregate.getAString()); assertTrue("New Operations contains AEvent", ((AEvent)testAggregate.getNewOperations().get(0)).getValue().... |
CommandFactory implements ApplicationContextAware { public Command create(Class<? extends Command> commandType) { return create(commandType, null, null, null, null); } Command create(Class<? extends Command> commandType); Command create(Class<? extends Command> commandType, Object payload, String tenantId); Command cr... | @Test public void create() throws Exception { Command cmd = commandFactory.create(TestCommand.class); Assert.assertNotNull(cmd); cmd.execute(); }
@Test public void createFromPayload() throws Exception { Command cmd = commandFactory.create(TestPayloadCommand.class, new TestRequest("AAA"), null); Assert.assertNotNull(cmd... |
StatefulSaga implements Saga { @Override public void handle(NewtonEvent event) { boolean eventHandled = eventAdaptor.apply(event); if (!eventHandled) { throw new IllegalStateException("Undefined @EventHandler method for event: ".concat(event.getClass().getName())); } version++; } long getVersion(); @Override void star... | @Test public void canDynamicDispatchEvents() throws Exception { TestSaga saga = new TestSaga(); saga.handle(new MyEvent()); assertNotNull(saga.event); }
@Test(expected = IllegalStateException.class) public void requiresAnnotation() throws Exception { TestSaga saga = new TestSaga(); saga.handle(new MyOtherEvent()); asse... |
Signatures { public static String sign(String urlString, String algorithm, String secretKey) { if (algorithm != null && !algorithm.equals(HMAC_SHA256_ALGORITHM)) { throw new RuntimeException("Unsupported signature: " + algorithm); } if (secretKey == null) { throw new RuntimeException("Signature key not found."); } Mac ... | @Test public void testAmazonHMACSHA256() { String secretKey = "1234567890"; String requestUrl = "http: String targetUrl = "http: String signedUrl = Signatures.sign(requestUrl, "HmacSHA256", secretKey); Assert.assertEquals("Signed request", targetUrl, signedUrl); } |
DateUtils { public static String getCurrentTimeString() { GregorianCalendar gc = new GregorianCalendar(); gc.setTimeZone(TimeZone.getTimeZone(DUBLIN_TIME_ZONE)); SimpleDateFormat sfd = new SimpleDateFormat(MASK, Locale.ENGLISH); return sfd.format(gc.getTime()); } static String getCurrentTimeString(); static String get... | @Test public void shouldPrintDublinTime() { System.out.print(DateUtils.getCurrentTimeString()); } |
NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel { @Override public void infoLoaded(List<MovieInfo> movieInfoList) { List<MovieViewInfo> movieViewInfoList = new ArrayList<>(); for (MovieInfo movieInfo : movieInfoList) { movieViewInfoList.add(new MovieViewInfoImpl(movieInfo)); } nowPlaying... | @Test public void infoLoaded() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); ArgumentCaptor<List<MovieViewInfo>> argumentCaptor = ArgumentCa... |
NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel { @Override public void errorLoadingInfoData() { nowPlayingViewModel.showError(); loadMoreInfo(); } @Inject NowPlayingPresenterImpl(NowPlayingViewModel nowPlayingViewModel,
NowPlayingInteractor nowPlaying... | @Test public void errorLoadingInfoData() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); nowPlayingPresenter.errorLoadingInfoData(); verify(mo... |
AccountData implements Cloneable { public AccountData() { this(null, null, null, null, null); } AccountData(); AccountData(String username, String email, String password); AccountData(String username, String email, String password, String dob, String country); void setDob(String dob); void setCountry(String country);... | @Test public void testAccountData() { AccountData account = new AccountData(); assertThat(account.getDob()).isNotBlank(); } |
ProxySpacedBottleneck implements Runnable, Bottleneck<ProxyInfo> { @Override public void syncUseOf(ProxyInfo proxy) { hostBottleNeck.syncUseOf(proxy.getProvider().getHost()); } ProxySpacedBottleneck(); ProxySpacedBottleneck(int retentionTime); void setRetentionTime(int retentionTime); @Override void syncUseOf(ProxyInf... | @Ignore @Test public void parallelUsesTest() { ProxySpacedBottleneck bottleneck = new ProxySpacedBottleneck(); Thread bottleNeckThread = new Thread(bottleneck); bottleNeckThread.start(); ProxyPolicy proxyPolicy = new NintendoTimeLimitPolicy(); ProxyInfo proxy1 = new ProxyInfo(proxyPolicy, new HttpProxy("test", 1234)); ... |
HttpProxy implements HttpProxyProvider { public static HttpProxy fromURI(String uri) { if (uri == null) { return null; } Matcher matcher = Pattern.compile(URI_REGEXP).matcher(uri); if (matcher.find()) { String host = matcher.group("host"); String protocol = StringUtils.lowerCase(matcher.group("protocol")); String login... | @Test public void encodedCharUriTest() { String uri = "user:p%40ss@127.0.0.1:3128"; HttpProxy proxy = HttpProxy.fromURI(uri); assertThat(proxy).isNotNull(); } |
SequenceAccountGenerator implements AccountGenerator { public void init() { emailGenerator = new PlusTrickEmailGenerator(baseEmail); SequenceUsernameGenerator seqUsernameGenerator = new SequenceUsernameGenerator(usernamePattern, startFrom); if (startFrom + nbAccounts > seqUsernameGenerator.getMaxSequence() + 1) { throw... | @Test public void maxStartAt1Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(1); generator.setNbAccounts(99); generator.init(); }
@Test(expected = IllegalArgumentException.class) public void overFlowStartAt1Test() { SequenceAccountGenerator generator = getSequenceAcco... |
ImageTypersProvider extends CaptchaProvider { public ImageTypersProvider(CaptchaQueue queue, String apiKey) throws ImageTypersConfigurationException { this.queue = queue; this.apiKey = apiKey; this.captchaClient = new OkHttpClient(); if (this.apiKey == null || this.apiKey.isEmpty()) { throw new ImageTypersConfiguration... | @Test @Ignore public void imageTypersProviderTest() throws ImageTypersConfigurationException, InterruptedException { CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String token = prop.getProperty("imageTypers.token"); ImageTypersProvider provider = new ImageTypersProvider(queue, token); logger.info("... |
TwoCaptchaProvider extends CaptchaProvider { public double getBalance() throws TechnicalException, TwoCaptchaConfigurationException { Request sendRequest = buildBalanceCheckequest(); try (Response sendResponse = captchaClient.newCall(sendRequest).execute()) { String body = sendResponse.body().string(); if (body == null... | @Ignore @Test public void solvingTest() throws CaptchaException, TechnicalException, InterruptedException { CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String apiKey = prop.getProperty("twoCaptcha.key"); TwoCaptchaProvider provider = new TwoCaptchaProvider(queue, apiKey); logger.info("Start Provid... |
AccountData implements Cloneable { public static String randomAdultDateOfBirth() { return randomDateOfBirth(18, 80); } AccountData(); AccountData(String username, String email, String password); AccountData(String username, String email, String password, String dob, String country); void setDob(String dob); void setC... | @Test public void testChooseRandomDateOfBirth() { logger.debug("Checking 10 random adults DOB"); for (int i = 0; i < 10; i++) { String rdob = AccountData.randomAdultDateOfBirth(); logger.debug("Random DOB : {}", rdob); assertThat(rdob).isNotBlank(); assertThat(rdob).matches("[0-9]{4}-[0-9]{2}-[0-9]{2}"); int year = Int... |
PtcSession { public void checkForErrors(AccountData account, Document doc) throws FatalException, AccountRateLimitExceededException, TechnicalException, AccountDuplicateException { Elements accessDenied = doc.getElementsContainingOwnText("Access Denied"); if (!accessDenied.isEmpty()) { throw new FatalException("Access ... | @Test(expected = AccountRateLimitExceededException.class) public void QuotaCheck() throws IOException, FatalException, TechnicalException { PtcSession session = new PtcSession(null); try (InputStream test1 = this.getClass().getResourceAsStream("/test1.html")) { AccountData account = new AccountData("username", "email",... |
AntiCaptchaProvider extends CaptchaProvider { public double getBalance() throws AntiCaptchaConfigurationException { try { Request sendRequest = buildBalanceCheckequestGet(); Response sendResponse = captchaClient.newCall(sendRequest).execute(); BalanceResponse balance = mapper.readValue(sendResponse.body().string(), Bal... | @Test public void captchaProviderTest() throws AntiCaptchaConfigurationException, InterruptedException { if (!hasConfig) { return; } CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String token = prop.getProperty("anticaptcha.token"); AntiCaptchaProvider provider = new AntiCaptchaProvider(queue, token... |
ToFileLinkActivator implements LinkActivator { @Override public boolean activateLink(Activation link) { FileLogger.logStatus(link, FileLogger.SKIPPED); return true; } @Override boolean activateLink(Activation link); @Override void start(); } | @Test public void testActivateLink() { ToFileLinkActivator activator = new ToFileLinkActivator(); activator.activateLink(new Activation("Test", "test@mail.com")); } |
PasswordProviderFactory { public static PasswordProvider getPasswordProvider(Properties config) { List<MatchingPair> mapping = new ArrayList<>(); String csvConfig = config.getProperty(CSV_CONFIG); if(StringUtils.isNotEmpty(csvConfig)) { CsvPasswordReader csvReader = new CsvPasswordReader(); mapping.addAll(csvReader.loa... | @Test public void getStaticPasswordProvider() { Properties config = new Properties(); config.setProperty("emailChanger.password.static", "static"); PasswordProvider factory = PasswordProviderFactory.getPasswordProvider(config); assertThat(factory.getPassword("anything")).isEqualTo("static"); }
@Test public void getCsvP... |
AppServerConfig implements ServerConfig { @Override public MetricsListener metricsListener() { return guiceValues.metricsListener; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(... | @Test public void constructor_calls_initServerConfigMetrics_on_metricsListener() { AppServerConfig asc = new AppServerConfig(configForTesting); assertThat(((CodahaleMetricsListener) asc.metricsListener()).getEndpointRequestsTimers()).isNotEmpty(); }
@Test public void constructor_does_not_blow_up_if_metricsListener_is_n... |
AppGuiceModule extends AbstractModule { @Provides @Singleton public CodahaleMetricsEngine codahaleMetricsEngine(@Nullable CodahaleMetricsCollector cmc, @Nullable List<ReporterFactory> reporters, @Named("metrics.reportJvmMetrics") boolean reportJvmMetrics) { if (cmc == null) return null; if (reporters == null) reporters... | @Test public void codahaleMetricsEngine_gracefully_handles_null_reporters_list() { CodahaleMetricsCollector cmc = new CodahaleMetricsCollector(); CodahaleMetricsEngine engine = appGuiceModule.codahaleMetricsEngine(cmc, null, false); assertThat((Collection<ReporterFactory>)Whitebox.getInternalState(engine, "reporters"))... |
HealthCheckEndpoint extends StandardEndpoint<Void, Void> { @Override public Matcher requestMatcher() { return matcher; } @Override CompletableFuture<ResponseInfo<Void>> execute(
RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx
); @Override Matcher requestMatcher(); } | @Test public void healthCheckEndpoint_should_match_all_http_methods() { assertThat(healthCheckEndpoint.requestMatcher().isMatchAllMethods()).isTrue(); } |
HealthCheckEndpoint extends StandardEndpoint<Void, Void> { @Override public CompletableFuture<ResponseInfo<Void>> execute( RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx ) { return CompletableFuture.completedFuture(ResponseInfo.<Void>newBuilder().withHttpStatusCode(200).build());... | @Test public void healthCheckEndpoint_should_always_return_http_status_code_200() { CompletableFuture<ResponseInfo<Void>> responseFuture = healthCheckEndpoint.execute(null, null, null); ResponseInfo<Void> responseInfo = responseFuture.join(); assertThat(responseInfo.getHttpStatusCode()).isEqualTo(200); } |
AppServerConfig implements ServerConfig { @Override public AccessLogger accessLogger() { return accessLogger; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override Completa... | @Test public void accessLogger_returns_non_null_object() { AccessLogger obj = appServerConfig.accessLogger(); assertThat(obj).isNotNull(); } |
AppServerConfig implements ServerConfig { @Override public CompletableFuture<AppInfo> appInfo() { return guiceValues.appInfoFuture; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger... | @Test public void appInfo_returns_non_null_object() { CompletableFuture<AppInfo> obj = appServerConfig.appInfo(); assertThat(obj).isNotNull(); assertThat(obj.join()).isNotNull(); } |
AppServerConfig implements ServerConfig { @Override public RequestSecurityValidator requestSecurityValidator() { return guiceValues.basicAuthSecurityValidator; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Overri... | @Test public void requestSecurityValidator_returns_a_BasicAuthSecurityValidator() { AppServerConfig asc = new AppServerConfig(configForTesting); assertThat(asc.requestSecurityValidator()) .isNotNull() .isInstanceOf(BasicAuthSecurityValidator.class); } |
AppServerConfig implements ServerConfig { @Override public boolean isDebugActionsEnabled() { return guiceValues.debugActionsEnabled; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogge... | @Test public void isDebugActionsEnabled_comes_from_config() { assertThat(appServerConfig.isDebugActionsEnabled()) .isEqualTo(configForTesting.getBoolean("debugActionsEnabled")); } |
AppServerConfig implements ServerConfig { @Override public int endpointsPort() { return guiceValues.endpointsPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override Com... | @Test public void endpointsPort_comes_from_config() { assertThat(appServerConfig.endpointsPort()).isEqualTo(configForTesting.getInt("endpoints.port")); } |
AppServerConfig implements ServerConfig { @Override public int endpointsSslPort() { return guiceValues.endpointsSslPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Overri... | @Test public void endpointsSslPort_comes_from_config() { assertThat(appServerConfig.endpointsSslPort()).isEqualTo(configForTesting.getInt("endpoints.sslPort")); } |
FacesResourceProcessor { public static byte[] execute(URL url, InputStream input, String encoding) throws IOException { byte[] bytes; try { StringBuilder sb = new StringBuilder(); UnicodeReader reader = new UnicodeReader(input, encoding); try { char[] cbuf = new char[32]; int r; while ((r = reader.read(cbuf, 0, 32)) !=... | @Test public void testPage() throws FileNotFoundException, IOException { URL url; byte[] bytes; String encoding = (String) ResourceUtils.getProperty("app.encoding"); url = ResourceUtils.getClasspathResource("META-INF/pages/index.html"); bytes = FacesResourceProcessor.execute(url, url.openConnection().getInputStream(), ... |
PropertyResource extends AbstractResource implements BeanFactoryPostProcessor { public Object getProperty(String key) { return eppc.getProperty(key); } PropertyResource(); Object getProperty(String key); void setIgnoreResourceNotFound(boolean ignoreResourceNotFound); void setLocation(String location); void setLocations... | @Test public void testOrder(){ assertEquals(10, ((Integer) ResourceUtils.getProperty("test")).intValue()); } |
RESTAPICallPreHandler implements APICallPreHandler { public URL getBaseURL() throws MalformedURLException { if (url == null) { String mode = this.configurationMap.get(Constants.MODE); String urlString = this.configurationMap.get(Constants.ENDPOINT); if (urlString == null || urlString.trim().isEmpty()) { if (Constants.S... | @Test public void getBaseURL_returnsServiceEndpointIfSet() throws MalformedURLException { Map<String, String> configurations = new HashMap<String, String>(); configurations.put(Constants.ENDPOINT, "https: RESTAPICallPreHandler restapiCallPreHandler = new RESTAPICallPreHandler(configurations); URL result = restapiCallPr... |
RESTUtil { public static String formatURIPath(String pattern, Object[] parameters) { String formattedPath = null; Object[] finalParameters = null; if (pattern != null) { if (parameters != null && parameters.length == 1 && parameters[0] instanceof CreateFromAuthorizationCodeParameters) { finalParameters = splitParameter... | @Test(dependsOnMethods = { "testFormatURIPathTwoQS" }) public void testFormatURIPathMap() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); pathParameters.put("second", "value2"); String uriPa... |
SSLUtil { public static SSLContext getSSLContext(KeyManager[] keymanagers) throws SSLConfigurationException { try { SSLContext ctx = null; String protocol = CONFIG_MAP.get(Constants.SSLUTIL_PROTOCOL); try { ctx = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { log.warn("WARNING: Your system do... | @Test public void getSSLContextTest() throws SSLConfigurationException { Assert.assertNotNull(SSLUtil.getSSLContext(null)); } |
SSLUtil { public static SSLContext setupClientSSL(String certPath, String certPassword) throws SSLConfigurationException { SSLContext sslContext = null; try { KeyStore ks = p12ToKeyStore(certPath, certPassword); KMF.init(ks, certPassword.toCharArray()); sslContext = getSSLContext(KMF.getKeyManagers()); } catch (NoSuchA... | @Test public void setupClientSSLTest() throws SSLConfigurationException { Assert.assertNotNull(SSLUtil.setupClientSSL( UnitTestConstants.CERT_PATH, UnitTestConstants.CERT_PASSWORD)); }
@Test(expectedExceptions = SSLConfigurationException.class) public void setupClientSSLExceptionTest() throws Exception { Assert.assertN... |
ConnectionManager { public HttpConnection getConnection() { if(customSslContext != null) { return new DefaultHttpConnection(customSslContext); } else { return new DefaultHttpConnection(); } } private ConnectionManager(); static ConnectionManager getInstance(); HttpConnection getConnection(); HttpConnection getConnecti... | @Test public void getConnectionTest() { Assert.assertNotNull(http); }
@Test public void getConnectionWithHttpConfigurationForGoogleAppEngineTest() { HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setGoogleAppEngine(true); Assert.assertEquals(conn.getConnection(httpConfig).getClass(), GoogleAppEngine... |
HttpConnection { public abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException; HttpConnection(); Map<String, List<String>> getResponseHeaderMap(); String execute(String url, String payload,
Map<String, String> headers); InputStream executeWithStream(String url, Str... | @Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); connection.createAndconfigureHttpConnection(httpConfiguration); } |
HttpConnection { public String execute(String url, String payload, Map<String, String> headers) throws InvalidResponseDataException, IOException, InterruptedException, HttpErrorException { BufferedReader reader; String successResponse; InputStream result = executeWithStream(url, payload, headers); reader = new Buffered... | @Test public void executeTest() throws InvalidResponseDataException, HttpErrorException, ClientActionRequiredException, IOException, InterruptedException { httpConfiguration .setEndPointUrl("https: connection.createAndconfigureHttpConnection(httpConfiguration); String response = connection.execute("url", "payload", nul... |
ConfigManager { public void load(InputStream is) throws IOException { properties = new Properties(); properties.load(is); if (!propertyLoaded) { setPropertyLoaded(true); } } private ConfigManager(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMa... | @Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void loadTest(ConfigManager conf) { Assert.assertEquals(conf.isPropertyLoaded(), true); } |
ConfigManager { public Map<String, String> getValuesByCategory(String category) { String key; HashMap<String, String> map = new HashMap<String, String>(); for (Object obj : properties.keySet()) { key = (String) obj; if (key.contains(category)) { map.put(key, properties.getProperty(key)); } } return map; } private Conf... | @Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void getValuesByCategoryTest(ConfigManager conf) { Map<String, String> map = conf.getValuesByCategory("acct"); Iterator<String> itr = map.keySet().iterator(); while (itr.hasNext()) { assert (((String) itr.next()).contains("acct"));... |
ConfigManager { public Set<String> getNumOfAcct() { String key; Set<String> set = new HashSet<String>(); for (Object obj : properties.keySet()) { key = (String) obj; if (key.contains("acct")) { int pos = key.indexOf('.'); String acct = key.substring(0, pos); set.add(acct); } } return set; } private ConfigManager(); st... | @Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void getNumOfAcctTest(ConfigManager conf) { Set<String> set = conf.getNumOfAcct(); Iterator<String> itr = set.iterator(); while (itr.hasNext()) { assert (((String) itr.next()).contains("acct")); } } |
HttpConfiguration { public int getConnectionTimeout() { return connectionTimeout; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxH... | @Test(priority = 0) public void getConnectionTimeoutTest() { Assert.assertEquals(httpConf.getConnectionTimeout(), 0); } |
HttpConfiguration { public String getEndPointUrl() { return endPointUrl; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnec... | @Test(priority = 1) public void getEndPointUrlTest() { Assert.assertEquals(httpConf.getEndPointUrl(), null); } |
HttpConfiguration { public int getMaxHttpConnection() { return maxHttpConnection; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxH... | @Test(priority = 2) public void getMaxHttpConnectionTest() { Assert.assertEquals(httpConf.getMaxHttpConnection(), 10); } |
HttpConfiguration { public int getMaxRetry() { return maxRetry; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); v... | @Test(priority = 3) public void getMaxRetryTest() { Assert.assertEquals(httpConf.getMaxRetry(), 2); } |
HttpConfiguration { public String getProxyHost() { return proxyHost; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection... | @Test(priority = 4) public void getProxyHostTest() { Assert.assertEquals(httpConf.getProxyHost(), null); } |
HttpConfiguration { public int getProxyPort() { return proxyPort; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection();... | @Test(priority = 5) public void getProxyPortTest() { Assert.assertEquals(httpConf.getProxyPort(), -1); } |
HttpConfiguration { public int getReadTimeout() { return readTimeout; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnectio... | @Test(priority = 6) public void getReadTimeoutTest() { Assert.assertEquals(httpConf.getReadTimeout(), 0); } |
HttpConfiguration { public int getRetryDelay() { return retryDelay; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(... | @Test(priority = 7) public void getRetryDelayTest() { Assert.assertEquals(httpConf.getRetryDelay(), 1000); } |
HttpConfiguration { public boolean isProxySet() { return proxySet; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection()... | @Test(priority = 9) public void isProxySetTest() { Assert.assertEquals(httpConf.isProxySet(), false); } |
DefaultHttpConnection extends HttpConnection { @Override public void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException { this.config = clientConfiguration; URL url = new URL(this.config.getEndPointUrl()); Proxy proxy = null; String proxyHost = this.config.getProxyHost(); int pr... | @Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); defaultHttpConnection .createAndconfigureHttpConnection(httpConfiguration); }
@Test(dataProvider = "configParamsForProxy", dataProviderClass = DataPro... |
DefaultHttpConnection extends HttpConnection { @Override public void setupClientSSL(String certPath, String certKey) throws SSLConfigurationException { try { this.sslContext = SSLUtil.setupClientSSL(certPath, certKey); } catch (Exception e) { throw new SSLConfigurationException(e.getMessage(), e); } } DefaultHttpConnec... | @Test(expectedExceptions = SSLConfigurationException.class) public void checkSSLConfigurationExceptionTest() throws SSLConfigurationException { defaultHttpConnection.setupClientSSL("certPath", "certKey"); } |
GoogleAppEngineHttpConnection extends HttpConnection { @Override public void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException { this.config = clientConfiguration; URL url = new URL(this.config.getEndPointUrl()); this.connection = (HttpURLConnection) url .openConnection(Proxy.N... | @Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); googleAppEngineHttpConnection .createAndconfigureHttpConnection(httpConfiguration); }
@Test public void testCreateAndConfigureHttpConnection_setsReque... |
NVPUtil { public static Map<String, String> decode(String nvpString) throws UnsupportedEncodingException { String[] nmValPairs = nvpString.split("&"); Map<String, String> response = new HashMap<String, String>(); for (String nmVal : nmValPairs) { String[] field = nmVal.split("="); response.put( URLDecoder.decode(field[... | @Test public void decodeTest() throws UnsupportedEncodingException { String nvpString = "responseEnvelope.timestamp=2011-05-17T21%3A24%3A44.279-07%3A00&responseEnvelope.ack=Success&responseEnvelope.correlationId=ca0c236593634&responseEnvelope.build=1901705&invoiceID=INV2-AAWE-TAQW-7UXT-ZHBY&invoiceNumber=INV-00404"; Ma... |
NVPUtil { public static String encodeUrl(String value) throws UnsupportedEncodingException { return URLEncoder.encode(value, Constants.ENCODING_FORMAT); } private NVPUtil(); static Map<String, String> decode(String nvpString); static String encodeUrl(String value); } | @Test public void encodeTest() throws UnsupportedEncodingException { String value = "jbui-us-personal1@paypal.com"; Assert.assertEquals("jbui-us-personal1%40paypal.com", NVPUtil.encodeUrl(value)); } |
Lottery { void run() { List<String> emails = emailsSource.get(); System.out.println("Emails count: " + emails.size()); List<String> winners = machine.setSeed(seedString).draw(emails); System.out.println("Winners:"); winners.forEach(System.out::println); } Lottery(Supplier<List<String>> emailsSource, LotteryMachine mach... | @Test public void mockedWithSpy() { EmailsReader emailsReader = mock(EmailsReader.class); List<String> list = new ArrayList<>(); List<String> spy = spy(list); doReturn(1).when(spy).size(); doReturn("0").when(spy).get(0); when(emailsReader.get()).thenReturn(spy); String seedString = "Test"; LotteryMachine lotteryMachine... |
LotteryMachine { List<String> draw(List<String> emails) { System.out.println("Draw for the seed: " + seed); Random rnd = new Random(seed); Set<String> winners = new HashSet<>(); while (winners.size() < Math.min(winnersCount, emails.size())) { int index = rnd.nextInt(emails.size()); System.out.println("Ball: " + index);... | @Test public void oneEmail() { Assert.assertEquals(1, lotteryMachine.draw(Collections.singletonList("test")).size()); }
@Test public void fiveEmails() { List<String> result = lotteryMachine .draw(Arrays.asList("0", "1", "2", "3", "4")); assertEquals(5, result.size()); Assert.assertTrue(result.contains("0")); Assert.ass... |
ReflectionHelper { static Object getFieldValue(Object object, String name) { Field field = null; boolean isAccessible = true; try { field = object.getClass().getDeclaredField(name); isAccessible = field.isAccessible(); field.setAccessible(true); return field.get(object); } catch (NoSuchFieldException | IllegalAccessExc... | @Test public void getFieldValue() { Assert.assertEquals("A", ReflectionHelper.getFieldValue(new TestClass(1, "A"), "s")); Assert.assertEquals(1, ReflectionHelper.getFieldValue(new TestClass(1, "B"), "a")); } |
ReflectionHelper { static void setFieldValue(Object object, String name, Object value) { Field field = null; boolean isAccessible = true; try { field = object.getClass().getDeclaredField(name); isAccessible = field.isAccessible(); field.setAccessible(true); field.set(object, value); } catch (NoSuchFieldException | Ille... | @Test public void setFieldValue() { TestClass test = new TestClass(1, "A"); Assert.assertEquals("A", test.getS()); ReflectionHelper.setFieldValue(test, "s", "B"); Assert.assertEquals("B", test.getS()); } |
ReflectionHelper { static Object callMethod(Object object, String name, Object... args) { Method method = null; boolean isAccessible = true; try { method = object.getClass().getDeclaredMethod(name, toClasses(args)); isAccessible = method.isAccessible(); method.setAccessible(true); return method.invoke(object, args); } ... | @Test public void callMethod() { Assert.assertEquals("A", ReflectionHelper.callMethod(new TestClass(1, "A"), "getS")); TestClass test = new TestClass(1, "A"); ReflectionHelper.callMethod(test, "setDefault"); Assert.assertEquals("", test.getS()); } |
LotteryMachine { List<String> draw() { System.out.println("Draw for the seed: " + seed); Random rnd = new Random(seed); Set<String> winners = new HashSet<>(); while (winners.size() < winnersCount) { int index = rnd.nextInt(emails.size()); System.out.println("Ball: " + index); winners.add(emails.get(index)); } return ne... | @Test public void oneEmail() { Assert.assertEquals(1, new LotteryMachine(Collections.singletonList("test"), 5).draw().size()); }
@Test public void fiveEmails() { List<String> result = new LotteryMachine(Arrays.asList("0", "1", "2", "3", "4"), 5).draw(); Assert.assertEquals(5, result.size()); Assert.assertTrue(result.co... |
ATM { public int getBalance() { Iterator<Cell> iterator = first.iterator(); int balance = 0; while (iterator.hasNext()) { balance += iterator.next().getBalance(); } return balance; } ATM(List<Cell> cells); boolean withdraw(int requested); int getBalance(); } | @Test public void balanceSimple() { List<Cell> cells = new ArrayList<>(); cells.add(new Cell(5, 10)); ATM atm = new ATM(cells); Assert.assertEquals(50, atm.getBalance()); } |
Cell implements Comparable<Cell>, Iterable<Cell> { public boolean withdraw(int requested) { int expectedCount = Math.min(requested / nominal, count); int expectedCash = expectedCount * nominal; boolean nextCellResult = true; if (requested != expectedCash) { nextCellResult = next != null && next.withdraw(requested - exp... | @Test public void withdrawToBig() { Cell cell = new Cell(1, 100); Assert.assertFalse(cell.withdraw(101)); }
@Test public void withdrawDiscrete() { Cell cell = new Cell(5, 100); Assert.assertFalse(cell.withdraw(43)); } |
RecyclingPagerAdapter extends PagerAdapter { @Override public final Object instantiateItem(ViewGroup container, int position) { int viewType = getItemViewType(position); View view = null; if (viewType != IGNORE_ITEM_VIEW_TYPE) { view = recycleBin.getScrapView(position, viewType); } view = getView(position, view, contai... | @Test public void recycledViewIsNotAttemptedForIgnoredType() { LinearLayout container = new LinearLayout(context); final TextView child = new TextView(context); RecyclingPagerAdapter adapter = new RecyclingPagerAdapter(recycleBin) { @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TYPE; } @O... |
RecyclingPagerAdapter extends PagerAdapter { @Override public final void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; container.removeView(view); int viewType = getItemViewType(position); if (viewType != IGNORE_ITEM_VIEW_TYPE) { recycleBin.addScrapView(view, position, viewT... | @Test public void ignoredViewTypeIsNotRecycled() { LinearLayout container = new LinearLayout(context); TextView child = new TextView(context); container.addView(child); RecyclingPagerAdapter adapter = new RecyclingPagerAdapter(recycleBin) { @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TY... |
BrendaChebiOntology { public static Map<String, Set<String>> getApplicationToMainApplicationsMap( Map<String, Set<String>> isSubtypeOfRelationships, String applicationChebiId) { Set<String> mainApplicationsChebiId = isSubtypeOfRelationships.get(applicationChebiId); ArrayList<String> applicationsToVisit = new ArrayList<... | @Test public void testApplicationToMainApplicationMapping() { Map<String, Set<String>> isSubtypeOfRelationships = new HashMap<>(); isSubtypeOfRelationships.put("1", new HashSet<>(Arrays.asList("2", "3"))); isSubtypeOfRelationships.put("2", Collections.singleton("4")); isSubtypeOfRelationships.put("3", Collections.singl... |
UniprotSeqEntry extends SequenceEntry { public Long getOrgId() { return this.orgId; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs... | @Test public void testOrgId() { assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000399L, seqEntries.get(0).getOrgId()); } |
UniprotSeqEntry extends SequenceEntry { public String getOrg() { return this.org; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs()... | @Test public void testOrg() { assertEquals("tests whether organism names are extracted accurately", "Arabidopsis thaliana", seqEntries.get(0).getOrg()); } |
UniprotSeqEntry extends SequenceEntry { public String getSeq() { return this.sequence; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingS... | @Test public void testSeq() { assertEquals("tests whether sequences are extracted accurately", sequences.get(0), seqEntries.get(0).getSeq()); } |
UniprotSeqEntry extends SequenceEntry { public String getEc() { return this.ec; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); ... | @Test public void testEc() { assertEquals("tests whether ec_numbers are extracted accurately", "1.1.1.1", seqEntries.get(0).getEc()); } |
UniprotSeqEntry extends SequenceEntry { public List<JSONObject> getRefs() { return this.references; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq>... | @Test public void testReferences() { List<JSONObject> pmidRefs = new ArrayList<>(); List<String> pmids = Arrays.asList("2937058", "7851777", "8844162", "8587508", "11018155", "11158375", "11130712", "14593172", "10382288", "3377754", "2277648", "12231733", "8787023", "9522467", "9611167", "9880346", "11402191", "114022... |
GenbankSeqEntry extends SequenceEntry { public DBObject getMetadata() { return this.metadata; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> ge... | @Test public void testMetadata() { ArrayList<DBObject> metadatas = new ArrayList<>(); List<String> geneSynonyms = Arrays.asList("STP", "STP1", "SULT1A1"); List<String> emptyGeneSynonyms = new ArrayList<>(); JSONObject obj = new JSONObject(); JSONObject accessionObject = new JSONObject(); accessionObject.put("genbank_pr... |
GenbankSeqEntry extends SequenceEntry { public JSONObject getAccession() { return this.accessions; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<Strin... | @Test public void testAccession() { JSONObject accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("CUB13083"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), proteinSeqEntries.get(0).getAccession().toString... |
GenbankSeqEntry extends SequenceEntry { public String getGeneName() { return this.geneName; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getG... | @Test public void testGeneName() { assertEquals("tests whether gene name is extracted accurately", null, proteinSeqEntries.get(0).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ST1A1_HUMAN", proteinSeqEntries.get(1).getGeneName()); assertEquals("tests whether gene name is extracted acc... |
GenbankSeqEntry extends SequenceEntry { public List<String> getGeneSynonyms() { return this.geneSynonyms; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); Lis... | @Test public void testGeneSynonyms() { List<String> geneSynonyms = Arrays.asList("STP", "STP1", "SULT1A1"); assertEquals("tests whether gene synonyms are extracted accurately", geneSynonyms, proteinSeqEntries.get(1).getGeneSynonyms()); geneSynonyms = new ArrayList<>(); assertEquals("tests whether gene synonyms are extr... |
GenbankSeqEntry extends SequenceEntry { public List<String> getProductName() { return this.productNames; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List... | @Test public void testProductName() { assertEquals("tests whether product names are extracted accurately", Collections.singletonList("Arylamine N-acetyltransferase"), proteinSeqEntries.get(0).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("Sulfotransfer... |
HMDBParser { protected Chemical extractChemicalFromXMLDocument(Document doc) throws JaxenException, JSONException { String hmdbId = getText(HMDB_XPATH.HMDB_ID_TEXT, doc); String primaryName = getText(HMDB_XPATH.PRIMARY_NAME_TEXT, doc); String iupacName = getText(HMDB_XPATH.IUPAC_NAME_TEXT, doc); List<String> synonyms =... | @Test public void testExtractChemicalFromXMLDocument() throws Exception { MockedMongoDB mockedDb = new MockedMongoDB(); HMDBParser parser = HMDBParser.Factory.makeParser(mockedDb.getMockMongoDB()); Chemical chem = parser.extractChemicalFromXMLDocument(doc); assertEquals("Canonical name matches", "acetaminophen", chem.g... |
GenbankSeqEntry extends SequenceEntry { public Long getOrgId() { return this.orgId; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynon... | @Test public void testOrgId() { assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000648L, proteinSeqEntries.get(0).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000002681L, proteinSeqEntries.get(1).getOrgId()); assertEquals("tests whether organism... |
GenbankSeqEntry extends SequenceEntry { public String getOrg() { return this.org; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonym... | @Test public void testOrg() { assertEquals("tests whether organism names are extracted accurately", "Bacillus cereus", proteinSeqEntries.get(0).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Homo sapiens", proteinSeqEntries.get(1).getOrg()); assertEquals("tests whether organism names ... |
GenbankSeqEntry extends SequenceEntry { public String getSeq() { return this.sequence; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSy... | @Test public void testSeq() { assertEquals("tests whether sequences are extracted accurately", sequences.get(0), proteinSeqEntries.get(0).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(1), proteinSeqEntries.get(1).getSeq()); assertEquals("tests whether sequences are extracted ... |
GenbankSeqEntry extends SequenceEntry { public String getEc() { return this.ec; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(... | @Test public void testEc() { assertEquals("tests whether ec_numbers are extracted accurately", "2.3.1.5", proteinSeqEntries.get(0).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "2.8.2.1", proteinSeqEntries.get(1).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "... |
GenbankSeqEntry extends SequenceEntry { public List<JSONObject> getPmids() { return this.pmids; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> ... | @Test public void testPMID() { List<JSONObject> pmidRefs = new ArrayList<>(); assertEquals("tests whether PMIDs were assigned accurately", pmidRefs, proteinSeqEntries.get(0).getPmids()); List<String> pmids = Arrays.asList("8363592", "8484775", "8423770", "8033246", "7864863", "7695643", "7581483", "8912648", "8924211",... |
GenbankSeqEntry extends SequenceEntry { public List<JSONObject> getPatents() { return this.patents; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<Stri... | @Test public void testPatents() { List<JSONObject> patentRefs = new ArrayList<>(); assertEquals("tests whether Patent references were assigned accurately", patentRefs, proteinSeqEntries.get(0).getPatents()); JSONObject obj = new JSONObject(); obj.put("src", "Patent"); obj.put("country_code", "JP"); obj.put("patent_numb... |
PubchemParser { public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader) throws XMLStreamException, JaxenException { Document bufferDoc = null; Element currentElement = null; StringBuilder textBuffer = null; while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch (event.getE... | @Test public void testParserProcessesTheCorrectChemicals() throws Exception { File testFile = new File(this.getClass().getResource("CompoundTest.xml.gz").getFile()); String expectedInchi1 = "InChI=1S/C18H27FN2/c1-2-14-11-17(20-16-5-3-4-6-16)13-21(12-14)18-9-7-15(19)8-10-18/h7-10,14,16-17,20H,2-6,11-13H2,1H3"; String ex... |
MechanisticValidator extends BiointerpretationProcessor { public void init() throws IOException, ReactionException, LicenseProcessingException { erosCorpus = new ErosCorpus(); erosCorpus.loadValidationCorpus(); blacklistedInchisCorpus = new BlacklistedInchisCorpus(); blacklistedInchisCorpus.loadCorpus(); projector = ne... | @Test public void testMechanisticValidatorIsMatchingTheCorrectROsToReaction() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1S/p+1"); idToInchi.put(2L, "InChI=1S/C5H10O/c1-3-4-5(2)6/h3-4H2,1-2H3"); idToInchi.put(3L, "InChI=1S... |
ImportantChemicalsWikipedia { public String formatInchiString(String inchi) { String tmpInchi = inchi.replaceAll("\\s+",""); String formattedInchi = tmpInchi.replaceAll("InChI[0-9]?", "InChI"); return formattedInchi; } ImportantChemicalsWikipedia(); String extractInchiFromLine(String line); String formatInchiString(Str... | @Test public void testFormatInchiString() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.formatI... |
ErosCorpus implements Iterable<Ero> { public void filterCorpusBySubstrateCount(Integer count) { filterCorpus(ro -> ro.getSubstrate_count().equals(count)); } ErosCorpus(List<Ero> ros); ErosCorpus(); List<Ero> getRos(); void setRos(List<Ero> eros); void loadValidationCorpus(); void loadCorpus(InputStream erosStream); Li... | @Test public void filterCorpusBySubstrateCount() throws Exception { ErosCorpus fullCorpus = new ErosCorpus(); fullCorpus.loadValidationCorpus(); ErosCorpus corpusOneSubstrate = new ErosCorpus(); corpusOneSubstrate.loadValidationCorpus(); corpusOneSubstrate.filterCorpusBySubstrateCount(1); assertEquals("One substrate ER... |
FullReactionBuilder { public Reactor buildReaction(List<RxnMolecule> rxnMolecules, Reactor seedReactor) throws ReactionException { if (!DbAPI.areAllOneSubstrate(rxnMolecules) || !DbAPI.areAllOneProduct(rxnMolecules)) { throw new IllegalArgumentException("FullReactionBuilder only handles one substrate, one product react... | @Test public void testTwoReactionsOneReactorMatchesBoth() throws ReactionException, IOException { Mockito.when(mockSearcher.getNextReactor()) .thenReturn(reactorMatch) .thenReturn(null); FullReactionBuilder reactionBuilder = new FullReactionBuilder(mockMcs, mockSearcher, PROJECTOR); Reactor fullReactor = reactionBuilde... |
OneSubstrateSubstructureSar implements Sar { @Override public boolean test(List<Molecule> substrates) { if (substrates.size() != 1) { return false; } searcher.setTarget(substrates.get(0)); try { return searcher.findFirst() != null; } catch (SearchException e) { LOGGER.error("Error on testing substrates with SAR %s", ge... | @Test public void oneSubstrateContainsSubstructure() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(containsBenzene); assertTrue("Substrate contains substructure.", sar.test(substrates)); }
@Test public void oneSubstrateDoesntContainsSubstructure()... |
ImportantChemicalsWikipedia { public String extractInchiFromLine(String line) { Matcher inchiMatcher = INCHI_PATTERN.matcher(line); if (inchiMatcher.matches()) { return inchiMatcher.group(1); } return null; } ImportantChemicalsWikipedia(); String extractInchiFromLine(String line); String formatInchiString(String inchi)... | @Test public void testExtractInchiFromLine() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.extr... |
McsCalculator { public Molecule getMCS(List<Molecule> molecules) { if (molecules.isEmpty()) { throw new IllegalArgumentException("Cannot get MCS of empty list of molecules."); } Molecule substructure = molecules.get(0); for (Molecule mol : molecules.subList(1, molecules.size())) { substructure = getMcsOfPair(substructu... | @Test public void testMcsCalculatorSimplePairs() throws IOException { McsCalculator calculator = new McsCalculator(McsCalculator.SAR_OPTIONS); Molecule mcs12 = calculator.getMCS(Arrays.asList(methylPyreneMol1, methylPyreneMol2)); Molecule mcs13 = calculator.getMCS(Arrays.asList(methylPyreneMol1, methylPyreneMol3)); Mol... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.