id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
62244807_3
class Version implements Comparable<Version> { public long value() { return version; } private Version(long version, String display); public static Version fromJson(JsonObject obj, String field, Version dftValue); public static Version fromJson(JsonObject obj, String field); public s...
assertEquals(-1, Version.UNSET.value()); assertEquals(0, Version.INIT.value()); assertEquals(1, Version.FIRST.value()); } }
62246133_145
class TokenRequest implements Request<Credentials, AuthenticationException> { @NonNull public TokenRequest addHeader(@NonNull String name, @NonNull String value) { request.addHeader(name, value); return this; } public TokenRequest(@NonNull ParameterizableRequest<Credentials, Authentic...
tokenRequest.addHeader("auth", "val123"); verify(mockRequest).addHeader(eq("auth"), eq("val123")); } }
62262439_6
class Move { public int getTypeId() { return typeId; } public Move(int moveId, String name, int typeId, int power, int pp, int accuracy, String className); public int getMoveId(); public String getName(); public int getPower(); public int getPp(); public int getAccuracy(); ...
assertEquals(0, mTestMoveOne.getTypeId()); assertEquals(1, mTestMoveTwo.getTypeId()); assertEquals(1, mTestMoveThree.getTypeId()); } }
62282525_18
class PatternValidator implements ConfigDef.Validator { @Override public void ensureValid(String setting, Object value) { if (value instanceof String) { String s = (String) value; validatePattern(setting, s); } else if (value instanceof List) { List<String> list = (List<String>) value; ...
ConfigException configException = assertThrows(ConfigException.class, ()->{ PatternValidator validator = new PatternValidator(); validator.ensureValid("foo", 1234); }); assertTrue(configException.getMessage().contains("foo")); } }
62303580_13
class ConfigStrategyProvider { public static ConfigStrategy get() { return new YamlConfig(); } private ConfigStrategyProvider(); } class ConfigStrategyProviderTest { @Test public void getReturnsYamlConfigByDefault() {
assumeTrue(StringUtils.isBlank(System.getProperty(ConfigKeys.CONFIG_STRATEGY))); ConfigStrategy configStrategy = ConfigStrategyProvider.get(); assertThat(configStrategy).isInstanceOf(YamlConfig.class); } }
62313135_1
class GetComicsUseCaseImpl implements GetComicsUseCase { @Override public void execute(int characterId, Callback callback) { this.characterId = characterId; this.callback = callback; this.threadExecutor.execute(this); } @Inject public GetComicsUseCaseImpl(ThreadExecutor thread...
interactor.execute(CHARACTER_ID, callback); verify(comicsRepository).getComics(anyInt(), any( ComicListCallback.class)); } }
62384018_0
class S3Util { public static String getContentType(final File file) { String contentType = URLConnection.guessContentTypeFromName(file.getName()); if (StringUtil.isNotEmpty(contentType)) { return contentType; } if (PROBE_CONTENT_TYPE_METHOD != null && FILE_TO_PATH_METHOD != null) { try { ...
Assert.assertEquals(S3Util.getContentType(new File("S3UtilsTest", fileName)), expectedType); } }
62422842_38
class During { public Future execute (CompletionCallback <Object> callback) { if (callback == null) throw new IllegalArgumentException ("Callback cannot be null"); TaskManagerImpl taskManager = new TaskManagerImpl ( this.executor_, this.cond_, this.task_, ...
final During during = new During ( Executors.newCachedThreadPool (), new ConditionalTask () { @Override public void evaluate (ConditionalCallback callback) { callback.done (remaining_ > 0); } }, new Task () { @Over...
62535317_13
class SalesOrderItem { public BigDecimal getGrossAmount() { return this.grossAmount; } public SalesOrderItem(); public SalesOrderItem(String salesOrderId, int itemNumber); public SalesOrderItemId getId(); public void setId(SalesOrderItemId id); public String getSalesOrderId(); public void setSalesOrderId...
EntityManager em = emf.createEntityManager(); String soId = "11111"; TestFactory tf = new TestFactory(); SalesOrderItem soItemAct = null; try { // Add Sales Order Item assertTrue("Sales Order Item", tf.createSalesOrderItem(em, soId)); // Search for Sales Order Item TypedQuery<SalesOrderItem> query...
62553999_134
class TextUtils { public static boolean equals(@Nullable CharSequence a, @Nullable CharSequence b) { if (a == b) { return true; } int length; if (a != null && b != null && (length = a.length()) == b.length()) { if (a instanceof String && b instanceof String)...
StringBuilder first = new StringBuilder("9pda"); StringBuilder second = new StringBuilder("0ca"); boolean equals = TextUtils.equals(first, second); assertFalse(equals); } }
62569629_43
class Normalize { public static String cleanupDeviceBrandName(String deviceBrand, String deviceName) { deviceName = replaceString(deviceName, "'", " "); deviceName = replaceString(deviceName, "_", " "); deviceName = DEVICE_CLEANUP_PATTERN_1.matcher(deviceName).replaceAll("-"); devi...
assertEquals("Asus Something T123", Normalize.cleanupDeviceBrandName("AsUs", "something t123")); assertEquals("Sony X1", Normalize.cleanupDeviceBrandName("Sony", "sony x1")); assertEquals("Sony X1", Normalize.cleanupDeviceBrandName("Sony", "sony-x1")); ...
62607150_1
class RegexUtil { public static boolean isThoughtWorkEmail(String email) { return THOUGHT_WORKS_EMAIL_PATTERN.matcher(email).matches(); } } class RegexUtilTest { @Test public void testNotMatcherNonThoughtWorksEmail() throws Exception {
String[] emails = new String[] {"test@google.com", "test @gmail.com", "test_wrong_email"}; for (String email : emails) { boolean matcher = isThoughtWorkEmail(email); assertThat(matcher).isFalse(); } } }
62640065_41
class ZeroCodeAssertionsProcessorImpl implements ZeroCodeAssertionsProcessor { @Override public String resolveStringJson(String requestJsonOrAnyString, String scenarioStateJson) { String resolvedFromTemplate = resolveKnownTokensAndProperties(requestJsonOrAnyString); String resolvedJson = resolv...
ScenarioSpec scenarioSpec = smartUtils.scenarioFileToJava( "unit_test_files/test_engine/01_request_with_place_holders.json", ScenarioSpec.class); final String requestJsonAsString = scenarioSpec.getSteps().get(0).getRequest().toString(); final String resol...
62640701_32
class DependencyManagement { public Long createDependencyWithinArchitecture(final Long architectureId, final Long serviceId, final Long dependsOnServiceId) { final Architecture architecture = architectureRepository.findOne(architectureId); final Service service = serviceRepository.findOne(serviceId...
stub(dependencyRepository.save(any(Dependency.class))).toReturn(new Dependency()); dependencyManagement.createDependencyWithinArchitecture(1L, 2L, 3L); verify(dependencyRepository).save(any(Dependency.class)); } }
62711375_6
class GithubImpl implements Github { @Override public Promise<Collection<Repository>, Throwable, Void> repositories(final String organization) { return deferredManager.when(() -> { Response<List<Repository>> response = api.repositories(organization).execute(); if (response.isSuc...
// given: Collection<Repository> repositories = createSampleRepositories(); stubFor(get(urlEqualTo("/orgs/" + ORGANIZATION + "/repos")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(reposito...
62793144_17
class RealmFinalizerController extends AbstractFinalizerController { @Override protected Result processFinalizer(AddressSpace addressSpace) { log.info("Processing realm finalizer for {}/{}", addressSpace.getMetadata().getNamespace(), addressSpace.getMetadata().getName()); final String realmNam...
when(authenticationServiceRegistry.findAuthenticationService(any())).thenReturn(Optional.of(createAuthService(AuthenticationServiceType.standard, "myrealm"))); AbstractFinalizerController.Result result = controller.processFinalizer(createTestSpace("standard", "myrealm")); assertNotNull(result); ...
62823867_3
class ResourceMatcher { public void match(Handler handler) { matcher.reset(); while (matcher.find()) { handler.handle(matcher.group(1), matcher.group(2)); } } public ResourceMatcher(String input, MatchType matchType); private ResourceMatcher.Handler mockHandler; } class ResourceMatcher...
String codeLine = "editTextView.setText(toString(R.string.title));" + "imageView.getLayoutParam().width = getResource().getDimen(R.dimen.width);"; ResourceMatcher matcher = new ResourceMatcher(codeLine, RES_VALUE_IN_JAVA); matcher.match(mockHandler); verify(mockHandler)...
62839192_13
class GroovyTreeParser implements TreeParser { @Override public Set<SymbolInformation> getFilteredSymbols(String query) { checkNotNull(query, "query must not be null"); Pattern pattern = getQueryPattern(query); return indexer.getFileSymbols().values().stream().flatMap(Collection::stream...
File coordinatesFiles = addFileToFolder(workspaceRoot, "Coordinates.groovy", "class Coordinates implements ICoordinates {\n" + " double latitude\n" + " double longitude\n" + " double longitude2\n" ...
62872951_20
class LogMapper { public static ExchangeLogType toModel(ExchangeLog entity) { ExchangeLogType model = new ExchangeLogType(); LogType logType = entity.getType(); if (logType.equals(LogType.RECEIVE_MOVEMENT)) { ReceiveMovementType type = new ReceiveMovementType(); typ...
Date dateReceived = new Date(); String guid = "Paradise"; String senderReceiver = "Chris Martin"; boolean incoming = true; ExchangeLogStatusTypeType status = ExchangeLogStatusTypeType.PROBABLY_TRANSMITTED; String destination = "destination"; ExchangeLog entity = ...
62914175_43
class CreateVCFFileTask extends GenericTask { @Override @SneakyThrows public void execute(TaskContext taskContext) { val testedDonorCount = resolveTotalSsmTestedDonorCount(taskContext); val releaseName = taskContext.getJobContext().getReleaseName(); val fastaFile = resolveFastaFile(); val header...
given(new File(INPUT_TEST_FIXTURES_DIR)); task.execute(createTaskContext(JobType.SUMMARIZE)); verifyOutput(); } }
62959750_0
class FieldUtils { @NonNull public static <T> Observable<T> toObservable(@NonNull final ObservableField<T> field) { return Observable.create(new ObservableOnSubscribe<T>() { @Override public void subscribe(final ObservableEmitter<T> e) throws Exception { T initi...
testObserver = toObservable(new ObservableField<>((Integer) null)).test(); testObserver.assertNoValues() .assertNoErrors(); } }
62970529_3
class ZookeeperCRUD { @VisibleForTesting String readZNodeData(String path) { //TODO: throw exceptions instead of returning null try { Stat stat = curatorClient.checkExists().forPath(path); if(stat == null) return null; // path does not exist String zNodeData ...
when(curatorFramework.checkExists().forPath(anyString())).thenReturn(null); String zNodeData = zookeeperClientWrapper.readZNodeData("/path1/path2"); verify(curatorFramework, never()).getData(); assertNull(zNodeData); } }
63061526_4
class SettingsTmc implements TmcSettings, Serializable { @Override public SystemDefaultRoutePlanner proxy() { // implement? return null; } public SettingsTmc(String serverAddress, String username, String password); public SettingsTmc(); public boolean isCheckForExercises(); ...
assertEquals(null, settingstmc.proxy()); } }
63085918_54
class KeywordsProvider implements IKeywordsProvider { public boolean isKeyword(final String name) { return this.keywords.contains(name); } public KeywordsProvider(); public KeywordsProvider(final String... files); private void init(final String file); } class KeywordsProviderTest { @Test public void te...
KeywordsProvider provider = new KeywordsProvider("nonExisting"); Assert.assertFalse(provider.isKeyword("SELECT")); } }
63107687_36
class Set implements LongFunction<java.util.Set<Object>> { @Example({"Set(HashRange(3,7),Add(15L))", "create a set between 3 and 7 elements of Long values"}) public Set(LongToIntFunction sizeFunc, LongFunction<Object> valueFunc) { this.sizeFunc = sizeFunc; this.valueFunc = valueF...
Set set = new Set(s -> 3, e -> e); java.util.Set<Object> s1 = set.apply(15L); assertThat(s1).containsOnly(15L,16L,17L); } }
63135578_3
class CSVSpecifiedWKTStrategy extends CSVStrategy { @Override protected SimpleFeatureType buildFeatureType() { ISOSimpleFeatureTypeBuilder featureBuilder = createBuilder(csvFileState); // For WKT strategy, we need to make sure the wktField is recognized as a Geometry AttributeDescriptor de...
String input = CSVTestStrategySupport.buildInputString("quux,morx\n"); CSVFileState fileState = new CSVFileState(input, "foo"); CSVStrategy strategy = new CSVSpecifiedWKTStrategy(fileState, "quux"); SimpleFeatureType featureType = strategy.getFeatureType(); assertEquals("Invalid ...
63251000_28
class ProcessDefinitionFinder { public Optional<ProcessDefinition> find(ProcessDefinitionSpec spec) { ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery(); add(processDefinitionQuery, ProcessDefinitionQuery::processDefinitionKey, spec.getProcessDefinitionKey()); ...
ZonedDateTime beforeDeployment = ZonedDateTime.now(); runWithAnotherDeployment(() -> { DeploymentSpec deploymentSpec = DeploymentSpec.builder() .earliestDeployment(beforeDeployment) .latestDeployment(ZonedDateTime.now()) .build(); Optional<ProcessDefinition> processDefiniti...
63251719_15
class DockerNode extends AbstractJCloudsNode<DockerCloudProvider> { @Override public ExecResult exec(String... command) { MiscApi api = cloudProvider.getMiscApi(); ExecCreateParams execCreateParams = ExecCreateParams.builder().attachStderr(true).attachStdout(true) .cmd(Arrays.as...
File srcFile = new File(WORK_DIR, "testCopyToNodeFileToNullTarget"); FileUtils.write(srcFile, "original content"); alpineSshNode.copyFileToNode(srcFile.toPath(), null); assertEquals("original content", alpineSshNode.exec("cat", "testCopyToNodeFileToNullTarget").getOutput(...
63270256_0
class SpringVoidRequestHandler extends SpringRequestHandler<I, Void> { @Override public Void handleRequest(final I input, final Context context) { super.handleRequest(input, context); return null; } ApplicationContext mockApplicationContext; } class SpringVoidRequestHandlerTest { ...
final RequestHandler handler = mock(RequestHandler.class); when(mockApplicationContext.getBean(RequestHandler.class)).thenReturn(handler); final TestSpringVoidRequestHandler testHandler = new TestSpringVoidRequestHandler(); final Context mockContext = mock(Context.class); final S...
63353944_0
class ErrorHandler { public ErrorHandler skipDefaults() { if (localContext != null) { localContext.get().skipDefaults = true; } return this; } private ErrorHandler(); private ErrorHandler(ErrorHandler parentErrorHandler); public static ErrorHandler createIsol...
ErrorHandler .create() .on(FooException.class, (throwable, handler) -> { actionDelegateMock.action1(); }) .handle(new FooException("foo error")); Mockito.verify(actionDelegateMock, times(1)).action1(); Mockito.v...
63372616_304
class NavigableSetTypeReferenceReader implements TypeReferenceReader { @Override public boolean test(TypeSupplier<?> typeReference) { Type type = typeReference.get(); if (ParameterizedType.class.isInstance(type)) { ParameterizedType parameterizedType = ParameterizedType.class.cast(t...
assertFalse(referenceReader.test(new TypeReference<SortedSet<Animal>>() { })); assertFalse(referenceReader.test(new TypeReference<NavigableSet<Animal>>() { })); assertFalse(referenceReader.test(new TypeReference<ArrayList<BigDecimal>>() { })); assertFalse(refere...
63380093_0
class Indexer { public void index(File sourceCodeDirectory) throws IOException { System.out.println("Indexing source code in " + sourceCodeDirectory.getAbsolutePath() + " into " + getDatabasePath(databaseDirectory)); databaseInitializer.initDatabase(); Collection<File> files = listFiles(so...
indexer.index(sourceCodeDirectory); assertThat(count("class")).isEqualTo(2); assertThat(count("interface")).isEqualTo(2); assertThat(count("annotation")).isEqualTo(1); assertThat(count("enumeration")).isEqualTo(1); assertThat(count("field")).isEqualTo(3); assertT...
63394793_9
class BaseHelper implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { @Override public void onConnectionSuspended(int i) { // Method's body left empty as we deem it's the best behavior. // // http://stackoverflow.com/a/27350444/972721 ...
baseHelper.onConnectionSuspended(0); Assert.assertEquals(0, baseHelper.onLocationPermissionsGrantedCount[0]); Assert.assertEquals(0, baseHelper.onGooglePlayServicesDisconnectingCount[0]); } }
63452341_16
class TickerCharacterList { CharacterIndices getCharacterIndices(char start, char end, TickerView.ScrollingDirection direction) { int startIndex = getIndexOfChar(start); int endIndex = getIndexOfChar(end); if (startIndex < 0 || endIndex < 0) { return null; } sw...
final TickerCharacterList list = new TickerCharacterList("012"); final TickerCharacterList.CharacterIndices indices = list.getCharacterIndices('0', '2', TickerView.ScrollingDirection.ANY); assertEquals(4, indices.startIndex); assertEquals(3, indices.endIndex); } }
63468727_7
class City extends ExceptStoredHolder { @Slow public Collection<Island> disclaim(@NotNull ChunkPos chunk, boolean createIslands) throws IllegalStateException, IllegalArgumentException, DataSourceException { if(invalid) throw new IllegalStateException(); if(islands.s...
BlockPos spawn = new BlockPos(test.overWorld, 200,64,100); ChunkPos spawnChunk = spawn.getChunk(); City city = new City(test.mineCity, "Disclaim", test.joserobjr, spawn, 0); Island spawnIsland = city.islands().iterator().next(); assertThrown(()-> city.disclaim(spawnChunk, false)...
63481746_1
class BurgersViewModel { @NonNull public Observable<Bun> getBunStream() { return mDataModel.getBunStream(); } public BurgersViewModel(@NonNull final DataModel dataModel); @NonNull public Observable<TomatoSlice> getTomatoSliceStream(); @NonNull public Observable<Meat> getMeatStream();...
ArrangeBuilder builder = new ArrangeBuilder(); TestSubscriber<Bun> testSubscriber = new TestSubscriber<>(); mViewModel.getBunStream().subscribe(testSubscriber); builder.withBun(BUN); testSubscriber.assertNoErrors(); testSubscriber.assertValue(BUN); } }
63499588_6
class MorseRecord extends AlexaStateModel { public void setOverallHighscorer(final String overallHighscorer) { this.overallHighscorer = overallHighscorer; } public Integer getOverallHighscore(); public void setOverallHighscore(final Integer score); public String getOverallHighscorer(); ...
final String highscorer = "Bob"; record.setOverallHighscorer(highscorer); assertEquals(highscorer, record.getOverallHighscorer()); } }
63527700_1
class TimeViewModel { public String formattedTime() { return formatWithPadding(time.hour()) + COLON + formatWithPadding(time.minutes()); } public TimeViewModel(Time time); public String formattedDate(); private String format(String pattern); private String formatWithP...
Time time = Mockito.mock(Time.class); Mockito.when(time.hour()).thenReturn(10); Mockito.when(time.minutes()).thenReturn(37); Mockito.when(time.seconds()).thenReturn(24); TimeViewModel timeViewModel = new TimeViewModel(time); String expectedFormattedTime = "10:37"; ...
63534520_26
class Project implements TypeIdentifiable { @XmlElement public Date getCreated() { return created; } public Project(); protected Project(Project projectDto); @XmlElement public String getId(); public void setId(String id); @XmlElement public String getName(); public void...
final Date date = new Date(); final Project project = new Project(); project.setCreated(date); Assert.assertEquals(date, project.getCreated()); } }
63553502_20
class XmlUtils { @Nonnull public static String getPathInWorkspace(@Nonnull final String absoluteFilePath, @Nonnull FilePath workspace) { boolean windows = FileUtils.isWindows(workspace); final String workspaceRemote = workspace.getRemote(); String sanitizedAbsoluteFilePath; St...
String workspace = "C:\\path\\to\\spring-petclinic\\"; String absolutePath = "C:\\path\\to\\spring-petclinic\\pom.xml"; String actual = XmlUtils.getPathInWorkspace(absolutePath, new FilePath(new File(workspace))); String expected = "pom.xml"; assertThat(actual, is(expected)); ...
63689332_0
class SimulationTreeTableToModelConverter { public BPMNProcess convertTreeToModel(final EventTree<Object> tree) { this.tree = tree; final BPMNStartEvent startEvent = new BPMNStartEvent(this.createID(), "Start", null); this.process.addBPMNElement(startEvent); final BPMNEndEvent endEvent = new BPMNEndEvent(this...
final SimulationTreeTableToModelConverter converter = new SimulationTreeTableToModelConverter(); final BPMNProcess process = converter.convertTreeToModel(this.tree); Assert.assertTrue("Should be 14, but was " + process.getBPMNElementsWithOutSequenceFlows().size(), process.getBPMNElementsWithOutSequenceFlows().siz...
63693352_17
class MongoUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = repository.findOne(username); if (user == null) { throw new UsernameNotFoundException(username); } return user; } @InjectMocks...
final User user = new User(); when(repository.findOne(any())).thenReturn(user); UserDetails loaded = service.loadUserByUsername("name"); assertEquals(user, loaded); } }
63707572_2
class InstanceService { public static Set<Instance> getInstances(final Context context) { if (!SystemResolver.get().isReadCalendarPermitted(context)) { return new HashSet<>(); } return readAllInstances(context); } static Set<Instance> readAllInstances(final Context con...
when(systemResolver.isReadCalendarPermitted(context)).thenReturn(false); Set<Instance> instances = getInstances(context); assertTrue(instances.isEmpty()); } }
63749548_5
class ClientBuilder implements Cloneable { public Collection<URI> endpoints() { return Collections.unmodifiableCollection(this.endpoints); } ClientBuilder(); public ClientBuilder endpoints(Collection<URI> endpoints); public ClientBuilder endpoints(URI... endpoints); public ClientBui...
// test default namespace setting final ClientBuilder builder = Client.builder().endpoints(new URI("http://127.0.0.1:2379")); final ClientConnectionManager connectionManager = new ClientConnectionManager(builder); assertThat(connectionManager.getNamespace()).isEqualTo(ByteSequence.EMPTY)...
63796401_11
class WeeklyPaymentSchedule extends PaymentSchedule { @Override public boolean isPayDate(LocalDate date) { return isDayOfWeek(date, PAYDAY_DAY_OF_WEEK); } @Override public DateInterval getPayIntervalForValidatedPayDate(LocalDate intervalEndDate); @Override public LocalDate getSameOrNextPayDate(LocalDate refere...
assertThat(weeklyPaymentSchedule.isPayDate(THIS_MONDAY), is(false)); assertThat(weeklyPaymentSchedule.isPayDate(PREV_SATURDAY), is(false)); } }
63800550_0
class JmsSendingMessageHandlerFactory implements ApplicationContextAware, BeanFactoryAware { public PartitionAwareJmsSendingMessageHandler build(TopicPartitionRegistrar destinations) { template.setPubSubDomain(true); PartitionAwareJmsSendingMessageHandler handler = new PartitionAwareJmsSendingMessageHandler( ...
PartitionAwareJmsSendingMessageHandler handler = target.build(TOPIC_PARTITION_REGISTRAR); assertThat(ReflectionTestUtils.getField(handler, "jmsTemplate"), Matchers.<Object>is(jmsTemplate)); } }
63837927_17
class AWSS3BuildProcessAdapter extends BuildProcessAdapter { public boolean runProcess() { final AgentRunnerBuildParametersModel model = helper.createModel(runnerParametersMap); AmazonS3 s3Client = createClient(model.getPublicKey(), model.getPrivateKey(), model.getBucketRegion(), model.getHttpProx...
final String bucketName = "someName"; final String bucketRegion = "someRegion"; final String uploadTaskLogBucket = uploadTaskLog + bucketName; final String desiredArtifactPaths = "src,examples/subfolder"; final String sourcePath = "src"; final String destinationPath = sou...
63894475_22
class BaseRESTServiceJavaDelegate implements JavaDelegate { void updateDataKeyVariable(DelegateExecution delegateExecution, ResponseEntity<Object> serviceResponse) { Object value = null; if (serviceResponse != null) value = serviceResponse.getBody(); setProcessVariable(delegateE...
final ResponseEntity<Object> responseEntity = mock(ResponseEntity.class); given(responseEntity.getBody()).willReturn("foo"); doThrow(RuntimeException.class).when(delegateExecution).setVariable(eq(BaseRESTServiceJavaDelegate.DATA_KEY), isNotNull()); try { baseDelegate.updateDa...
63895649_23
class MetaUtils { static public boolean containsHyperlink(String s) { return startsWithNetworkProtocol(s) || HYPERLINK.matcher(s).find(); } private MetaUtils(); static public boolean startsWithNetworkProtocol(String s); static public boolean endsWithFileExtension(String s); } class MetaUtilsTest { @Test...
String s; s = "http://www.clearnlp.com"; assertTrue(MetaUtils.containsHyperlink(s)); s = "https://www-01.clearnlp.com"; assertTrue(MetaUtils.containsHyperlink(s)); s = "www.clearnlp.com"; assertTrue(MetaUtils.containsHyperlink(s)); s = "wiki.clearnlp.com"; assertTrue(MetaUtils.containsHype...
63898559_0
class TemplatePlugin implements Plugin { public PluginMessageHandlingResult onCommand(Command command) { if (command.getCommand().equalsIgnoreCase("template")) { if (Objects.equals(command.getArgs().get(0), "topic")) { final String template = command.getArgs().subList(1, command...
tester.getPublicVariables().onNext(new PublicVariables(ImmutableMap.of("foo.oof", "bar"))); tester.test(plugin -> plugin.onCommand(Command.of("/bot template topic hello ${foo.oof} rocks"))); assertThat(tester.getRoomApi().getLastTopic(), is("hello bar rocks")); tester.getPublicVariables...
63931184_186
class DistributedLogManagerImpl implements DistributedLogManager { @Override public AppendOnlyStreamWriter getAppendOnlyStreamWriter() throws IOException { return impl.getAppendOnlyStreamWriter(); } public DistributedLogManagerImpl(org.apache.distributedlog.api.DistributedLogManager impl); ...
AppendOnlyStreamWriter writer = mock(AppendOnlyStreamWriter.class); when(impl.getAppendOnlyStreamWriter()).thenReturn(writer); assertEquals(writer, manager.getAppendOnlyStreamWriter()); verify(impl, times(1)).getAppendOnlyStreamWriter(); } }
63947141_375
class AsyncEndpointResponseCall implements AsyncEndpointCall<EndpointResponse<T>> { @Override public void executeAsync(EndpointCallCallback<EndpointResponse<T>> callback) { new CompletionStageAsyncEndpointCall<>(doExecuteAsync(), executor) .executeAsync(callback); } public AsyncEndpointResponseCall(Endpoint...
asyncCall.executeAsync(callback); verify(callback).onSuccess(response); verify(asyncEndpointRequestExecutor).executeAsync(request); } }
63972047_1
class MediaIDHelper { public static String getParentMediaID(@NonNull String mediaID) { String[] hierarchy = getHierarchy(mediaID); if (!isBrowseable(mediaID)) { return createMediaID(null, hierarchy); } if (hierarchy.length <= 1) { return MEDIA_ID_ROOT; ...
assertEquals( MediaIDHelper.MEDIA_ID_ROOT, MediaIDHelper.getParentMediaID(MediaIDHelper.MEDIA_ID_ROOT)); } }
64025178_6
class VoxelwindBaseInventory implements Inventory { @Override public boolean addItem(@Nonnull ItemStack stack) { return addItem(stack, null); } VoxelwindBaseInventory(InventoryType type); @Override public Optional<ItemStack> getItem(int slot); @Override public void setItem(int slot,...
VoxelwindBaseInventory inventory = new VoxelwindBaseInventory(InventoryType.CHEST); assertTrue("Can't add item even when inventory is empty", inventory.addItem(new VoxelwindItemStack(BlockTypes.DIRT, 1, null))); assertTrue("Can't add item but no conflicts exist", inventory.addItem(new VoxelwindI...
64067562_4
class ResponseParser { @NonNull Student parseStudent(@NonNull String loginJson, @NonNull String attendanceJson) throws InvalidCredentialsException, InvalidResponseException { Student student = processLogin(loginJson); try { student.subjects.putAll(processAttendance(atten...
ResponseParser responseParser = new ResponseParser(); Student student = responseParser.parseStudent("{\"name\":\"name\",\"status\":\"success\"}", ""); assertEquals(0, student.subjects.size()); } }
64095208_18
class ItemGetter { ItemDetails get(IInAppBillingService service, String itemType, ArrayList<String> itemIds) throws BillingException { ItemDetails itemDetails = new ItemDetails(); List<ArrayList<String>> splitItemIdList = new ArrayList<>(); // There...
int size = 20; ArrayList<String> itemIds = mDataConverter.convertToItemIdArrayList(size); ArrayList<String> items = mDataConverter.convertToSkuItemDetailsJsonArrayList(size, PurchaseType.IN_APP); Bundle responseBundle = new Bundle(); responseBundle.putLong(Constants.RESPONSE_CODE...
64177091_38
class OptimizelyClient { public @Nullable NotificationCenter getNotificationCenter() { if (isValid()) { return optimizely.notificationCenter; } else { logger.warn("Optimizely is not initialized, could not get the notification listener"); } return null; ...
OptimizelyClient optimizelyClient = new OptimizelyClient(optimizely, logger); ActivateNotificationListener listener = new ActivateNotificationListener() { @Override public void onActivate(Experiment experiment, String userId, Map<String, ?> attributes, Variation variation, LogEve...
64185596_146
class DalConnectionManager { public DalConnection getNewConnection(DalHints hints, boolean useMaster, DalEventEnum operation) throws SQLException { DalConnection connHolder = null; String realDbName = logicDbName; try { if(DalStatusManager.getDatabaseSetStatus(logicDbName).isMarkdown()) throw new Da...
boolean useMaster = true; DalHints hints = new DalHints(); try { DalConnectionManager test = getDalConnectionManager(noShardDb); DalConnection conn = test.getNewConnection(hints, useMaster, DalEventEnum.BATCH_CALL); assertNotNull(conn); assertNotNull(conn.getConn()); conn.getConn().close(); } ...
64193956_151
class AddEditTaskPresenter implements AddEditTaskContract.Presenter, LoaderManager.LoaderCallbacks<Cursor>, TasksDataSource.GetTaskCallback { @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToLast()) { Task task = Task.from(dat...
Task testTask = new Task("TITLE", "DESCRIPTION"); // When the presenter is asked to populate an existing task mAddEditTaskPresenter.onLoadFinished(mock(Loader.class), mActiveTaskCursor); // Then the task repository is queried and the view updated //verify(mTasksRepository).getT...
64203431_21
class Emitter { public List<Listener> listeners(String event) { ConcurrentLinkedQueue<Listener> callbacks = this.callbacks.get(event); return callbacks != null ? new ArrayList<Listener>(callbacks) : new ArrayList<Listener>(0); } public Emitter on(String event, Listener fn);...
Emitter emitter = new Emitter(); assertThat(emitter.listeners("foo").toArray(), is(new Object[] {})); } }
64210266_4
class MesosHTTPFetcher { public static Optional<String> extractDirectory(InputStream stream, String frameworkId, String executorId, String containerId) throws IOException { // TODO: prepare corresponding object type instead of using java.util.Map ...
InputStream in; Optional<String> s; in = MesosHTTPFetcherTest.class.getResourceAsStream("/slave-state.json"); s = MesosHTTPFetcher.extractDirectory(in, "3a3e9491-84a5-4c9d-8fed-5ca10c23d922-0000", "sum", "d9b0e1d9-49dc-4dd1-8773-d53366fc1517"); assertTrue(s.isPre...
64226557_15
class ConfigProvider implements Provider<Config> { @Override public Config get() { return config; } @Inject public ConfigProvider(); } class ConfigProviderTest { @Test public void check_that_the_configuration_is_correctly_loaded() {
Config config = new ConfigProvider().get(); assertThat(config.getString("generic.property")).isEqualTo("Text property"); assertThat(config.getIntList("generic.to-be-overriden")).containsExactly(4, 5); } }
64257587_220
class JsonSimpleConfigParser implements ConfigParser { @Override public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParseException { try { JSONParser parser = new JSONParser(); JSONObject rootObject = (JSONObject) parser.parse(json); String a...
JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); ProjectConfig actual = parser.parseProjectConfig(validConfigJsonV3()); ProjectConfig expected = validProjectConfigV3(); verifyProjectConfig(actual, expected); } }
64339521_6
class AuthenticationResult implements IAuthenticationResult { @Nullable @Override public UUID getCorrelationId() { return mCorrelationId; } AuthenticationResult(@NonNull final List<ICacheRecord> cacheRecords, @Nullable final String correlationId); @Override ...
final String invalidCorrelationId = "garbage"; AuthenticationResult authenticationResult = new AuthenticationResult( mCacheRecords, invalidCorrelationId ); Assert.assertNotNull(authenticationResult); Assert.assertNull(authenticationResult.getCorre...
64340716_77
class PropertyUtils { public static Type getPropertyType(Class<?> beanClass, String field) { try { return INSTANCE.findPropertyType(beanClass, field); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw handleReflectionException(bea...
// WHEN Object result = PropertyUtils.getPropertyType(Bean.class, "setProperty"); // THEN assertThat(ParameterizedType.class).isAssignableFrom(result.getClass()); } }
64371551_1
class LoginPresenter { void doLogin(String userName, String password) { if (isLoginAttemptExceeded()) { loginView.showErrorMessageForMaxLoginAttempt(); return; } if (userName.equals("nj") && password.equals("tdd")) { loginView.showLoginSuccessMessage(); ...
LoginView loginView= mock(LoginView.class); LoginPresenter loginPresenter = new LoginPresenter(loginView); loginPresenter.doLogin("nj","tdd"); verify(loginView).showLoginSuccessMessage(); } }
64405938_0
class AllNamesStrategy implements QueryAssemblyStrategy { @Override public String getQuery(DBpediaResource resource, int option) { return constructQuery(resource, this.excludeNames+option); } public AllNamesStrategy(); public AllNamesStrategy(int excludeNames); @Override public Stri...
List<String> names = new LinkedList<>(); names.add("test_name"); names.add("test_name"); names.add("test_name"); names.add("test_name"); names.add("test_name2"); names.add("test_name2"); names.add("test_name2"); names.add("test_name3"); na...
64431348_524
class DropWizardUtils { static String generateFullMetricDescription(String metricName, Metric metric) { return "Collected from " + SOURCE + " (metric=" + metricName + ", type=" + metric.getClass().getName() + ")"; } private DropWizardUtils(); static String...
assertThat(DropWizardUtils.generateFullMetricDescription("Counter", new Counter())) .isEqualTo("Collected from codahale (metric=Counter, type=com.codahale.metrics.Counter)"); } }
64458355_0
class BundledJarRunnable implements TwillRunnable { protected void setMainArgs(String[] mainArgs) { this.arguments = new BundledJarRunner.Arguments.Builder() .from(arguments) .setMainArgs(mainArgs) .createArguments(); } @Override public void stop(); @Override public void run(); protect...
String[] mainArgs = {"a", "b", "c"}; String jarFileName = "test/123.jar"; String libFolder = "libsdf"; String mainClassName = "org.apache.twill.ext.Test"; List<String> argsArrayList = ImmutableList.<String>builder() .add(jarFileName) .add(libFolder) .add(mainClassName) .addA...
64510591_31
class Provider { public final Single<T> read() { return Single.defer(() -> Single.fromObservable(builder.processorProviders .<T>process(getConfigProvider(exceptionAdapter.placeholderLoader(), new EvictDynamicKey(false), false, null)))) .onErrorResumeNext(exceptionAdapt...
saveMock(); TestObserver<Mock> observer = cacheProvider.read().test(); observer.awaitTerminalEvent(); observer.assertValueCount(1); observer.assertNoErrors(); observer.assertComplete(); assertThat(observer.values() .get(0).getMessage(), is(MESSAGE)); } }
64529819_0
class Policy { public abstract A nextAction(INDArray input)public abstract A nextAction(INDArray input); public abstract A nextAction(INDArray input)public abstract NeuralNet getNeuralNet(); public abstract A nextAction(INDArray input)public double play(MDP<O, A, AS> mdp); public abstract A nextAction(INDArray input)...
ACPolicy policy = new ACPolicy(new DummyAC(), new Random(555)); INDArray input = Nd4j.create(new double[] {1.0, 0.0}); for (int i = 0; i < 100; i++) { assertEquals(0, (int)policy.nextAction(input)); } input = Nd4j.create(new double[] {0.0, 1.0}); for (int i ...
64565477_5
class EnvironmentVariablesConfigurationSource implements ConfigurationSource { @Override public JsonNode getConfiguration() { return ConfigurationUtils.Properties.fromMap(System.getenv()); } private final EnvironmentVariablesConfigurationSource environmentVariablesConfigurationSource; } class EnvironmentVaria...
String environmentVariableKey = "key"; String environmentVariableValue = "value"; new MockUp<System>() { @Mock Map<String,String> getenv() { Map<String, String> environmentVariables = new HashMap<>(); environmentVariables.put(environmentVariableKey, environmentVariableValue); return environm...
64608558_1
class CellularAutomaton { public Rule getRule() { return this.rule; } protected CellularAutomaton(Rule rule); public void executeRule(Space space, Time time); } class CellularAutomatonTest { @Test public void dimensionalCellularAutomataConstructor() throws CloneNotSupportedException, InvalidAbsoluteTi...
final State dimensionalBlackState = new DimensionalState("black", 0); final State dimensionalWhiteState = new DimensionalState("white", 1); final Combination dimensionalCombination0 = new DimensionalCombination(dimensionalBlackState, dimensionalBlackState, dimensionalBlackState); final Transition dimensiona...
64658258_0
class Period implements Serializable { public Calendar periodBegin(Calendar time) { return periodBegin(time, 0); } private Period(int periodSeconds, int beginOffsetSeconds); public int periodSeconds(); public int periodBeginOffsetSeconds(); public static Period secondsOf(int periodSe...
Period p = Period.secondsOf(60); Calendar t1 = Calendar.getInstance(); t1.set(Calendar.MILLISECOND, 999); t1.set(Calendar.SECOND, 59); Calendar t2 = Calendar.getInstance(); t2.set(Calendar.MILLISECOND, 0); t2.set(Calendar.SECOND, 0); t2.add(Calendar.MINU...
64719557_101
class HttpServletResponseWrapperForResponseInfo implements HttpServletResponse { @Override public void sendRedirect(String location) throws IOException { throw new UnsupportedOperationException(); } public HttpServletResponseWrapperForResponseInfo(ResponseInfo<T> responseInfo); @Override...
// expect verifyUnsupportedOperation(() -> wrapper.sendRedirect(null)); } }
64751214_2
class DataService implements Serializable { public Collection<Category> getAllCategories() { return categoryRepository.findAll(); } public Collection<Product> getAllProducts(); public Product updateProduct(Product product); public void deleteProduct(int productId); public Product getPr...
Category category = new Category(); category.setName("foo"); long count = categoryRepository.count(); Category created = categoryRepository.save(category); Assert.assertNotEquals(-1, created.getId()); Assert.assertEquals(count + 1, categoryRepository.count()); ...
64767540_1
class XWikiLDAPConfig { @Deprecated public boolean isLDAPEnabled(XWikiContext context) { return isLDAPEnabled(); } @Deprecated public XWikiLDAPConfig(String userId, XWikiContext xcontext); public XWikiLDAPConfig(String userId); public XWikiLDAPConfig(String userId, Configuration...
// No param set assertEquals(false, this.config.isLDAPEnabled()); assertEquals(false, this.config.isLDAPEnabled(null)); // Param set in xwiki.cfg only setCfgPreference("xwiki.authentication.ldap", "1"); assertEquals(true, this.config.isLDAPEnabled()); assertEqual...
64785879_7
class UnidentifiedProducer { public void sendName(String destinationName, String firstName, String lastName) throws JMSException { String text = firstName + " " + lastName; // create a JMS TextMessage TextMessage textMessage = session.createTextMessage(text); // create the Destination to whi...
try { unidentifiedProducer.sendName("helloworld.q", "John", "Doe"); String greeting = consumer.getGreeting(1000); assertEquals("Hello John Doe!", greeting); } catch (JMSException e) { fail("a JMS Exception occurred"); } } }
64790683_1
class CategoryResource { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{categoryId}") public Category get(@PathParam("categoryId") Integer categoryId) { return em.find(Category.class, categoryId); } @GET @Produces(MediaType.APPLICATION_JSON) public Collection<Category> all(); ...
Response response = given() .pathParam("categoryId", 1014) .when() .get("/admin/category/{categoryId}") .then() .extract().response(); String jsonAsString = response.asString(); ...
64873196_8
class IncrementalPositionIterator extends AbstractPositionIterator { @Override public Integer next() { if (!hasNext()) throw new IllegalStateException("position out of bounds reached"); return pos++; } IncrementalPositionIterator(@IntRange(from = 0) int itemCount); @Override pub...
AbstractPositionIterator iterator = providePositionIterator(5); int result = iterator.next(); assertTrue(result == 0); result = iterator.next(); assertTrue(result == 1); result = iterator.next(); assertTrue(result == 2); } }
65041301_17
class UserRepository { @VisibleForTesting Single<Reply<List<User>>> getUsersReply(Integer lastIdQueried, final boolean refresh) { int safeId = lastIdQueried == null ? FIRST_DEFAULT_ID : lastIdQueried; Single<List<User>> apiCall = githubUsersApi .getUsers(safeId, USERS_PER_PAGE) .compose(ne...
mockApiForSuccess(); TestObserver<Reply<List<User>>> observer1 = userRepositoryUT.getUsersReply(null, false).test(); observer1.awaitTerminalEvent(); assertEquals(Source.CLOUD, observer1.values().get(0).getSource()); TestObserver<Reply<List<User>>> observer2 = userRepositoryUT.getUsersRepl...
65084302_122
class HttpRequestReplaceFilter extends AbstractRequestReplaceFilter implements Filter { @Override public void doFilter(ApiContext apiContext, Future<ApiContext> completeFuture) { for (int i = 0; i < apiContext.requests().size(); i++) { RpcRequest request = apiContext.requests().get(i); ...
Multimap<String, String> params = ArrayListMultimap.create(); Multimap<String, String> headers = ArrayListMultimap.create(); JsonObject jsonObject = new JsonObject(); ApiContext apiContext = ApiContext.create(HttpMethod.GET, "/devices", headers, params, jsonObject); ...
65089775_0
class ASpinWait { public boolean awaitFulfill(final Instant waitingSince) throws IOException { while (true) { awaitFulfill(waitingSince, Duration.ONE_DAY); } } protected Duration determineSkipSpinAfterWaitingSince(); protected static MethodHandle determineOnSpinWait(); ...
final ASpinWait waitingSpinWait = new ASpinWait() { @Override protected boolean isConditionFulfilled() { return false; } }; final Duration maxWait = Duration.ONE_SECOND; final Instant waitingSince = new Instant(); waitingSpinWa...
65158020_24
class EGradleJUnitTaskVariableReplacement { public String replace(String origin, String replacement) { if (origin == null) { return null; } if (replacement == null) { return origin; } Matcher matcher = PATTERN.matcher(origin); String result = matcher.replaceAll(replacement); return result; } pr...
/* prepare */ String tasksWithVariable = null; /* execute */ String tasks = supportToTest.replace(tasksWithVariable, "REPLACEMENT"); /* test */ assertEquals(tasksWithVariable, tasks); } }
65194280_0
class SequenceTempDirMgr extends TempDirMgr { public synchronized Path getTempDir() throws IOException { Path tempDir = new Path(prefix+Integer.toString(seqNum++)); if(fileSystem!=null) { while (dirs.contains(tempDir) || fileSystem.exists(tempDir)) { tempDir = new Path(prefix+Integer.toString(se...
SequenceTempDirMgr mgr=new SequenceTempDirMgr("test", 2); mgr.getTempDir(); Path path2=mgr.getTempDir(); mgr.getTempDir(); mgr.getTempDir(); assertTrue(mgr.getDirs().size()==4); assertTrue(mgr.getSeqNum()==6); mgr.removePath(path2); assertTrue(mgr.getDirs().size()==3); mgr.deleteAll(); assertT...
65245890_41
class EpoxyController implements ModelCollector, StickyHeaderCallbacks { public boolean isDuplicateFilteringEnabled() { return filterDuplicates; } public EpoxyController(); public EpoxyController(Handler modelBuildingHandler, Handler diffingHandler); public void requestModelBuild(); public boolean ...
EpoxyController controller = new EpoxyController() { @Override protected void buildModels() { } }; assertFalse(controller.isDuplicateFilteringEnabled()); } }
65277100_0
class BasicObservable implements Observable<V> { protected void updateValue(final V value) { if(inWillChangeEvent) { throw new IllegalStateException("Value can not change while willChangeEvents are handled!"); } if (this.value != value) { boolean canChange = fireWill...
try { BasicObservable<Boolean> observable = new BasicObservable<>(); CheckBooleanObservable.checkBooleanObservableBasicMethods(observable); } catch (Exception e) { e.printStackTrace(); Assert.fail("Error"); } try { BasicObserva...
65312676_1
class AIServiceContextBuilder { public AIServiceContext build() { if (sessionId == null) { throw new IllegalStateException("Session id is undefined"); } return new PlainAIServiceContext(sessionId, timeZone); } public AIServiceContextBuilder(); public String getSessionId(); public AIServi...
AIServiceContextBuilder builder = new AIServiceContextBuilder(); assertNull(builder.getSessionId()); builder.setSessionId(DUMMY_SESSION_ID); assertEquals(DUMMY_SESSION_ID, builder.getSessionId()); AIServiceContext context = builder.build(); assertEquals(DUMMY_SESSION_ID, context.getSessionId()); } ...
65356302_30
class OkHttpSender extends Sender { @Override public CheckResult check() { try { Request request = new Request.Builder().url(endpoint) .post(RequestBody.create(MediaType.parse("application/json"), "[]")).build(); try (Response response = client.newCall(request).execute()) { if (!respo...
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); assertThat(sender.check().ok()).isFalse(); } }
65402989_8
class BundleImmutable implements IBundle { @NonNull @Override public Option<Float> getFloat(@NonNull final String key) { return getObject(key) .ofType(Float.class); } public BundleImmutable(); public BundleImmutable(@NonNull final Map<String, Object> map); @NonNu...
String key = "SomeKey"; final float value = 0.2f; BundleImmutable bundle = new BundleImmutable( Collections.<String, Object>singletonMap(key, value)); Option<Float> result = bundle.getFloat(key); assertThat(OptionUnsafe.getUnsafe(result)).isEqualTo(value); }...
65441815_0
class WikiSearch { public List<Entry<String, Double>> sort(Map<String, Double> map) { List<Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet()); Comparator<Entry<String, Double>> comparator = new Comparator<Entry<String, Double>>(){ public int compare(Entry<String, Double> one...
List<Entry<String, Integer>> list = search2.sort(); assertThat(list.get(0).getValue(), is(4)); assertThat(list.get(1).getValue(), is(5)); assertThat(list.get(2).getValue(), is(7)); } }
65505864_3
class CloudPubSubSinkConnector extends SinkConnector { @Override public List<Map<String, String>> taskConfigs(int maxTasks) { // Each task will get the exact same configuration. Delegate all config validation to the task. ArrayList<Map<String, String>> configs = new ArrayList<>(); for (int i = 0; i < m...
connector.start(props); List<Map<String, String>> taskConfigs = connector.taskConfigs(NUM_TASKS); assertEquals(taskConfigs.size(), NUM_TASKS); for (int i = 0; i < taskConfigs.size(); ++i) { assertEquals(taskConfigs.get(i), props); } } }
65507705_13
class GerritApiClient implements GerritApi { @Override public Observable<ServerInfo> getServerInfo() { return withVersionRequestCheck(mService.getServerInfo()); } GerritApiClient(String endpoint, Authorization authorization, PlatformAbstractionLayer abstractionLayer); privat...
final GerritApiClient client = getGerritClient(ENDPOINT); ServerInfo info = client.getServerInfo().blockingFirst(); assertNotNull(info); assertEquals(info.gerrit.docUrl, ENDPOINT + "Documentation/"); } }
65559078_9
class HarryPotter { static BigDecimal getPrice(List<Book> books) { return Function1.of(HarryPotter::getBookSets) .andThen(HarryPotter::getBundles) .andThen(HarryPotter::adjustBundles) .andThen(HarryPotter::getPriceForBundles) ...
assertThat(HarryPotter.getPrice(books(1, 1, 2, 2))).isEqualByComparingTo("30.40"); assertThat(HarryPotter.getPrice(books(1, 1, 2, 3))).isEqualByComparingTo("29.60"); } }
65582397_2
class LogServiceProtoUtil { public static LogServiceRequestProto toReadLogRequestProto(LogName name, long start, int total) { LogNameProto logNameProto = LogNameProto.newBuilder().setName(name.getName()).build(); ReadLogRequestProto.Builder builder = ReadLogRequestProto.newBuilder(); builder.setL...
LogName name = LogName.of("test"); long start = 100; int total = 5; LogServiceRequestProto proto = LogServiceProtoUtil.toReadLogRequestProto(name, start, total); ReadLogRequestProto request = proto.getReadNextQuery(); assertEquals(name.getName(), request.getLogName().getName()); assertEqual...
65604083_16
class PermutationSampler implements SharedStateSampler<PermutationSampler> { public static int[] natural(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i; } return a; } public PermutationSampler(UniformRandomProvider rng, ...
final int[] natural = PermutationSampler.natural(0); Assert.assertEquals(0, natural.length); } }
65606855_51
class CheckInHistoryViewModel extends ViewModel { public List<CheckInDetail> getCheckInDetails(Attendee attendee, List<CheckInDetail> checkInDetails) { String[] checkInTimes = attendee.getCheckinTimes().split(","); String[] checkOutTimes = attendee.getCheckoutTimes().split(","); for (int i...
List<CheckInDetail> ch = new ArrayList<>(); List<CheckInDetail> checkInDetails = checkInHistoryViewModel.getCheckInDetails(ATTENDEE, ch); assertEquals(checkInDetails.get(0).getCheckTime(), "2018-07-20T20:36:32.822+03:00"); assertEquals(checkInDetails.get(0).getScanAction(), SCAN_IN); ...
65701037_10
class ModifyTextPresenter implements ModifyTextContract.Presenter { @Override public void modifyText(String title, String oldString, String modifyString) { if (StringUtils.isEmpty(modifyString)) { view.showTip(title + "不能为空"); return; } // 旧文字为空或旧文字和新文字不相等,视为已修改...
String title = "昵称"; String oldString = ""; String modifyString = "bbb"; presenter.modifyText(title, oldString, modifyString); verify(view).modifyTextSuccess(true, "bbb"); } }
65751573_64
class BigQueryRecordConverter implements RecordConverter<Map<String, Object>> { public Map<String, Object> convertRecord(SinkRecord record, KafkaSchemaRecordType recordType) { Schema kafkaConnectSchema = recordType == KafkaSchemaRecordType.KEY ? record.keySchema() : record.valueSchema(); Object kafkaConnectS...
Map kafkaConnectMap = new HashMap<Object, Object>(){{ put("f1", "abc"); put("f2", "abc"); put("f3", null); }}; SinkRecord kafkaConnectRecord = spoofSinkRecord(null, kafkaConnectMap, true); Map<String, Object> stringObjectMap = new BigQueryRecordConverter(SHOULD_CONVERT_DOUBLE).convert...
65800867_31
class ProfileResultProcessor { public ProfileResult process(List<Run> runs) { if (runs.isEmpty()) { return null; } List<RootSingleProfileResult> results = new ArrayList<>(); for (Run run : runs) { results.add(processSingleRun(run)); } if (res...
assertNull(mProcessor.process(Collections.<Run>emptyList())); } }