method2testcases
stringlengths
118
3.08k
### Question: NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow maxValue() { return quantilesSketch.getMaxValue(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer: @Test public void testMaxValue() throws StandardException { Assert.assertEquals(maxRow,impl.maxValue()); }
### Question: NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public ExecRow minValue() { return quantilesSketch.getMinValue(); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer: @Test public void testMinValue() throws StandardException { Assert.assertEquals(minRow,impl.minValue()); }
### Question: NonUniqueKeyStatisticsImpl implements ItemStatistics<ExecRow> { @Override public long selectivity(ExecRow element) { long count = frequenciesSketch.getEstimate(element); if (count>0) return count; return (long) (quantilesSketch.getN()/thetaSketch.getEstimate()); } NonUniqueKeyStatisticsImpl(ExecRow execRow); NonUniqueKeyStatisticsImpl(ExecRow execRow, ItemsSketch quantilesSketch, com.yahoo.sketches.frequencies.ItemsSketch<ExecRow> frequenciesSketch, Sketch thetaSketch ); @Override ExecRow minValue(); @Override long nullCount(); @Override long notNullCount(); @Override long cardinality(); @Override ExecRow maxValue(); @Override long totalCount(); @Override long selectivity(ExecRow element); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation); @Override long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop); @Override void update(ExecRow execRow); @Override String toString(); @Override void writeExternal(ObjectOutput out); @Override void readExternal(ObjectInput in); @Override ItemStatistics<ExecRow> getClone(); @Override Type getType(); @Override long selectivityExcludingValueIfSkewed(ExecRow value); }### Answer: @Test public void testNullSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(null)); } @Test public void testEmptySelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(new ValueRow(3))); } @Test public void testIndividualSelectivity() throws StandardException { Assert.assertEquals(1,impl.selectivity(minRow)); }
### Question: CurrentDatetime { public Date getCurrentDate() { if (currentDate == null) { setCurrentDatetime(); currentDate = Date.valueOf(currentDateTime.toLocalDate()); } return currentDate; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }### Answer: @Test public void testGetCurrentDate() { LocalDate local = LocalDate.now(); Date date = cut.getCurrentDate(); long difference = ChronoUnit.DAYS.between(local, date.toLocalDate()); assertTrue(difference <= 1); }
### Question: CurrentDatetime { public Time getCurrentTime() { if (currentTime == null) { setCurrentDatetime(); currentTime = Time.valueOf(currentDateTime.toLocalTime()); } return currentTime; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }### Answer: @Test public void testGetCurrentTime() { LocalTime local = LocalTime.now(); Time time = cut.getCurrentTime(); long difference = ChronoUnit.SECONDS.between(local, time.toLocalTime()); assertTrue(difference <= 1); }
### Question: CurrentDatetime { public Timestamp getCurrentTimestamp() { if (currentTimestamp == null) { setCurrentDatetime(); currentTimestamp = Timestamp.valueOf(currentDateTime); int mask = POWERS_OF_10[9 - timestampPrecision]; int newNanos = currentTimestamp.getNanos() / mask * mask; currentTimestamp.setNanos(newNanos); } return currentTimestamp; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }### Answer: @Test public void testGetCurrentTimestamp() { LocalDateTime local = LocalDateTime.now(); Timestamp timestamp = cut.getCurrentTimestamp(); long difference = ChronoUnit.MILLIS.between(local, timestamp.toLocalDateTime()); assertTrue(difference <= 500); }
### Question: 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 forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }### Answer: @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.getCurrentTimestamp(); assertNotEquals(timestamp, newTimestamp); }
### Question: 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 = physicalAndLogicalToHLC(hlc[0],hlc[1]); if (atomicHLC.compareAndSet(currentHLC,returnHLC)) return returnHLC; } } long sendOrLocalEvent(); long receiveEvent(long message); static long clockTimestampToHLC(long timestamp, TimeUnit timeUnit); static long[] HLCToPhysicalAndLogical(long htTimestamp); static long physicalAndLogicalToHLC(long physical, long logical); static final int hlcNumBitsToShift; static final int hlcLogicalBitsMask; }### Answer: @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; } }
### Question: 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 nextIsNull(int position); BitIndex getCurrentIndex(); byte[] getData(int position); MultiFieldDecoder getEntryDecoder(); boolean seekForward(MultiFieldDecoder decoder, int position); ByteBuffer nextAsBuffer(MultiFieldDecoder decoder, int position); void accumulate(int position, EntryAccumulator accumulator, byte[] buffer, int offset, int length); void close(); long length(); void nextField(MultiFieldDecoder mutationDecoder, int indexPosition, ByteSlice rowSlice); @Override MultiFieldDecoder get(); }### Answer: @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-null fields", 1, bitIndex.cardinality()); }
### Question: 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 (ed == null) { continue; } if (ed.getName().equals(interests.getKey())) { try { Object ret = method.invoke(event); if (ret == null) break; String val = ret.toString(); if (interests.getValue().equals(val)) { matches = true; break; } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } } return matches; } boolean matches(NewtonEvent event, SagaInterest interests); }### Answer: @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 world" ); final boolean result = matcher.matches(testEvent, sagaInterest); assertTrue(result); }
### Question: 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 event); }### Answer: @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 Exception { Handler handler = new Handler(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new Event1()); assertTrue(handler.event instanceof Event1); } @Test public void canInvokeClassParentHandler() throws Exception { HandlerWithParent handler = new HandlerWithParent(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new NonExplicitMatchEvent()); assertTrue(handler.event instanceof NonExplicitMatchEvent); }
### Question: MuonEventSourceRepository implements EventSourceRepository<A> { @Override public CompletableFuture<A> loadAsync(Object aggregateIdentifier) { return CompletableFuture.supplyAsync(() -> load(aggregateIdentifier)); } MuonEventSourceRepository(Class<A> type, AggregateRootSnapshotRepository snapshotRepository, NewtonEventClient aggregateEventClient, EventStreamProcessor eventStreamProcessor, String appName); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier, Long expectedVersion); @Override A load(Object aggregateIdentifier); @Override A load(Object aggregateIdentifier, Long version); @Override A newInstance(Callable<A> factoryMethod); @Override List<NewtonEvent> save(A aggregate); @Override List<NewtonEvent> delete(A aggregate); @Override Publisher<NewtonEvent> replay(Object aggregateIdentifier); @Override Publisher<AggregateRootUpdate<A>> susbcribeAggregateUpdates(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeColdHot(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeHot(Object aggregateIdentifier); static T executeCausedBy(NewtonEvent ev, Supplier<T> run); }### Answer: @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()); } @Test public void throwsExceptionOnNonExistingAggregateAsync() throws ExecutionException, InterruptedException { final AtomicBoolean bool = new AtomicBoolean(false); repository.loadAsync("no-such-id-as-this").exceptionally(throwable -> { bool.set(true); return null; }).join(); assertTrue(bool.get()); }
### Question: 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(); snapshotRepository.persist(aggregate); return events; } MuonEventSourceRepository(Class<A> type, AggregateRootSnapshotRepository snapshotRepository, NewtonEventClient aggregateEventClient, EventStreamProcessor eventStreamProcessor, String appName); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier, Long expectedVersion); @Override A load(Object aggregateIdentifier); @Override A load(Object aggregateIdentifier, Long version); @Override A newInstance(Callable<A> factoryMethod); @Override List<NewtonEvent> save(A aggregate); @Override List<NewtonEvent> delete(A aggregate); @Override Publisher<NewtonEvent> replay(Object aggregateIdentifier); @Override Publisher<AggregateRootUpdate<A>> susbcribeAggregateUpdates(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeColdHot(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeHot(Object aggregateIdentifier); static T executeCausedBy(NewtonEvent ev, Supplier<T> run); }### Answer: @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.class.getSimpleName(), events.get(0).getEventType()); }
### Question: 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(); }### Answer: @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().equals("ZZZ")); }
### Question: 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 startWith(NewtonEvent event); @Override void handle(NewtonEvent event); }### Answer: @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()); assertNotNull(saga.event); }
### Question: 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 mac = null; URL url = null; try { byte[] secretyKeyBytes = secretKey.getBytes(UTF8_CHARSET); SecretKeySpec secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM); mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(secretKeySpec); url = new URL(urlString); } catch (Exception e) { throw new RuntimeException(e); } String protocol = url.getProtocol(); String host = url.getHost(); String path = url.getPath(); String query = url.getQuery(); Map<String, String> params = new HashMap<String, String>(); for (String pair: query.split("&")) { String[] keyValue = pair.split("="); params.put(keyValue[0], keyValue[1]); } if(!params.containsKey("Timestamp")) params.put("Timestamp", timestamp()); SortedMap<String, String> sortedParamMap = new TreeMap<String, String>(params); String canonicalQS = canonicalize(sortedParamMap); String toSign = "GET\n" + host + "\n" + path + "\n" + canonicalQS; String hmac = hmac(mac, toSign); String sig = percentEncodeRfc3986(hmac); return protocol + ": } static String sign(String urlString, String algorithm, String secretKey); }### Answer: @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); }
### Question: 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 getCurrentTimeStringNoSeparator(); static String formatStringDate(String date); }### Answer: @Test public void shouldPrintDublinTime() { System.out.print(DateUtils.getCurrentTimeString()); }
### Question: 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)); } nowPlayingViewModel.addToAdapter(movieViewInfoList); nowPlayingViewModel.showInProgress(false); } @Inject NowPlayingPresenterImpl(NowPlayingViewModel nowPlayingViewModel, NowPlayingInteractor nowPlayingInteractor); @Override void loadMoreInfo(); @Override void onStart(); @Override void onStop(); @Override void start(Bundle savedInstanceState); @Override void dataRestored(); @Override void infoLoaded(List<MovieInfo> movieInfoList); @Override void errorLoadingInfoData(); }### Answer: @Test public void infoLoaded() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); ArgumentCaptor<List<MovieViewInfo>> argumentCaptor = ArgumentCaptor.forClass(List.class); nowPlayingPresenter.infoLoaded(movieInfoList); verify(mockNowPlayingViewModel).addToAdapter(anyListOf(MovieViewInfo.class)); verify(mockNowPlayingViewModel).showInProgress(false); verify(mockNowPlayingViewModel).addToAdapter(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().size()).isEqualTo(1); }
### Question: NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel { @Override public void errorLoadingInfoData() { nowPlayingViewModel.showError(); loadMoreInfo(); } @Inject NowPlayingPresenterImpl(NowPlayingViewModel nowPlayingViewModel, NowPlayingInteractor nowPlayingInteractor); @Override void loadMoreInfo(); @Override void onStart(); @Override void onStop(); @Override void start(Bundle savedInstanceState); @Override void dataRestored(); @Override void infoLoaded(List<MovieInfo> movieInfoList); @Override void errorLoadingInfoData(); }### Answer: @Test public void errorLoadingInfoData() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); nowPlayingPresenter.errorLoadingInfoData(); verify(mockNowPlayingViewModel).showError(); verify(mockNowPlayingInteractor).loadMoreInfo(); }
### Question: 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); AccountData clone(); String toCsv(); @Override String toString(); static String randomAdultDateOfBirth(); static String randomDateOfBirth(int minAge, int maxAge); static final String DEFAULT_COUNTRY; }### Answer: @Test public void testAccountData() { AccountData account = new AccountData(); assertThat(account.getDob()).isNotBlank(); }
### Question: 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 = matcher.group("login"); String pass = matcher.group("pass"); int port = -1; if (matcher.group("port") != null) { port = Integer.parseInt(matcher.group("port")); } if (port < 0 && protocol == null) { protocol = "http"; port = DEFAULT_PORT; } else { if (protocol == null) { for (Entry<String, Integer> entry : DEFAULT_MAPPING.entrySet()) { if (entry.getValue() == port) { protocol = entry.getKey(); break; } } if (protocol == null) { protocol = DEFAULT_PROTOCOL; } } else if (port < 0) { if (DEFAULT_MAPPING.get(protocol) != null) { port = DEFAULT_MAPPING.get(protocol); } else { port = DEFAULT_PORT; } } } Type type = StringUtils.startsWith(protocol, "socks") ? Type.SOCKS : Type.HTTP; return new HttpProxy(host, port, login, pass, type, protocol); } else { logger.warn("Cannot load URI [{}] as a HTTP Proxy", uri); return null; } } HttpProxy(String host, int port, String login, String pass); HttpProxy(String host, int port, String login, String pass, Type type, String protocol); HttpProxy(String host, int port); static HttpProxy fromURI(String uri); @Override OkHttpClient getClient(); String toURI(); String toString(); @Override String getHost(); static final String URI_REGEXP; }### Answer: @Test public void encodedCharUriTest() { String uri = "user:p%[email protected]:3128"; HttpProxy proxy = HttpProxy.fromURI(uri); assertThat(proxy).isNotNull(); }
### Question: SequenceAccountGenerator implements AccountGenerator { public void init() { emailGenerator = new PlusTrickEmailGenerator(baseEmail); SequenceUsernameGenerator seqUsernameGenerator = new SequenceUsernameGenerator(usernamePattern, startFrom); if (startFrom + nbAccounts > seqUsernameGenerator.getMaxSequence() + 1) { throw new IllegalArgumentException("Sequence would overflow format, use more *"); } usernameGenerator = seqUsernameGenerator; passwordGenerator = new SinglePasswordGenerator(staticPassword); initDone = true; } void init(); @Override boolean hasNext(); @Override AccountData next(); }### Answer: @Test public void maxStartAt1Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(1); generator.setNbAccounts(99); generator.init(); } @Test(expected = IllegalArgumentException.class) public void overFlowStartAt1Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(1); generator.setNbAccounts(100); generator.init(); } @Test public void maxStartAt0Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(0); generator.setNbAccounts(100); generator.init(); } @Test(expected = IllegalArgumentException.class) public void overFlowStartAt0Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(0); generator.setNbAccounts(101); generator.init(); }
### Question: 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 ImageTypersConfigurationException("Missing ImageTypers Access Token"); } } ImageTypersProvider(CaptchaQueue queue, String apiKey); static CaptchaProvider getInstance(CaptchaQueue queue, String apiKey); @Override void run(); double getBalance(); static final String INSUFFICIENT_BALANCE; }### Answer: @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("Start Provider"); new Thread(provider).start(); logger.info("Provider Started, get Balance"); double balance = provider.getBalance(); logger.info("Balance is : {}", balance); CaptchaRequest request = queue.addRequest(new CaptchaRequest("test1")); CaptchaRequest request2 = queue.addRequest(new CaptchaRequest("test2")); while (request.getResponse() == null || request2.getResponse() == null) { Thread.sleep(500); } logger.info("Response 1 given : {}", request.getResponse()); logger.info("Response 2 given : {}", request2.getResponse()); Thread.sleep(2000); }
### Question: 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 setCountry(String country); AccountData clone(); String toCsv(); @Override String toString(); static String randomAdultDateOfBirth(); static String randomDateOfBirth(int minAge, int maxAge); static final String DEFAULT_COUNTRY; }### Answer: @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 = Integer.parseInt((rdob.substring(0, 4))); int month = Integer.parseInt((rdob.substring(5, 7))); int day = Integer.parseInt((rdob.substring(8, 10))); assertThat(year).isGreaterThan(1900); assertThat(month).isLessThanOrEqualTo(12); assertThat(day).isLessThanOrEqualTo(31); int age = LocalDateTime.now().getYear() - year; assertThat(age).isGreaterThanOrEqualTo(18); assertThat(age).isLessThanOrEqualTo(80); } }
### Question: ToFileLinkActivator implements LinkActivator { @Override public boolean activateLink(Activation link) { FileLogger.logStatus(link, FileLogger.SKIPPED); return true; } @Override boolean activateLink(Activation link); @Override void start(); }### Answer: @Test public void testActivateLink() { ToFileLinkActivator activator = new ToFileLinkActivator(); activator.activateLink(new Activation("Test", "[email protected]")); }
### Question: 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(); }### Answer: @Test public void healthCheckEndpoint_should_match_all_http_methods() { assertThat(healthCheckEndpoint.requestMatcher().isMatchAllMethods()).isTrue(); }
### Question: 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()); } @Override CompletableFuture<ResponseInfo<Void>> execute( RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx ); @Override Matcher requestMatcher(); }### Answer: @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); }
### Question: AppServerConfig implements ServerConfig { @Override public AccessLogger accessLogger() { return accessLogger; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void accessLogger_returns_non_null_object() { AccessLogger obj = appServerConfig.accessLogger(); assertThat(obj).isNotNull(); }
### Question: AppServerConfig implements ServerConfig { @Override public CompletableFuture<AppInfo> appInfo() { return guiceValues.appInfoFuture; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void appInfo_returns_non_null_object() { CompletableFuture<AppInfo> obj = appServerConfig.appInfo(); assertThat(obj).isNotNull(); assertThat(obj.join()).isNotNull(); }
### Question: AppServerConfig implements ServerConfig { @Override public RequestSecurityValidator requestSecurityValidator() { return guiceValues.basicAuthSecurityValidator; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void requestSecurityValidator_returns_a_BasicAuthSecurityValidator() { AppServerConfig asc = new AppServerConfig(configForTesting); assertThat(asc.requestSecurityValidator()) .isNotNull() .isInstanceOf(BasicAuthSecurityValidator.class); }
### Question: AppServerConfig implements ServerConfig { @Override public boolean isDebugActionsEnabled() { return guiceValues.debugActionsEnabled; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void isDebugActionsEnabled_comes_from_config() { assertThat(appServerConfig.isDebugActionsEnabled()) .isEqualTo(configForTesting.getBoolean("debugActionsEnabled")); }
### Question: AppServerConfig implements ServerConfig { @Override public int endpointsPort() { return guiceValues.endpointsPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void endpointsPort_comes_from_config() { assertThat(appServerConfig.endpointsPort()).isEqualTo(configForTesting.getInt("endpoints.port")); }
### Question: AppServerConfig implements ServerConfig { @Override public int endpointsSslPort() { return guiceValues.endpointsSslPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }### Answer: @Test public void endpointsSslPort_comes_from_config() { assertThat(appServerConfig.endpointsSslPort()).isEqualTo(configForTesting.getInt("endpoints.sslPort")); }
### Question: 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(String[] locations); void setLocations(List<String> locations); void setWildcardLocations(String[] locations); void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory); Resource[] getResources(); }### Answer: @Test public void testOrder(){ assertEquals(10, ((Integer) ResourceUtils.getProperty("test")).intValue()); }
### Question: 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 does not support TLSv1.2. Per PCI Security Council mandate (https: ctx = SSLContext.getInstance(protocol); } ctx.init(keymanagers, null, null); return ctx; } catch (Exception e) { throw new SSLConfigurationException(e.getMessage(), e); } } static SSLContext getSSLContext(KeyManager[] keymanagers); static SSLContext setupClientSSL(String certPath, String certPassword); static boolean validateCertificateChain(Collection<X509Certificate> clientCerts, Collection<X509Certificate> trustCerts, String authType); static InputStream downloadCertificateFromPath(String urlPath); static InputStream downloadCertificateFromPath(String urlPath, Map<String, String> configurations); @SuppressWarnings("unchecked") static Collection<X509Certificate> getCertificateFromStream(InputStream stream); static long crc32(String data); static Boolean validateData(Collection<X509Certificate> clientCerts, String algo, String actualSignatureEncoded, String expectedSignature, String requestBody, String webhookId); }### Answer: @Test public void getSSLContextTest() throws SSLConfigurationException { Assert.assertNotNull(SSLUtil.getSSLContext(null)); }
### Question: ConnectionManager { public HttpConnection getConnection() { if(customSslContext != null) { return new DefaultHttpConnection(customSslContext); } else { return new DefaultHttpConnection(); } } private ConnectionManager(); static ConnectionManager getInstance(); HttpConnection getConnection(); HttpConnection getConnection(HttpConfiguration httpConfig); void configureCustomSslContext(SSLContext sslContext); }### Answer: @Test public void getConnectionTest() { Assert.assertNotNull(http); } @Test public void getConnectionWithHttpConfigurationForGoogleAppEngineTest() { HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setGoogleAppEngine(true); Assert.assertEquals(conn.getConnection(httpConfig).getClass(), GoogleAppEngineHttpConnection.class); }
### Question: 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, String payload, Map<String, String> headers); abstract void setupClientSSL(String certPath, String certKey); abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }### Answer: @Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); connection.createAndconfigureHttpConnection(httpConfiguration); }
### Question: 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 BufferedReader(new InputStreamReader(result, Constants.ENCODING_FORMAT)); successResponse = read(reader); return successResponse; } HttpConnection(); Map<String, List<String>> getResponseHeaderMap(); String execute(String url, String payload, Map<String, String> headers); InputStream executeWithStream(String url, String payload, Map<String, String> headers); abstract void setupClientSSL(String certPath, String certKey); abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }### Answer: @Test public void executeTest() throws InvalidResponseDataException, HttpErrorException, ClientActionRequiredException, IOException, InterruptedException { httpConfiguration .setEndPointUrl("https: connection.createAndconfigureHttpConnection(httpConfiguration); String response = connection.execute("url", "payload", null); Assert.assertTrue(response.contains("<ack>Failure</ack>")); }
### Question: 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> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }### Answer: @Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void loadTest(ConfigManager conf) { Assert.assertEquals(conf.isPropertyLoaded(), true); }
### Question: 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 ConfigManager(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }### Answer: @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")); } }
### Question: 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(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }### Answer: @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")); } }
### Question: 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 getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 0) public void getConnectionTimeoutTest() { Assert.assertEquals(httpConf.getConnectionTimeout(), 0); }
### Question: 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 getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 1) public void getEndPointUrlTest() { Assert.assertEquals(httpConf.getEndPointUrl(), null); }
### Question: 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 getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 2) public void getMaxHttpConnectionTest() { Assert.assertEquals(httpConf.getMaxHttpConnection(), 10); }
### Question: 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(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 3) public void getMaxRetryTest() { Assert.assertEquals(httpConf.getMaxRetry(), 2); }
### Question: 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(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 4) public void getProxyHostTest() { Assert.assertEquals(httpConf.getProxyHost(), null); }
### Question: 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(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 5) public void getProxyPortTest() { Assert.assertEquals(httpConf.getProxyPort(), -1); }
### Question: 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 getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 6) public void getReadTimeoutTest() { Assert.assertEquals(httpConf.getReadTimeout(), 0); }
### Question: 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(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 7) public void getRetryDelayTest() { Assert.assertEquals(httpConf.getRetryDelay(), 1000); }
### Question: 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(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }### Answer: @Test(priority = 9) public void isProxySetTest() { Assert.assertEquals(httpConf.isProxySet(), false); }
### Question: 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); } } DefaultHttpConnection(); DefaultHttpConnection(SSLContext sslContext); @Override void setupClientSSL(String certPath, String certKey); @Override void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }### Answer: @Test(expectedExceptions = SSLConfigurationException.class) public void checkSSLConfigurationExceptionTest() throws SSLConfigurationException { defaultHttpConnection.setupClientSSL("certPath", "certKey"); }
### Question: 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.NO_PROXY); this.connection.setDoInput(true); this.connection.setDoOutput(true); if ("PATCH".equals(config.getHttpMethod().toUpperCase())) { this.connection.setRequestMethod("POST"); this.requestMethod = "PATCH"; } else { this.connection.setRequestMethod(config.getHttpMethod()); } this.connection.setConnectTimeout(this.config.getConnectionTimeout()); this.connection.setReadTimeout(this.config.getReadTimeout()); switch (config.getInstanceFollowRedirects()) { case NO_DO_NOT_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(false); break; case YES_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(true); break; } } @Override void setupClientSSL(String certPath, String certKey); @Override void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); @Override InputStream executeWithStream(String url, String payload, Map<String, String> headers); }### Answer: @Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); googleAppEngineHttpConnection .createAndconfigureHttpConnection(httpConfiguration); } @Test public void testCreateAndConfigureHttpConnection_setsRequestMethodToPost() throws IOException { httpConfiguration.setEndPointUrl("http: httpConfiguration.setHttpMethod("PATCH"); GoogleAppEngineHttpConnection googleAppEngineHttpConnection = spy(GoogleAppEngineHttpConnection.class); doCallRealMethod().when(googleAppEngineHttpConnection).createAndconfigureHttpConnection((HttpConfiguration) any()); googleAppEngineHttpConnection.createAndconfigureHttpConnection(httpConfiguration); Assert.assertEquals("POST", googleAppEngineHttpConnection.connection.getRequestMethod()); }
### Question: 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[0], Constants.ENCODING_FORMAT), (field.length > 1) ? URLDecoder.decode(field[1].trim(), Constants.ENCODING_FORMAT) : ""); } return response; } private NVPUtil(); static Map<String, String> decode(String nvpString); static String encodeUrl(String value); }### Answer: @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"; Map<String, String> map = NVPUtil.decode(nvpString); Assert.assertEquals(6, map.size()); assert (map.containsValue("Success")); assert (map.containsKey("invoiceID")); assert (map.containsKey("invoiceNumber")); Assert.assertEquals("INV2-AAWE-TAQW-7UXT-ZHBY", map.get("invoiceID")); Assert.assertEquals("INV-00404", map.get("invoiceNumber")); }
### Question: 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); }### Answer: @Test public void encodeTest() throws UnsupportedEncodingException { String value = "[email protected]"; Assert.assertEquals("jbui-us-personal1%40paypal.com", NVPUtil.encodeUrl(value)); }
### Question: 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 machine, String seedString); }### Answer: @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 = new LotteryMachine(5); LotteryMachine spyMachine = spy(lotteryMachine); when(spyMachine.setSeed(seedString)).thenReturn(spyMachine.setSeed(0)); Lottery lottery = new Lottery(emailsReader, spyMachine, seedString); lottery.run(); Assert.assertEquals(0, lotteryMachine.getSeed()); } @Test public void mockedLottery() { EmailsReader emailsReader = mock(EmailsReader.class); LotteryMachine lotteryMachine = mock(LotteryMachine.class); String seedString = "May the Force be with you"; when(emailsReader.get()).thenReturn(Arrays.asList("0", "1", "2", "3", "4")); when(lotteryMachine.setSeed(seedString)).thenReturn(lotteryMachine); Lottery lottery = new Lottery(emailsReader, lotteryMachine, seedString); lottery.run(); verify(emailsReader, times(1)).get(); verify(lotteryMachine, times(1)).setSeed(seedString); verify(lotteryMachine, never()).dispose(); }
### Question: 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); winners.add(emails.get(index)); } return new ArrayList<>(winners); } LotteryMachine(int winnersCount); long getSeed(); }### Answer: @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.assertTrue(result.contains("1")); Assert.assertTrue(result.contains("2")); Assert.assertTrue(result.contains("3")); Assert.assertTrue(result.contains("4")); }
### Question: 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 | IllegalAccessException e) { e.printStackTrace(); } finally { if (field != null && !isAccessible) { field.setAccessible(false); } } return null; } private ReflectionHelper(); }### Answer: @Test public void getFieldValue() { Assert.assertEquals("A", ReflectionHelper.getFieldValue(new TestClass(1, "A"), "s")); Assert.assertEquals(1, ReflectionHelper.getFieldValue(new TestClass(1, "B"), "a")); }
### Question: 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 | IllegalAccessException e) { e.printStackTrace(); } finally { if (field != null && !isAccessible) { field.setAccessible(false); } } } private ReflectionHelper(); }### Answer: @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()); }
### Question: 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); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } finally { if (method != null && !isAccessible) { method.setAccessible(false); } } return null; } private ReflectionHelper(); }### Answer: @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()); }
### Question: 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 new ArrayList<>(winners); } LotteryMachine(List<String> emails, int winnersCount); }### Answer: @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.contains("0")); Assert.assertTrue(result.contains("1")); Assert.assertTrue(result.contains("2")); Assert.assertTrue(result.contains("3")); Assert.assertTrue(result.contains("4")); }
### Question: 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(); }### Answer: @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()); }
### Question: 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 - expectedCash); } if(nextCellResult) { count = count - expectedCount; return true; } return false; } Cell(int nominal, int count); boolean withdraw(int requested); int getNominal(); int getCount(); void setNext(Cell next); int getBalance(); @Override int compareTo(Cell o); @Override Iterator<Cell> iterator(); }### Answer: @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)); }
### Question: 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, container); container.addView(view); return view; } RecyclingPagerAdapter(); RecyclingPagerAdapter(RecycleBin recycleBin); @Override void notifyDataSetChanged(); @Override final Object instantiateItem(ViewGroup container, int position); @Override final void destroyItem(ViewGroup container, int position, Object object); @Override final boolean isViewFromObject(View view, Object object); int getViewTypeCount(); @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. int getItemViewType(int position); abstract View getView(int position, View convertView, ViewGroup container); }### Answer: @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; } @Override public View getView(int position, View convertView, ViewGroup container) { return child; } @Override public int getCount() { throw new AssertionError("getCount should not have been called."); } }; verify(recycleBin).setViewTypeCount(1); adapter.instantiateItem(container, 0); verifyNoMoreInteractions(recycleBin); }
### Question: 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, viewType); } } RecyclingPagerAdapter(); RecyclingPagerAdapter(RecycleBin recycleBin); @Override void notifyDataSetChanged(); @Override final Object instantiateItem(ViewGroup container, int position); @Override final void destroyItem(ViewGroup container, int position, Object object); @Override final boolean isViewFromObject(View view, Object object); int getViewTypeCount(); @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. int getItemViewType(int position); abstract View getView(int position, View convertView, ViewGroup container); }### Answer: @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_TYPE; } @Override public View getView(int position, View convertView, ViewGroup container) { throw new AssertionError("getView should not have been called."); } @Override public int getCount() { throw new AssertionError("getCount should not have been called."); } }; verify(recycleBin).setViewTypeCount(1); adapter.destroyItem(container, 0, child); verifyNoMoreInteractions(recycleBin); }
### Question: 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(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testOrgId() { assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000399L, seqEntries.get(0).getOrgId()); }
### Question: 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(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testOrg() { assertEquals("tests whether organism names are extracted accurately", "Arabidopsis thaliana", seqEntries.get(0).getOrg()); }
### Question: 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> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testSeq() { assertEquals("tests whether sequences are extracted accurately", sequences.get(0), seqEntries.get(0).getSeq()); }
### Question: 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(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testEc() { assertEquals("tests whether ec_numbers are extracted accurately", "1.1.1.1", seqEntries.get(0).getEc()); }
### Question: 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> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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 accurately", "ureA", dnaSeqEntries.get(0).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ureB", dnaSeqEntries.get(1).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ureC", dnaSeqEntries.get(2).getGeneName()); }
### Question: 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(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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 extracted accurately", geneSynonyms, proteinSeqEntries.get(0).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(0).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(1).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(2).getGeneSynonyms()); }
### Question: 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<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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("Sulfotransferase 1A1"), proteinSeqEntries.get(1).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("gamma subunit of urase"), dnaSeqEntries.get(0).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("beta subunit of urease"), dnaSeqEntries.get(1).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("alpha subunit of urease"), dnaSeqEntries.get(2).getProductName()); }
### Question: 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> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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 ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(0).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(1).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(2).getOrgId()); }
### Question: 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> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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 are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(0).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(1).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(2).getOrg()); }
### Question: 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> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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 accurately", sequences.get(2), dnaSeqEntries.get(0).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(3), dnaSeqEntries.get(1).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(4), dnaSeqEntries.get(2).getSeq()); }
### Question: 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(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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", "3.5.1.5", dnaSeqEntries.get(0).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "3.5.1.5", dnaSeqEntries.get(1).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "3.5.1.5", dnaSeqEntries.get(2).getEc()); }
### Question: 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<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }### Answer: @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_number", "2008518610"); obj.put("patent_year", "2008"); patentRefs.add(obj); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), proteinSeqEntries.get(1).getPatents().toString()); JSONObject obj2 = new JSONObject(); obj2.put("src", "Patent"); obj2.put("country_code", "EP"); obj2.put("patent_number", "2904117"); obj2.put("patent_year", "2015"); patentRefs.add(obj2); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(0).getPatents().toString()); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(1).getPatents().toString()); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(2).getPatents().toString()); }
### Question: 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(String inchi); boolean isChemaxonValidInchi(String inchi); void processInchiLine(String line); void processLine(String line); void writeToTSV(String outputPath); void writeToJSON(String outputPath); static void main(final String[] args); static final CSVFormat TSV_FORMAT; static final String OPTION_WIKIPEDIA_DUMP_FULL_PATH; static final String OPTION_OUTPUT_PATH; static final String OPTION_TSV_OUTPUT; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }### Answer: @Test public void testFormatInchiString() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.formatInchiString(testcase.getMatchedInchi()), testcase.getExpectedInchi() ); } }
### Question: 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", getSubstructureInchi()); return false; } } private OneSubstrateSubstructureSar(); OneSubstrateSubstructureSar(Molecule substructure, MolSearchOptions searchOptions); OneSubstrateSubstructureSar(Molecule substructure); @Override boolean test(List<Molecule> substrates); }### Answer: @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() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(noBenzene); assertFalse("Substrate does not contain substructure.", sar.test(substrates)); } @Test public void twoSubstratesRejects() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(noBenzene, containsBenzene); assertFalse("Can't operate on two substrates", sar.test(substrates)); } @Test public void NoSubstratesRejects() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = new ArrayList<>(); assertFalse("Can't operate on no substrates", sar.test(substrates)); }
### Question: 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); boolean isChemaxonValidInchi(String inchi); void processInchiLine(String line); void processLine(String line); void writeToTSV(String outputPath); void writeToJSON(String outputPath); static void main(final String[] args); static final CSVFormat TSV_FORMAT; static final String OPTION_WIKIPEDIA_DUMP_FULL_PATH; static final String OPTION_OUTPUT_PATH; static final String OPTION_TSV_OUTPUT; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }### Answer: @Test public void testExtractInchiFromLine() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.extractInchiFromLine(testcase.getExtractedLine()), testcase.getMatchedInchi() ); } }
### Question: UniprotSeqEntry extends SequenceEntry { public String getGeneName() { return this.geneName; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testGeneName() { assertEquals("tests whether gene name is extracted accurately", "ADH1", seqEntries.get(0).getGeneName()); }
### Question: GenbankInterpreter { public ArrayList<String> getSequenceStrings() { checkInit(); ArrayList<String> sequences = new ArrayList<>(); for (AbstractSequence sequence : this.sequences) { sequences.add(sequence.getSequenceAsString()); } return sequences; } GenbankInterpreter(File GenbankFile, String type); void init(); void printSequences(); ArrayList<String> getSequenceStrings(); void printFeaturesAndQualifiers(); ArrayList<ArrayList<String>> getFeatures(); Map<String, List<Qualifier>> getQualifiers(int sequence_index, String feature_type, String feature_source); void addQualifier(AbstractFeature<AbstractSequence<Compound>, Compound> feature, String qual_name, String qual_value); AbstractFeature<AbstractSequence<Compound>, Compound> constructFeature(String type, String source); void printDescription(); void printAccessionID(); void printHeader(); List<AbstractSequence> getSequences(); void addFeature(int bioStart, int bioEnd, AbstractFeature<AbstractSequence<Compound>, Compound> feature, int sequence_index); static void main(String[] args); static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }### Answer: @Test public void testReadSequence() { assertEquals("test whether parser extracts sequence accurately", protein_seq, giProtein.getSequenceStrings().get(0)); assertEquals("test whether parser extracts sequence accurately", dna_seq, giDna.getSequenceStrings().get(0)); }
### Question: LcmsChemicalFormula implements ChemicalFormula { @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Map.Entry<Element, Integer> entry : getSortedElementCounts().entrySet()) { builder.append(entry.getKey().getSymbol()); Integer count = entry.getValue(); if (count > 1) { builder.append(count.toString()); } } return builder.toString(); } LcmsChemicalFormula(String chemicalFormula); LcmsChemicalFormula(Map<Element, Integer> elementCounts); LcmsChemicalFormula(Map<Element, Integer> elementCounts, String name); Map<Element, Integer> getElementCounts(); Integer getElementCount(Element element); Double getMonoIsotopicMass(); Optional<String> getName(); @Override boolean equals(Object chemicalFormula); @Override String toString(); void fromString(String formulaString); }### Answer: @Test public void testChemicalFormulaToString() { assertEquals(acetaminophenFormulaString, acetaminophenFormula.toString()); assertEquals(sulfuricAcidFormulaString, sulfuricAcidFormula.toString()); }
### Question: LcmsChemicalFormula implements ChemicalFormula { public Double getMonoIsotopicMass() { return elementCounts .entrySet() .stream() .mapToDouble(entry -> entry.getKey().getMass() * entry.getValue()) .sum(); } LcmsChemicalFormula(String chemicalFormula); LcmsChemicalFormula(Map<Element, Integer> elementCounts); LcmsChemicalFormula(Map<Element, Integer> elementCounts, String name); Map<Element, Integer> getElementCounts(); Integer getElementCount(Element element); Double getMonoIsotopicMass(); Optional<String> getName(); @Override boolean equals(Object chemicalFormula); @Override String toString(); void fromString(String formulaString); }### Answer: @Test public void testChemicalFormulaMonoIsotopicMass() { assertEquals(151.063, acetaminophenFormula.getMonoIsotopicMass(), MASS_TOLERANCE); assertEquals(97.967, sulfuricAcidFormula.getMonoIsotopicMass(), MASS_TOLERANCE); }
### Question: UniprotSeqEntry extends SequenceEntry { public List<String> getGeneSynonyms() { return this.geneSynonyms; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testGeneSynonyms() { assertEquals("tests whether gene synonyms are extracted accurately", Collections.singletonList("ADH"), seqEntries.get(0).getGeneSynonyms()); }
### Question: UniprotSeqEntry extends SequenceEntry { public List<String> getProductName() { return this.productNames; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testProductName() { assertEquals("tests whether product names are extracted accurately", Arrays.asList("Alcohol dehydrogenase class-P", "Alc Dehyd"), seqEntries.get(0).getProductName()); }
### Question: UniprotSeqEntry extends SequenceEntry { public String getCatalyticActivity() {return this.catalyticActivity; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }### Answer: @Test public void testCatalyticActivity() { assertEquals("tests whether catalytic activity is extracted accurately", "An alcohol + NAD(+) = an aldehyde or ketone + NADH.", seqEntries.get(0).getCatalyticActivity()); }
### Question: AverageAggregator extends AbsDiffAggregator { @Override public DoubleWritable finalizeAggregation() { return new DoubleWritable(getValue().get() / getTimesAggregated().get()); } @Override DoubleWritable finalizeAggregation(); }### Answer: @Test public void testAggregator() { AverageAggregator diff = new AverageAggregator(); diff.aggregate(new DoubleWritable(5), new DoubleWritable(2)); diff.aggregateInternal(); diff.aggregate(new DoubleWritable(5), new DoubleWritable(2)); diff.aggregateInternal(); diff.aggregate(null, new DoubleWritable(5)); diff.aggregateInternal(); assertEquals(3, diff.getTimesAggregated().get()); DoubleWritable x = diff.finalizeAggregation(); assertEquals(2, (int) x.get()); }
### Question: DynamicGraph { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { if (args.length != 2) { printUsage(); } HamaConfiguration conf = new HamaConfiguration(new Configuration()); GraphJob graphJob = createJob(args, conf); long startTime = System.currentTimeMillis(); if (graphJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }### Answer: @Test public void test() throws IOException, InterruptedException, ClassNotFoundException { try { DynamicGraph.main(new String[] { "src/test/resources/dg.txt", OUTPUT }); verifyResult(); } finally { deleteTempDirs(); } }
### Question: KCore { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { if (args.length != 2) { printUsage(); } HamaConfiguration conf = new HamaConfiguration(new Configuration()); GraphJob graphJob = createJob(args, conf); long startTime = System.currentTimeMillis(); if (graphJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }### Answer: @Test public void testKcore() throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException { try { setOutputResult(); KCore.main(new String[] { INPUT, OUTPUT }); verifyResult(); } finally { fs.exists(new Path(OUTPUT)); } }
### Question: SpMV { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); parseArgs(conf, args); startTask(conf); } static String getResultPath(); static void setResultPath(String resultPath); static String convertSpMVOutputToDenseVector( String SpMVoutputPathString, HamaConfiguration conf); static void readFromFile(String pathString, Writable result, HamaConfiguration conf); static void writeToFile(String pathString, Writable result, HamaConfiguration conf); static void main(String[] args); }### Answer: @Test public void runFromDriver() { try { String matrixPath = ""; String vectorPath = ""; String outputPath = ""; if (matrixPath.isEmpty() || vectorPath.isEmpty() || outputPath.isEmpty()) { LOG.info("Please setup input path for vector and matrix and output path for result."); return; } ExampleDriver.main(new String[] { "spmv", matrixPath, vectorPath, outputPath, "4" }); } catch (Exception e) { e.printStackTrace(); fail(e.getLocalizedMessage()); } }
### Question: PiEstimator { public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); BSPJob bsp = new BSPJob(conf, PiEstimator.class); bsp.setJobName("Pi Estimation Example"); bsp.setBspClass(MyEstimator.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputKeyClass(Text.class); bsp.setOutputValueClass(DoubleWritable.class); bsp.setOutputFormat(TextOutputFormat.class); FileOutputFormat.setOutputPath(bsp, TMP_OUTPUT); BSPJobClient jobClient = new BSPJobClient(conf); ClusterStatus cluster = jobClient.getClusterStatus(true); if (args.length > 0) { bsp.setNumBspTask(Integer.parseInt(args[0])); } else { bsp.setNumBspTask(cluster.getMaxTasks()); } long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { printOutput(conf); System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }### Answer: @Test public void testCorrectPiExecution() { try { PiEstimator.main(new String[] { "10" }); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testPiExecutionWithEmptyArgs() { try { PiEstimator.main(new String[10]); fail("PiEstimator should fail if the argument list has size 0"); } catch (Exception e) { } }
### Question: PageRank { public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException, ParseException { Options opts = new Options(); opts.addOption("i", "input_path", true, "The Location of output path."); opts.addOption("o", "output_path", true, "The Location of input path."); opts.addOption("h", "help", false, "Print usage"); opts.addOption("t", "task_num", true, "The number of tasks."); opts.addOption("f", "file_type", true, "The file type of input data. Input" + "file format which is \"text\" tab delimiter separated or \"json\"." + "Default value - Text"); if (args.length < 2) { new HelpFormatter().printHelp("pagerank -i INPUT_PATH -o OUTPUT_PATH " + "[-t NUM_TASKS] [-f FILE_TYPE]", opts); System.exit(-1); } HamaConfiguration conf = new HamaConfiguration(); GraphJob pageJob = createJob(args, conf, opts); long startTime = System.currentTimeMillis(); if (pageJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static GraphJob createJob(String[] args, HamaConfiguration conf, Options opts); static void main(String[] args); }### Answer: @Test public void testPageRank() throws IOException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException { generateTestData(); try { PageRank.main(new String[] { "-input_path", INPUT, "-output_path", OUTPUT, "-task_num", "5", "-f", "json" }); verifyResult(); } catch (ParseException e) { e.printStackTrace(); } finally { deleteTempDirs(); } }
### Question: RandBench { public static void main(String[] args) throws Exception { if (args.length < 3) { System.out.println("Usage: <sizeOfMsg> <nCommunications> <nSupersteps>"); System.exit(-1); } HamaConfiguration conf = new HamaConfiguration(); conf.setInt(SIZEOFMSG, Integer.parseInt(args[0])); conf.setInt(N_COMMUNICATIONS, Integer.parseInt(args[1])); conf.setInt(N_SUPERSTEPS, Integer.parseInt(args[2])); BSPJob bsp = new BSPJob(conf, RandBench.class); bsp.setJobName("Random Communication Benchmark"); bsp.setBspClass(RandBSP.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputFormat(NullOutputFormat.class); BSPJobClient jobClient = new BSPJobClient(conf); ClusterStatus cluster = jobClient.getClusterStatus(false); bsp.setNumBspTask(cluster.getMaxTasks()); long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }### Answer: @Test public void testCorrectRandBenchExecution() { try { RandBench.main(new String[] { "10", "3", "2" }); } catch (Exception e) { fail(e.getLocalizedMessage()); } } @Test public void testRandBenchExecutionWithEmptyArgs() { try { RandBench.main(new String[10]); fail("RandBench should fail if the argument list has size < 3"); } catch (Exception e) { } }
### Question: CombineExample { public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException { HamaConfiguration conf = new HamaConfiguration(); BSPJob bsp = new BSPJob(conf, CombineExample.class); bsp.setJobName("Combine Example"); bsp.setBspClass(MyBSP.class); bsp.setCombinerClass(SumCombiner.class); bsp.setInputFormat(NullInputFormat.class); bsp.setOutputKeyClass(Text.class); bsp.setOutputValueClass(IntWritable.class); bsp.setOutputFormat(TextOutputFormat.class); FileOutputFormat.setOutputPath(bsp, TMP_OUTPUT); bsp.setNumBspTask(2); long startTime = System.currentTimeMillis(); if (bsp.waitForCompletion(true)) { printOutput(conf); System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } static void main(String[] args); }### Answer: @Test public void testCorrectCombineExecution() { try { CombineExample.main(new String[] {}); } catch (Exception e) { fail(e.getLocalizedMessage()); } }
### Question: SyncServiceFactory { public static PeerSyncClient getPeerSyncClient(Configuration conf) throws ClassNotFoundException { return (PeerSyncClient) ReflectionUtils.newInstance(conf .getClassByName(conf.get(SYNC_CLIENT_CLASS, ZooKeeperSyncClientImpl.class.getName())), conf); } static PeerSyncClient getPeerSyncClient(Configuration conf); static SyncClient getMasterSyncClient(Configuration conf); static SyncServer getSyncServer(Configuration conf); static SyncServerRunner getSyncServerRunner(Configuration conf); static final String SYNC_SERVER_CLASS; static final String SYNC_CLIENT_CLASS; static final String SYNC_MASTER_CLASS; }### Answer: @Test public void testClientInstantiation() throws Exception { Configuration conf = new Configuration(); PeerSyncClient syncClient = SyncServiceFactory.getPeerSyncClient(conf); assertTrue(syncClient instanceof ZooKeeperSyncClientImpl); }
### Question: SyncServiceFactory { public static SyncServer getSyncServer(Configuration conf) throws ClassNotFoundException { return (SyncServer) ReflectionUtils.newInstance(conf.getClassByName(conf .get(SYNC_SERVER_CLASS, org.apache.hama.bsp.sync.ZooKeeperSyncServerImpl.class .getCanonicalName())), conf); } static PeerSyncClient getPeerSyncClient(Configuration conf); static SyncClient getMasterSyncClient(Configuration conf); static SyncServer getSyncServer(Configuration conf); static SyncServerRunner getSyncServerRunner(Configuration conf); static final String SYNC_SERVER_CLASS; static final String SYNC_CLIENT_CLASS; static final String SYNC_MASTER_CLASS; }### Answer: @Test public void testServerInstantiation() throws Exception { Configuration conf = new Configuration(); SyncServer syncServer = SyncServiceFactory.getSyncServer(conf); assertTrue(syncServer instanceof ZooKeeperSyncServerImpl); }
### Question: VectorDoubleFileInputFormat extends FileInputFormat<VectorWritable, DoubleWritable> { @Override public RecordReader<VectorWritable, DoubleWritable> getRecordReader( InputSplit split, BSPJob job) throws IOException { return new VectorDoubleRecorderReader(job.getConfiguration(), (FileSplit) split); } @Override RecordReader<VectorWritable, DoubleWritable> getRecordReader( InputSplit split, BSPJob job); }### Answer: @Test public void testFileRead() throws Exception { VectorDoubleFileInputFormat inputFormat = new VectorDoubleFileInputFormat(); Path file = new Path("src/test/resources/vd_file_sample.txt"); InputSplit split = new FileSplit(file, 0, 1000, new String[]{"localhost"}); BSPJob job = new BSPJob(); RecordReader<VectorWritable, DoubleWritable> recordReader = inputFormat.getRecordReader(split, job); assertNotNull(recordReader); VectorWritable key = recordReader.createKey(); assertNotNull(key); DoubleWritable value = recordReader.createValue(); assertNotNull(value); assertTrue(recordReader.next(key, value)); assertEquals(new DenseDoubleVector(new double[]{2d, 3d, 4d}), key.getVector()); assertEquals(new DoubleWritable(1d), value); }
### Question: LinearRegressionModel implements RegressionModel { @Override public BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta) { return costFunction.calculateCostForItem(x, y, m, theta, this); } LinearRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }### Answer: @Test public void testCorrectCostCalculation() throws Exception { LinearRegressionModel linearRegressionModel = new LinearRegressionModel(); DoubleVector x = new DenseDoubleVector(new double[]{2, 3, 4}); double y = 1; DoubleVector theta = new DenseDoubleVector(new double[]{1, 1, 1}); BigDecimal cost = linearRegressionModel.calculateCostForItem(x, y, 2, theta); assertEquals("wrong cost calculation for linear regression", BigDecimal.valueOf(16d), cost); }
### Question: LinearRegressionModel implements RegressionModel { @Override public BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x) { return BigDecimal.valueOf(theta.dotUnsafe(x)); } LinearRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }### Answer: @Test public void testCorrectHypothesisCalculation() throws Exception { LinearRegressionModel linearRegressionModel = new LinearRegressionModel(); BigDecimal hypothesisValue = linearRegressionModel.applyHypothesis(new DenseDoubleVector(new double[]{1, 1, 1}), new DenseDoubleVector(new double[]{2, 3, 4})); assertEquals("wrong hypothesis value for linear regression", BigDecimal.valueOf(9d), hypothesisValue); }
### Question: LogisticRegressionModel implements RegressionModel { @Override public BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta) { return costFunction.calculateCostForItem(x, y, m, theta, this); } LogisticRegressionModel(); @Override BigDecimal applyHypothesis(DoubleVector theta, DoubleVector x); @Override BigDecimal calculateCostForItem(DoubleVector x, double y, int m, DoubleVector theta); }### Answer: @Test public void testCorrectCostCalculation() throws Exception { LogisticRegressionModel logisticRegressionModel = new LogisticRegressionModel(); DoubleVector x = new DenseDoubleVector(new double[]{2, 3, 4}); double y = 1; DoubleVector theta = new DenseDoubleVector(new double[]{1, 1, 1}); BigDecimal cost = logisticRegressionModel.calculateCostForItem(x, y, 2, theta); assertEquals("wrong cost calculation for logistic regression", 6.170109486162941E-5d, cost.doubleValue(), 0.000001); }