focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static ServiceBusMessage createServiceBusMessage(
final Object data, final Map<String, Object> applicationProperties, final String correlationId) {
ServiceBusMessage serviceBusMessage;
if (data instanceof String) {
serviceBusMessage = new ServiceBusMessage((String) data);
... | @Test
void testCreateServiceBusMessage() {
// test string
final ServiceBusMessage message1 = ServiceBusUtils.createServiceBusMessage("test string", null, null);
assertEquals("test string", message1.getBody().toString());
// test int
final ServiceBusMessage message2 = Servic... |
@Override
public Processor<K, Change<V>, K, Change<VOut>> get() {
return new KTableTransformValuesProcessor(transformerSupplier.get());
} | @Test
public void shouldNotSendOldValuesByDefault() {
final KTableTransformValues<String, String, String> transformValues =
new KTableTransformValues<>(parent, new ExclamationValueTransformerSupplier(), null);
final Processor<String, Change<String>, String, Change<String>> processor = t... |
@Override
public byte[] serialize() {
byte[] optionsData = null;
if (this.options.hasOptions()) {
optionsData = this.options.serialize();
}
int optionsLength = 0;
if (optionsData != null) {
optionsLength = optionsData.length;
}
final ... | @Test
public void testSerialize() {
Redirect rd = new Redirect();
rd.setTargetAddress(TARGET_ADDRESS);
rd.setDestinationAddress(DESTINATION_ADDRESS);
rd.addOption(NeighborDiscoveryOptions.TYPE_TARGET_LL_ADDRESS,
MAC_ADDRESS.toBytes());
assertArrayEquals(... |
@Override // To express more specific javadoc
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
} | @SuppressWarnings("TruthSelfEquals")
@Test
public void isEqualTo() {
// make sure this still works
assertThat(TEN).isEqualTo(TEN);
} |
@Override
public boolean test(Pickle pickle) {
URI picklePath = pickle.getUri();
if (!lineFilters.containsKey(picklePath)) {
return true;
}
for (Integer line : lineFilters.get(picklePath)) {
if (Objects.equals(line, pickle.getLocation().getLine())
... | @Test
void matches_first_examples() {
LinePredicate predicate = new LinePredicate(singletonMap(
featurePath,
singletonList(5)));
assertTrue(predicate.test(firstPickle));
assertTrue(predicate.test(secondPickle));
assertFalse(predicate.test(thirdPickle));
... |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREF... | @Test
public void testFinalDestinationBaseSubdirsChild() {
assertEquals(l("2", "3.txt"),
finalDestination(l(MAGIC_PATH_PREFIX, "4", BASE, "2", "3.txt")));
} |
@Override
@MethodNotAvailable
public <T> T invoke(K key, EntryProcessor<K, V, T> entryProcessor, Object... arguments) throws EntryProcessorException {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testInvoke() {
adapter.invoke(23, new ICacheReplaceEntryProcessor(), "value", "newValue");
} |
@Override
public MetricsRepository load() {
List<Metric> metrics = new ArrayList<>();
try {
loadFromPaginatedWs(metrics);
} catch (Exception e) {
throw new IllegalStateException("Unable to load metrics", e);
}
return new MetricsRepository(metrics);
} | @Test
public void testIOError() throws IOException {
Reader reader = mock(Reader.class);
when(reader.read(any(char[].class), anyInt(), anyInt())).thenThrow(new IOException());
WsTestUtil.mockReader(wsClient, reader);
assertThatThrownBy(() -> metricsRepositoryLoader.load())
.isInstanceOf(IllegalS... |
public Collection<ResultPartitionID> stopTrackingPartitions(K key) {
Preconditions.checkNotNull(key);
Set<ResultPartitionID> storedPartitions = trackedPartitionsPerKey.remove(key);
return storedPartitions == null ? Collections.emptyList() : storedPartitions;
} | @Test
void testStopTrackingPartitions() {
final ResultPartitionID partitionId2 = new ResultPartitionID();
final PartitionTable<JobID> table = new PartitionTable<>();
table.startTrackingPartitions(JOB_ID, Collections.singletonList(PARTITION_ID));
table.startTrackingPartitions(JOB_ID,... |
static public String toString(InputStream input, String encoding) throws IOException {
return (null == encoding) ? toString(new InputStreamReader(input, StandardCharsets.UTF_8)) : toString(new InputStreamReader(
input, encoding));
} | @Test
public void testToString() throws Exception {
byte[] b = "testToString".getBytes(StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(b);
String str = IOTinyUtils.toString(is, null);
assertEquals("testToString", str);
is = new ByteArrayInputStream(b);
... |
public DeleteObjectsResult deleteObjects(List<String> keyList) throws CosClientException {
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(cosClientConfig.getBucket());
// 设置要删除的key列表, 最多一次删除1000个
ArrayList<DeleteObjectsRequest.KeyVersion> keyVersions = new ArrayList<>();
... | @Test
void deleteObjects() {
cosManager.deleteObjects(Arrays.asList("test/2.jpg",
"test/7.jpg"
));
} |
@Override
public String getName() {
return TransformFunctionType.OR.getName();
} | @Test
public void testOrNullColumn() {
ExpressionContext expression =
RequestContextUtils.getExpression(String.format("or(%s,%s)", INT_SV_COLUMN, INT_SV_NULL_COLUMN));
TransformFunction transformFunction = TransformFunctionFactory.get(expression, _dataSourceMap);
Assert.assertTrue(transformFunctio... |
public static Object newInstance(String name) {
try {
return forName(name).getDeclaredConstructor().newInstance();
} catch (InstantiationException
| IllegalAccessException
| InvocationTargetException
| NoSuchMethodException e) {
thr... | @Test
void testNewInstance1() {
Assertions.assertThrows(
IllegalStateException.class,
() -> ClassUtils.newInstance(
"org.apache.dubbo.common.compiler.support.internal.HelloServiceInternalImpl"));
} |
@Override
public boolean filterPath(Path filePath) {
if (getIncludeMatchers().isEmpty() && getExcludeMatchers().isEmpty()) {
return false;
}
// compensate for the fact that Flink paths are slashed
final String path =
filePath.hasWindowsDrive() ? filePath.... | @Test
void testExcludeFilenameWithStart() {
assumeThat(OperatingSystem.isWindows())
.as("Windows does not allow asterisks in file names.")
.isFalse();
GlobFilePathFilter matcher =
new GlobFilePathFilter(
Collections.singletonLi... |
public Method getMethod(Class<?> clazz, String name) {
Method m = null;
try {
for (Method tempMethod : clazz.getMethods()) {
if (tempMethod.getName().equals(name)) {
m = tempMethod;
break;
}
}
} catch (Exception e) {
m = null;
}
return m;
} | @Test
public void testGetMethodDeepInheritance() {
try {
ReflectionEngine engine = new ReflectionEngine();
MethodInvoker mInvoker;
TestEngine2 tEngine2 = new TestEngine2();
mInvoker = engine.getMethod(tEngine2, "method3", new Object[] { tEngine2 });
assertArrayEquals(mInvoker.getMethod().getParameter... |
public DirectGraph getGraph() {
checkState(finalized, "Can't get a graph before the Pipeline has been completely traversed");
return DirectGraph.create(
producers, viewWriters, perElementConsumers, rootTransforms, stepNames);
} | @Test
public void getRootTransformsContainsRootTransforms() {
PCollection<byte[]> impulse = p.apply(Impulse.create());
impulse.apply(WithKeys.of("abc"));
p.traverseTopologically(visitor);
DirectGraph graph = visitor.getGraph();
assertThat(graph.getRootTransforms(), hasSize(1));
assertThat(
... |
@Override
public Option<IndexedRecord> combineAndGetUpdateValue(IndexedRecord currentValue, Schema schema, Properties properties)
throws IOException {
return combineAndGetUpdateValue(currentValue, schema);
} | @Test
public void testDeleteWithEmptyPayLoad() {
Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING);
Properties properties = new Properties();
GenericRecord oldRecord = new GenericData.Record(avroSchema);
oldRecord.put("field1", 2);
oldRecord.put("Op", "U");
AWSDmsAvroPayload ... |
public static <P> Matcher<P> or(Iterable<? extends Matcher<P>> matchers) {
return or(toArray(matchers));
} | @Test void or_multiple_matched() {
Matcher<Void> one = b -> true;
Matcher<Void> two = b -> false;
Matcher<Void> three = b -> true;
assertThat(or(one, two, three).matches(null)).isTrue();
} |
public String getDataId() {
return dataId;
} | @Test
void getDataId() {
ConfigurationChangeEvent event = new ConfigurationChangeEvent();
event.setDataId("dataId");
Assertions.assertEquals("dataId", event.getDataId());
} |
@Override
public AppResponse process(Flow flow, SessionDataRequest request) throws SharedServiceClientException {
return validateAmountOfApps(flow, appSession.getAccountId(), request)
.orElseGet(() -> validateSms(flow, appSession.getAccountId(), request.getSmscode())
.orElseGet(... | @Test
void processActivateAppWithPasswordLetterFlow() throws SharedServiceClientException {
when(appAuthenticatorService.countByAccountIdAndInstanceIdNot(ACCOUNT_ID, SESSION_DATA_REQUEST_INSTANCE_ID)).thenReturn(3);
AppResponse appResponse = sessionConfirmed.process(mockedActivateAppWithPasswordLet... |
public byte[] createChildKeyStore(ApplicationId appId, String ksPassword)
throws Exception {
// We don't check the expiration date, and this will provide further reason
// for outside users to not accept these certificates
Date from = new Date();
Date to = from;
KeyPairGenerator keyGen = KeyPa... | @Test
void testCreateChildKeyStore() throws Exception {
ProxyCA proxyCA = new ProxyCA();
proxyCA.init();
ApplicationId appId =
ApplicationId.newInstance(System.currentTimeMillis(), 1);
byte[] keystoreBytes = proxyCA.createChildKeyStore(appId,
"password");
KeyStore keyStore = KeySto... |
@Override
public @Nullable Instant currentOutputWatermarkTime() {
return watermarks.getOutputWatermark();
} | @Test
public void getOutputWatermarkTimeUsesWatermarkTime() {
when(watermarks.getOutputWatermark()).thenReturn(new Instant(25525L));
assertThat(internals.currentOutputWatermarkTime(), equalTo(new Instant(25525L)));
} |
public static synchronized void registerProvider(ZuulBlockFallbackProvider provider) {
AssertUtil.notNull(provider, "fallback provider cannot be null");
String route = provider.getRoute();
if ("*".equals(route) || route == null) {
defaultFallbackProvider = provider;
} else {
... | @Test
public void testRegisterProvider() throws Exception {
MyNullResponseFallBackProvider myNullResponseFallBackProvider = new MyNullResponseFallBackProvider();
ZuulBlockFallbackManager.registerProvider(myNullResponseFallBackProvider);
Assert.assertEquals(myNullResponseFallBackProvider.getR... |
public static String[][] assignExecutors(
List<? extends ScanTaskGroup<?>> taskGroups, List<String> executorLocations) {
Map<Integer, JavaHash<StructLike>> partitionHashes = Maps.newHashMap();
String[][] locations = new String[taskGroups.size()][];
for (int index = 0; index < taskGroups.size(); index... | @Test
public void testFileScanTaskWithDeletes() {
StructLike partition1 = Row.of("k2", null);
StructLike partition2 = Row.of("k1");
List<ScanTask> tasks =
ImmutableList.of(
new MockFileScanTask(
mockDataFile(partition1), mockDeleteFiles(1, partition1), SCHEMA, SPEC_1),
... |
public String removeFileExtension(String filename) {
if (filename == null || filename.isEmpty()) {
return filename;
}
String extPattern = "(?<!^)[.]" + "[^.]*$";
return filename.replaceAll(extPattern, "");
} | @Test
public void testRemoveFileExtension() {
String result = fileUtil.removeFileExtension(FOOBAR_HTML);
assertEquals(FOOBAR, result);
result = fileUtil.removeFileExtension(null);
assertNull(result);
result = fileUtil.removeFileExtension("");
assertEquals(0, result... |
public Optional<ContentPackInstallation> findById(ObjectId id) {
final ContentPackInstallation installation = dbCollection.findOneById(id);
return Optional.ofNullable(installation);
} | @Test
@MongoDBFixtures("ContentPackInstallationPersistenceServiceTest.json")
public void findByIdWithInvalidId() {
final Optional<ContentPackInstallation> contentPacks = persistenceService.findById(new ObjectId("0000000000000000deadbeef"));
assertThat(contentPacks).isEmpty();
} |
@Override
public CompletableFuture<Long> getMessageStoreTimeStampAsync(String topic, int queueId,
long consumeQueueOffset) {
if (fetchFromCurrentStore(topic, queueId, consumeQueueOffset)) {
Stopwatch stopwatch = Stopwatch.createStarted();
return fetcher.getMessageStoreTimeSta... | @Test
public void testGetMessageStoreTimeStampAsync() {
// TieredStorageLevel.DISABLE
Properties properties = new Properties();
properties.setProperty("tieredStorageLevel", "DISABLE");
configuration.update(properties);
when(fetcher.getMessageStoreTimeStampAsync(anyString(), a... |
public List<Entity> insert(String kind, Map<Long, FullEntity<?>> entities) {
List<Entity> created = new ArrayList<>();
try {
for (Map.Entry<Long, FullEntity<?>> entry : entities.entrySet()) {
Key entityKey =
datastore.newKeyFactory().setKind(kind).setNamespace(namespace).newKey(entry.... | @Test
public void testInsert() {
// Prepare test data
Map<Long, FullEntity<?>> entities = new HashMap<>();
Entity entity = Entity.newBuilder(datastoreMock.newKeyFactory().newKey(1L)).build();
entities.put(1L, entity);
// Mock the Datastore put method
when(datastoreMock.put(any(FullEntity.clas... |
@Override
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
String scopeId = null;
if (scopedObjects != null) {
scopeId = Scope.enter(scopedObjects);
}
final AbstractLiquibaseCommand<T> subcommand =
requireNonNull(subcommands.get(nam... | @Test
void testRun() throws Exception {
// Apply and rollback some DDL changes
final TestMigrationConfiguration conf = MigrationTestSupport.createConfiguration();
assertThatNoException()
.isThrownBy(() -> dbTestCommand.run(null, new Namespace(Collections.emptyMap()), conf));
... |
@Override
public Collection<String> connectors() {
FutureCallback<Collection<String>> connectorsCallback = new FutureCallback<>();
herder.connectors(connectorsCallback);
try {
return connectorsCallback.get(herderRequestTimeoutMs, TimeUnit.MILLISECONDS);
} catch (Interrupt... | @Test
public void connectors() {
@SuppressWarnings("unchecked")
ArgumentCaptor<Callback<Collection<String>>> callback = ArgumentCaptor.forClass(Callback.class);
doAnswer(invocation -> {
callback.getValue().onCompletion(null, expectedConnectors);
return null;
}... |
static List<String> parseYarn(String[] args) {
String[] params = new String[args.length - 1];
System.arraycopy(args, 1, params, 0, params.length);
CommandLine commandLine = parse(YARN_OPTIONS, params);
if (commandLine.hasOption(OPTION_HELP.getOpt())) {
printYarnHelp();
... | @Test
void testParseYarnWithoutOptions() {
String[] args = {"yarn"};
List<String> commandOptions = PythonShellParser.parseYarn(args);
String[] expectedCommandOptions = {"yarn", "-m", "yarn-cluster"};
assertThat(commandOptions.toArray()).isEqualTo(expectedCommandOptions);
} |
@Override
public E set(int index, E element) {
return underlying.set(index, element);
} | @Test
public void testSet() {
BoundedList<Integer> list = BoundedList.newArrayBacked(3);
list.add(1);
list.add(200);
list.add(3);
assertEquals(Arrays.asList(1, 200, 3), list);
list.set(0, 100);
list.set(1, 200);
list.set(2, 300);
assertEquals(A... |
public boolean isEmptyValue( String valueName ) throws KettleValueException {
int idx = rowMeta.indexOfValue( valueName );
if ( idx < 0 ) {
throw new KettleValueException( "Unknown column '" + valueName + "'" );
}
ValueMetaInterface metaType = rowMeta.getValueMeta( idx );
// find by source va... | @Test
public void testEmptyValues() throws Exception {
RowMeta rowsMetaEmpty = new RowMeta();
rowsMetaEmpty.addValueMeta( new ValueMetaString( "str" ) );
rowsMetaEmpty.addValueMeta( new ValueMetaBoolean( "bool" ) );
rowsMetaEmpty.addValueMeta( new ValueMetaInteger( "int" ) );
rowsMetaEmpty.addVal... |
@Nonnull
public SerializedCheckpointException getSerializedCheckpointException() {
return serializedCheckpointException;
} | @Test
void testDeclineCheckpointWithUserExceptionCanBeDeserializedWithoutUserClass()
throws Exception {
final String className = "UserException";
final URLClassLoader userClassLoader =
ClassLoaderUtils.compileAndLoadJava(
TempDirUtils.newFolder(tem... |
public static byte[] serialize(Descriptors.Descriptor descriptor) {
byte[] schemaDataBytes;
try {
Map<String, FileDescriptorProto> fileDescriptorProtoCache = new HashMap<>();
//recursively cache all FileDescriptorProto
serializeFileDescriptor(descriptor.getFile(), fil... | @Test
public static void testSerialize() {
byte[] data = ProtobufNativeSchemaUtils.serialize(org.apache.pulsar.client.schema.proto.Test.TestMessage.getDescriptor());
Descriptors.Descriptor descriptor = ProtobufNativeSchemaUtils.deserialize(data);
Assert.assertNotNull(descriptor);
A... |
@Override
public boolean trySetCount(long count) {
return get(trySetCountAsync(count));
} | @Test
public void testTrySetCount() throws Exception {
RCountDownLatch latch = redisson.getCountDownLatch("latch");
assertThat(latch.trySetCount(1)).isTrue();
assertThat(latch.trySetCount(2)).isFalse();
} |
public static <T> T[] getBeans(Class<T> interfaceClass) {
Object object = serviceMap.get(interfaceClass.getName());
if(object == null) return null;
if(object instanceof Object[]) {
return (T[])object;
} else {
Object array = Array.newInstance(interfaceClass, 1);
... | @Test
@Ignore
public void testMultipleWithProperties() {
J[] j = SingletonServiceFactory.getBeans(J.class);
Arrays.stream(j).forEach(o -> logger.debug(o.getJack()));
K[] k = SingletonServiceFactory.getBeans(K.class);
Arrays.stream(k).forEach(o -> logger.debug(o.getKing()));
... |
public static MemberVersion of(int major, int minor, int patch) {
if (major == 0 && minor == 0 && patch == 0) {
return MemberVersion.UNKNOWN;
} else {
return new MemberVersion(major, minor, patch);
}
} | @Test
public void testVersionOf_whenVersionStringIsRelease() {
MemberVersion expected = MemberVersion.of(3, 8, 2);
assertEquals(expected, MemberVersion.of(VERSION_3_8_2_STRING));
} |
@Override
public Optional<FileHashesDto> getDbFile(Component component) {
checkState(previousFileHashesByUuid != null, "Repository not initialized");
return Optional.ofNullable(previousFileHashesByUuid.get(component.getUuid()));
} | @Test
public void fail_if_not_set() {
assertThatThrownBy(() -> previousFileHashesRepository.getDbFile(mock(Component.class))).isInstanceOf(IllegalStateException.class);
} |
public void refer(OperationProgress other) {
// ensure the integrity and avoid dead lock.
List<OperationStep> steps;
List<Long> startTimes;
synchronized (other) {
steps = other._steps;
startTimes = other._startTimes;
}
synchronized (this) {
ensureMutable();
this._steps = ... | @Test
public void testRefer() {
OperationProgress progress1 = new OperationProgress();
progress1.addStep(new Pending());
OperationProgress progress2 = new OperationProgress();
progress2.addStep(new WaitingForClusterModel());
assertThat(progress1.progress().get(0), instanceOf(Pending.class));
... |
public MetricsBuilder enableThreadPool(Boolean enableThreadPool) {
this.enableThreadpool = enableThreadPool;
return getThis();
} | @Test
void enableThreadPool() {
MetricsBuilder builder = MetricsBuilder.newBuilder();
builder.enableThreadPool(false);
Assertions.assertFalse(builder.build().getEnableThreadpool());
} |
public int findSubscriptionDataCount(final String group) {
ConsumerGroupInfo consumerGroupInfo = this.getConsumerGroupInfo(group);
if (consumerGroupInfo != null) {
return consumerGroupInfo.getSubscriptionTable().size();
}
return 0;
} | @Test
public void findSubscriptionDataCountTest() {
register();
final int count = consumerManager.findSubscriptionDataCount(GROUP);
assert count > 0;
} |
public AgentBootstrapperArgs parse(String... args) {
AgentBootstrapperArgs result = new AgentBootstrapperArgs();
try {
new JCommander(result).parse(args);
if (result.help) {
printUsageAndExit(0);
}
return result;
} catch (Paramete... | @Test
public void shouldRaiseExceptionWhenSSLPrivateKeyPassphraseFileIsNotPresent() {
assertThatCode(() -> agentCLI.parse("-serverUrl", "http://example.com/go", "-sslPrivateKeyPassphraseFile", UUID.randomUUID().toString()))
.isInstanceOf(ExitException.class)
.satisfies(o -> a... |
@Override
public Optional<ServiceInstance> findById(final String id) {
return jdbcRepository.getDslContextWrapper().transactionResult(
configuration -> findById(id, configuration, false)
);
} | @Test
protected void shouldFindByServiceId() {
// Given
AbstractJdbcServiceInstanceRepositoryTest.Fixtures.all().forEach(repository::save);
String uuid = AbstractJdbcServiceInstanceRepositoryTest.Fixtures.EmptyServiceInstance.id();
// When
Optional<ServiceInstance> result = ... |
public void processIssuesByBatch(DbSession dbSession, Set<String> issueKeysSnapshot, Consumer<List<IssueDto>> listConsumer, Predicate<? super IssueDto> filter) {
boolean hasMoreIssues = !issueKeysSnapshot.isEmpty();
long offset = 0;
List<IssueDto> issueDtos = new ArrayList<>();
while (hasMoreIssues) {... | @Test
public void processIssuesByBatch_correctly_processes_all_issues_regardless_of_creation_timestamp() {
var pullActionIssuesRetriever = new PullActionIssuesRetriever(dbClient, queryParams);
List<IssueDto> issuesWithSameCreationTimestamp = IntStream.rangeClosed(1, 100).mapToObj(i -> new IssueDto()
.se... |
public void command(String primaryCommand, SecureConfig config, String... allArguments) {
terminal.writeLine("");
final Optional<CommandLine> commandParseResult;
try {
commandParseResult = Command.parse(primaryCommand, allArguments);
} catch (InvalidCommandException e) {
... | @Test
public void testHelpAdd() {
cli.command("add", null, "--help");
assertThat(terminal.out).containsIgnoringCase("Add secrets to the keystore");
} |
@Override
public void onStreamRequest(StreamRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
disruptRequest(req, requestContext, wireAttrs, nextFilter);
} | @Test
public void testStreamTimeoutDisrupt() throws Exception
{
final RequestContext requestContext = new RequestContext();
requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.timeout());
final DisruptFilter filter = new DisruptFilter(_scheduler, _executor, REQUEST_TIMEOUT, _clock);
fi... |
static EndTransactionMarker deserializeValue(ControlRecordType type, ByteBuffer value) {
ensureTransactionMarkerControlType(type);
if (value.remaining() < CURRENT_END_TXN_MARKER_VALUE_SIZE)
throw new InvalidRecordException("Invalid value size found for end transaction marker. Must have " +
... | @Test
public void testCannotDeserializeUnknownControlType() {
assertThrows(IllegalArgumentException.class,
() -> EndTransactionMarker.deserializeValue(ControlRecordType.UNKNOWN, ByteBuffer.wrap(new byte[0])));
} |
public double[][] test(DataFrame data) {
DataFrame x = formula.x(data);
int n = x.nrow();
int ntrees = models.length;
double[][] prediction = new double[ntrees][n];
for (int j = 0; j < n; j++) {
Tuple xj = x.get(j);
double base = 0;
for (int ... | @Test
public void testBank32nh() {
test("bank32nh", Bank32nh.formula, Bank32nh.data, 0.0978);
} |
@Bean
public ShenyuPlugin sofaPlugin(final ObjectProvider<SofaParamResolveService> sofaParamResolveService) {
return new SofaPlugin(new SofaProxyService(sofaParamResolveService.getIfAvailable()));
} | @Test
public void testSofaPlugin() {
applicationContextRunner.run(context -> {
ShenyuPlugin plugin = context.getBean("sofaPlugin", ShenyuPlugin.class);
assertNotNull(plugin);
assertThat(plugin.named()).isEqualTo(PluginEnum.SOFA.getName());
}
... |
public String toString() {
// ensure minimum precision of 3 decimal places by using our own 3-decimal-place formatter when we have no nanos.
final DateTimeFormatter formatter = (instant.getNano() == 0 ? ISO_INSTANT_MILLIS : DateTimeFormatter.ISO_INSTANT);
return formatter.format(instant);
} | @Test
public void testParsingDateWithOffset() throws Exception {
final Timestamp t = new Timestamp("2014-09-23-08:00", OFFSET_CLOCK, LOCALE);
assertEquals("2014-09-23T08:00:00.000Z", t.toString());
} |
public static Statement sanitize(
final Statement node,
final MetaStore metaStore) {
return sanitize(node, metaStore, true);
} | @Test
public void shouldThrowIfInsertIntoSourceWithHeader() {
// Given:
final Statement stmt = givenQuery("INSERT INTO TEST1 SELECT * FROM TEST0;");
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> AstSanitizer.sanitize(stmt, META_STORE)
);
// Then:
a... |
@Override
public void open() throws Exception {
windowSerializer = windowAssigner.getWindowSerializer(new ExecutionConfig());
internalTimerService = getInternalTimerService("window-timers", windowSerializer, this);
// The structure is: [type]|[normal record]|[timestamp]|[current watermark]|... | @Test
void testFinishBundleTriggeredByTime() throws Exception {
Configuration conf = new Configuration();
conf.set(PythonOptions.MAX_BUNDLE_SIZE, 10);
conf.set(PythonOptions.MAX_BUNDLE_TIME_MILLS, 1000L);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness = getTestHarnes... |
public void deleteFavorite(long favoriteId) {
Favorite favorite = favoriteRepository.findById(favoriteId).orElse(null);
checkUserOperatePermission(favorite);
favoriteRepository.delete(favorite);
} | @Test
@Sql(scripts = "/sql/favorites/favorites.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testDeleteFavorite() {
long legalFavoriteId = 21L;
favoriteService.deleteFavorite(legalFavorite... |
public Type getType() {
return this.type;
} | @Test
public void testGetType() {
AppPermission appPermission = new AppPermission(Type.APP_WRITE);
assertEquals(Type.APP_WRITE, appPermission.getType());
} |
@Override
public List<String> getChildren(String path) {
try {
return client.getChildren().forPath(path);
} catch (NoNodeException e) {
return null;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
} | @Test
void testChildrenPath() {
String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers";
curatorClient.create(path, false, true);
curatorClient.create(path + "/provider1", false, true);
curatorClient.create(path + "/provider2", false, true);
List<String> children ... |
@Override
public void configure(Map<String, ?> configs) {
super.configure(configs);
configureSamplingInterval(configs);
configurePrometheusAdapter(configs);
configureQueryMap(configs);
} | @Test(expected = ConfigException.class)
public void testConfigureWithNoPrometheusEndpointFails() throws Exception {
Map<String, Object> config = new HashMap<>();
addCapacityConfig(config);
_prometheusMetricSampler.configure(config);
} |
@Override
protected KafkaLogCollectClient getLogConsumeClient() {
return LoggingKafkaPluginDataHandler.getKafkaLogCollectClient();
} | @Test
public void testGetLogConsumeClient() {
LogConsumeClient logConsumeClient = new KafkaLogCollector().getLogConsumeClient();
Assertions.assertEquals(KafkaLogCollectClient.class, logConsumeClient.getClass());
} |
@PostMapping(
path = "/admin/extension/{namespaceName}/{extensionName}/delete",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<ResultJson> deleteExtension(@PathVariable String namespaceName,
@PathVariable String extension... | @Test
public void testDeleteExtension() throws Exception {
mockAdminUser();
mockExtension(2, 0, 0);
mockMvc.perform(post("/admin/extension/{namespace}/{extension}/delete", "foobar", "baz")
.with(user("admin_user").authorities(new SimpleGrantedAuthority(("ROLE_ADMIN"))))
... |
@Override
public PackageConfiguration responseMessageForPackageConfiguration(String responseBody) {
try {
PackageConfiguration packageConfiguration = new PackageConfiguration();
Map<String, Map> configurations;
try {
configurations = parseResponseToMap(res... | @Test
public void shouldBuildPackageConfigurationFromResponseBody() throws Exception {
String responseBody = "{" +
"\"key-one\":{}," +
"\"key-two\":{\"default-value\":\"two\",\"part-of-identity\":true,\"secure\":true,\"required\":true,\"display-name\":\"display-two\",\"displa... |
@Override
public boolean isGeneric() {
return generic;
} | @Test
void isGeneric() {
Assertions.assertFalse(method.isGeneric());
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void setStickerPositionInSet() {
GetStickerSetResponse setResponse = bot.execute(new GetStickerSet(stickerSet));
Sticker sticker = setResponse.stickerSet().stickers()[0];
BaseResponse response = bot.execute(new SetStickerPositionInSet(sticker.fileId(), 0));
assertTrue(r... |
@Override
public int size() {
return contents.size();
} | @Test
public void testGetSetByType3() throws HCatException {
HCatRecord inpRec = getHCat13TypesRecord();
HCatRecord newRec = new DefaultHCatRecord(inpRec.size());
HCatSchema hsch = HCatSchemaUtils.getHCatSchema(
"a:decimal(5,2),b:char(10),c:varchar(20),d:date,e:timestamp");
newRec.setDecim... |
public static void updateKeyForBlobStore(Map<String, Object> conf, BlobStore blobStore, CuratorFramework zkClient, String key,
NimbusInfo nimbusDetails) {
try {
// Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForB... | @Test
public void testUpdateKeyForBlobStore_nullNimbusInfo() {
BlobStoreUtils.updateKeyForBlobStore(conf, blobStore, zkClientBuilder.build(), KEY, null);
zkClientBuilder.verifyExists(false);
zkClientBuilder.verifyGetChildren(false);
verify(nimbusDetails, never()).getHost();
... |
public ValidationResult validateMessagesAndAssignOffsets(PrimitiveRef.LongRef offsetCounter,
MetricsRecorder metricsRecorder,
BufferSupplier bufferSupplier) {
if (sourceCompressionType == Co... | @Test
public void testControlRecordsNotCompressed() {
long offset = 1234567;
EndTransactionMarker endTxnMarker = new EndTransactionMarker(ControlRecordType.COMMIT, 0);
MemoryRecords records = MemoryRecords.withEndTransactionMarker(23423L, (short) 5, endTxnMarker);
LogValidator.Valida... |
public Subscription addSubscriber(Function<? super E, Subscription> subscriber) {
Objects.requireNonNull(subscriber);
subscribers.add(subscriber);
List<E> keys = new ArrayList<>(map.keySet());
keys.forEach(key -> {
List<Subscription> otherSubs = map.get(key);
Sub... | @Test
public void adding_subscriber_and_removing_it_will_not_throw_exception() {
SubscribeableContentsObsSet<Integer> set = new SubscribeableContentsObsSet<>();
Subscription removeSubscriber = set.addSubscriber(i -> Subscription.EMPTY);
removeSubscriber.unsubscribe();
} |
public void stop() {
if (shutdownExecutorOnStop) {
executor.shutdown(); // Disable new tasks from being submitted
}
try {
report(); // Report metrics one last time
} catch (Exception e) {
LOG.warn("Final reporting of metrics failed.", e);
}
... | @Test
public void shouldNotFailOnStopIfReporterWasNotStared() {
for (ScheduledReporter reporter : reporters) {
reporter.stop();
}
} |
public void setDefault() {
replaceAllByValue = null;
replaceAllMask = null;
selectFields = false;
selectValuesType = false;
setEmptyStringAll = false;
int nrfields = 0;
int nrtypes = 0;
allocate( nrtypes, nrfields );
/*
* Code will never execute. nrfields and nrtypes
* are... | @Test
public void testSetDefault() throws Exception {
IfNullMeta inm = new IfNullMeta();
inm.setDefault();
assertTrue( ( inm.getValueTypes() != null ) && ( inm.getValueTypes().length == 0 ) );
assertTrue( ( inm.getFields() != null ) && ( inm.getFields().length == 0 ) );
assertFalse( inm.isSelectFi... |
public RemotingDesc getRemotingBeanDesc(Object bean) {
return remotingServiceMap.get(bean);
} | @Test
public void testGetRemotingDeanDescFail() {
SimpleBean simpleBean = new SimpleBean();
assertNull(remotingParser.getRemotingBeanDesc(simpleBean));
} |
public boolean finish() {
return finish(false);
} | @Test
@Timeout(value = 3000, unit = TimeUnit.MILLISECONDS)
public void testHandlerAddedExecutedInEventLoop() throws Throwable {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
final ChannelHandler handler = ne... |
public String render(String inline, Map<String, Object> variables) throws IllegalVariableEvaluationException {
return this.render(inline, variables, this.variableConfiguration.getRecursiveRendering());
} | @Test
void shouldRenderUsingAlternativeRendering() throws IllegalVariableEvaluationException {
TestVariableRenderer renderer = new TestVariableRenderer(applicationContext, variableConfiguration);
String render = renderer.render("{{ dummy }}", Map.of());
Assertions.assertEquals("result", rend... |
public ContentInfo verify(ContentInfo signedMessage, Date date) {
final SignedData signedData = SignedData.getInstance(signedMessage.getContent());
final X509Certificate cert = certificate(signedData);
certificateVerifier.verify(cert, date);
final X500Name name = X500Name.getInstance(ce... | @Test
public void shouldThrowExceptionIfSignatureIsIncorrect() throws Exception {
final byte[] data = fixture();
data[2183]++;
final ContentInfo signedMessage = ContentInfo.getInstance(data);
thrown.expect(VerificationException.class);
thrown.expectMessage("Could not verify ... |
@Override
public Iterable<Token> tokenize(String input, Language language, StemMode stemMode, boolean removeAccents) {
if (input.isEmpty()) return List.of();
List<Token> tokens = textToTokens(input, analyzerFactory.getAnalyzer(language, stemMode, removeAccents));
log.log(Level.FINEST, () ->... | @Test
public void testTokenizer() {
String text = "This is my Text";
Iterable<Token> tokens = luceneLinguistics().getTokenizer()
.tokenize(text, Language.ENGLISH, StemMode.ALL, true);
assertEquals(List.of("my", "text"), tokenStrings(tokens));
} |
public static String getCertFingerPrint(Certificate cert) {
byte [] digest = null;
try {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance("SHA-1");
digest = md.digest(encCertInfo);
} catch (Exception e) {
logger... | @Test
public void testGetCertFingerPrintBob() throws Exception {
X509Certificate cert = null;
try (InputStream is = Config.getInstance().getInputStreamFromFile("bob.crt")){
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) cf.generateCe... |
Flux<DataEntityList> export(KafkaCluster cluster) {
String clusterOddrn = Oddrn.clusterOddrn(cluster);
Statistics stats = statisticsCache.get(cluster);
return Flux.fromIterable(stats.getTopicDescriptions().keySet())
.filter(topicFilter)
.flatMap(topic -> createTopicDataEntity(cluster, topic,... | @Test
void doesExportTopicData() {
when(schemaRegistryClientMock.getSubjectVersion("testTopic-value", "latest", false))
.thenReturn(Mono.just(
new SchemaSubject()
.schema("\"string\"")
.schemaType(SchemaType.AVRO)
));
when(schemaRegistryClientMock.g... |
@Operation(summary = "grantUDFFunc", description = "GRANT_UDF_FUNC_NOTES")
@Parameters({
@Parameter(name = "userId", description = "USER_ID", required = true, schema = @Schema(implementation = int.class, example = "100")),
@Parameter(name = "udfIds", description = "UDF_IDS", required = true,... | @Test
public void testGrantUDFFunc() throws Exception {
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
paramsMap.add("userId", "32");
paramsMap.add("udfIds", "5");
MvcResult mvcResult = mockMvc.perform(post("/users/grant-udf-func")
.header(SES... |
public static List<String> loadAndModifyConfiguration(String[] args) throws FlinkException {
return ConfigurationParserUtils.loadAndModifyConfiguration(
filterCmdArgs(args, ModifiableClusterConfigurationParserFactory.options()),
BashJavaUtils.class.getSimpleName());
} | @TestTemplate
void testloadAndModifyConfigurationRemoveKeysMatched() throws Exception {
String key = "key";
String[] args = {
"--configDir",
confDir.toFile().getAbsolutePath(),
String.format("-D%s=value", key),
"--removeKey",
key
}... |
@CanIgnoreReturnValue
public final Ordered containsAtLeastEntriesIn(Multimap<?, ?> expectedMultimap) {
checkNotNull(expectedMultimap, "expectedMultimap");
checkNotNull(actual);
ListMultimap<?, ?> missing = difference(expectedMultimap, actual);
// TODO(kak): Possible enhancement: Include "[1 copy]" if... | @Test
public void containsAtLeastRespectsDuplicates() {
ImmutableListMultimap<Integer, String> actual =
ImmutableListMultimap.of(3, "one", 3, "two", 3, "one", 4, "five", 4, "five");
ImmutableListMultimap<Integer, String> expected =
ImmutableListMultimap.of(3, "two", 4, "five", 3, "one", 4, "fi... |
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
this.config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesNodeConfiguration.class);
this.keys = config.getKeys();
} | @Test
void givenMsg_whenOnMsg_thenVerifyOutput_SendAttributesDeletedNotification_NotifyDevice() throws Exception {
config.setSendAttributesDeletedNotification(true);
config.setNotifyDevice(true);
config.setScope(DataConstants.SHARED_SCOPE);
nodeConfiguration = new TbNodeConfiguration... |
public HoodieConfig() {
this.props = new TypedProperties();
} | @Test
public void testHoodieConfig() {
// Case 1: defaults and infer function are used
HoodieTestFakeConfig config1 = HoodieTestFakeConfig.newBuilder().build();
assertEquals("1", config1.getFakeString());
assertEquals(0, config1.getFakeInteger());
assertEquals("value3", config1.getFakeStringNoDefa... |
Schema getAvroCompatibleSchema() {
return avroCompatibleSchema;
} | @Test
public void shouldDropOptionalFromRootPrimitiveSchema() {
// Given:
final Schema schema = Schema.OPTIONAL_INT64_SCHEMA;
// When:
final AvroDataTranslator translator =
new AvroDataTranslator(schema, AvroProperties.DEFAULT_AVRO_SCHEMA_FULL_NAME);
// Then:
assertThat("Root require... |
@VisibleForTesting
void submit(long requestId, DispatchableSubPlan dispatchableSubPlan, long timeoutMs, Map<String, String> queryOptions)
throws Exception {
Deadline deadline = Deadline.after(timeoutMs, TimeUnit.MILLISECONDS);
// Serialize the stage plans in parallel
List<DispatchablePlanFragment> ... | @Test
public void testQueryDispatcherThrowsWhenQueryServerThrows() {
String sql = "SELECT * FROM a WHERE col1 = 'foo'";
QueryServer failingQueryServer = _queryServerMap.values().iterator().next();
Mockito.doThrow(new RuntimeException("foo")).when(failingQueryServer).submit(Mockito.any(), Mockito.any());
... |
@Override
public double variance() {
return (1 - p) / (p * p);
} | @Test
public void testVariance() {
System.out.println("variance");
ShiftedGeometricDistribution instance = new ShiftedGeometricDistribution(0.3);
instance.rand();
assertEquals(0.7/0.09, instance.variance(), 1E-7);
} |
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for eac... | @Test
public void testReplaceAclEntriesAccessMaskPreserved() throws AclException {
List<AclEntry> existing = new ImmutableList.Builder<AclEntry>()
.add(aclEntry(ACCESS, USER, ALL))
.add(aclEntry(ACCESS, USER, "bruce", READ))
.add(aclEntry(ACCESS, USER, "diana", READ_WRITE))
.add(aclEntry(A... |
public <T> T parse(String input, Class<T> cls) {
return readFlow(input, cls, type(cls));
} | @Test
void invalidProperty() {
ConstraintViolationException exception = assertThrows(
ConstraintViolationException.class,
() -> this.parse("flows/invalids/invalid-property.yaml")
);
assertThat(exception.getMessage(), is("Unrecognized field \"invalid\" (class io.kestr... |
public void onPeriodicEmit() {
updateCombinedWatermark();
} | @Test
void singleDeferredWatermarkAfterIdleness() {
TestingWatermarkOutput underlyingWatermarkOutput = createTestingWatermarkOutput();
WatermarkOutputMultiplexer multiplexer =
new WatermarkOutputMultiplexer(underlyingWatermarkOutput);
WatermarkOutput watermarkOutput = create... |
public static AggregationUnit create(final AggregationType type, final boolean isDistinct) {
switch (type) {
case MAX:
return new ComparableAggregationUnit(false);
case MIN:
return new ComparableAggregationUnit(true);
case SUM:
... | @Test
void assertCreateDistinctAverageAggregationUnit() {
assertThat(AggregationUnitFactory.create(AggregationType.AVG, true), instanceOf(DistinctAverageAggregationUnit.class));
} |
Map<Class, Object> getSerializers() {
return serializers;
} | @Test
public void testLoad_withParametrizedConstructor() {
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setClassName("com.hazelcast.internal.serialization.impl.TestSerializerHook$TestSerializerWithTypeConstructor");
serializerConfig.setTypeClassName("com.hazel... |
public static final String getLine( LogChannelInterface log, BufferedInputStreamReader reader, int formatNr,
StringBuilder line ) throws KettleFileException {
EncodingType type = EncodingType.guessEncodingType( reader.getEncoding() );
return getLine( log, reader, type, form... | @Test
public void getLineWithEnclosureTest() throws Exception {
String text = "\"firstLine\"\n\"secondLine\"";
StringBuilder linebuilder = new StringBuilder( "" );
InputStream is = new ByteArrayInputStream( text.getBytes() );
BufferedInputStreamReader isr = new BufferedInputStreamReader( new InputStre... |
@Override
public String toString() {
return "ByteArrayObjectDataInput{"
+ "size=" + size
+ ", pos=" + pos
+ ", mark=" + mark
+ '}';
} | @Test
public void testToString() {
assertNotNull(in.toString());
} |
public static void mergeParams(
Map<String, ParamDefinition> params,
Map<String, ParamDefinition> paramsToMerge,
MergeContext context) {
if (paramsToMerge == null) {
return;
}
Stream.concat(params.keySet().stream(), paramsToMerge.keySet().stream())
.forEach(
name ... | @Test
public void testMergeWithParamMismatchDefinedBySEL() throws JsonProcessingException {
Map<String, ParamDefinition> allParams =
parseParamDefMap("{'tomerge': {'type': 'STRING','expression': 'stringValue'}}");
Map<String, ParamDefinition> paramsToMerge =
parseParamDefMap(
"{'to... |
void storeEdits(byte[] inputData, long newStartTxn, long newEndTxn,
int newLayoutVersion) {
if (newStartTxn < 0 || newEndTxn < newStartTxn) {
Journal.LOG.error(String.format("Attempted to cache data of length %d " +
"with newStartTxn %d and newEndTxn %d",
inputData.length, newStartTx... | @Test
public void testCacheBelowCapacityRequestOnBoundary() throws Exception {
storeEdits(1, 5);
storeEdits(6, 20);
storeEdits(21, 30);
// First segment only
assertTxnCountAndContents(1, 3, 3);
// Second segment only
assertTxnCountAndContents(6, 10, 15);
// First and second segment
... |
@Override
public int hashCode() {
return Objects.hash(targetImage, imageDigest, imageId, tags, imagePushed);
} | @Test
public void testEquality_differentImageId() {
JibContainer container1 = new JibContainer(targetImage1, digest1, digest1, tags1, true);
JibContainer container2 = new JibContainer(targetImage1, digest1, digest2, tags1, true);
Assert.assertNotEquals(container1, container2);
Assert.assertNotEquals(... |
@VisibleForTesting
static Optional<String> buildGlueExpressionForSingleDomain(String columnName, Domain domain)
{
checkState(!domain.isAll());
ValueSet valueSet = domain.getValues();
if (!canConvertSqlTypeToStringForGlue(domain.getType())) {
return Optional.empty();
... | @Test
public void testBuildGlueExpressionDomainEqualsSingleValue()
{
Domain domain = Domain.singleValue(VarcharType.VARCHAR, utf8Slice("2020-01-01"));
Optional<String> foo = buildGlueExpressionForSingleDomain("foo", domain);
assertEquals(foo.get(), "((foo = '2020-01-01'))");
} |
@Override
public ProxyInvocationHandler parserInterfaceToProxy(Object target, String objectName) {
// eliminate the bean without two phase annotation.
Set<String> methodsToProxy = this.tccProxyTargetMethod(target);
if (methodsToProxy.isEmpty()) {
return null;
}
//... | @Test
public void testNestTcc_should_rollback() throws Exception {
TccActionImpl tccAction = new TccActionImpl();
TccAction tccActionProxy = ProxyUtil.createProxy(tccAction, "oldtccAction");
Assertions.assertNotNull(tccActionProxy);
NestTccActionImpl nestTccAction = new NestTccAct... |
@VisibleForTesting
public void validateTemplateParams(NotifyTemplateDO template, Map<String, Object> templateParams) {
template.getParams().forEach(key -> {
Object value = templateParams.get(key);
if (value == null) {
throw exception(NOTIFY_SEND_TEMPLATE_PARAM_MISS, k... | @Test
public void testCheckTemplateParams_paramMiss() {
// 准备参数
NotifyTemplateDO template = randomPojo(NotifyTemplateDO.class,
o -> o.setParams(Lists.newArrayList("code")));
Map<String, Object> templateParams = new HashMap<>();
// mock 方法
// 调用,并断言异常
... |
@Override
protected void write(final PostgreSQLPacketPayload payload) {
payload.writeInt2(columnDescriptions.size());
for (PostgreSQLColumnDescription each : columnDescriptions) {
payload.writeStringNul(each.getColumnName());
payload.writeInt4(each.getTableOID());
... | @Test
void assertWrite() {
PostgreSQLColumnDescription description = new PostgreSQLColumnDescription("name", 1, Types.VARCHAR, 4, null);
PostgreSQLRowDescriptionPacket packet = new PostgreSQLRowDescriptionPacket(Collections.singleton(description));
packet.write(payload);
verify(paylo... |
static Object parseCell(String cell, Schema.Field field) {
Schema.FieldType fieldType = field.getType();
try {
switch (fieldType.getTypeName()) {
case STRING:
return cell;
case INT16:
return Short.parseShort(cell);
case INT32:
return Integer.parseInt(c... | @Test
public void givenValidBooleanCell_parses() {
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry("false", false);
Schema schema =
Schema.builder().addBooleanField("a_boolean").addStringField("a_string").build();
assertEquals(
cellToExpectedValue.getValue(),
CsvIOParseHe... |
public ClientTelemetrySender telemetrySender() {
return clientTelemetrySender;
} | @Test
public void testHandleResponsePushTelemetryTerminating() {
ClientTelemetryReporter.DefaultClientTelemetrySender telemetrySender = (ClientTelemetryReporter.DefaultClientTelemetrySender) clientTelemetryReporter.telemetrySender();
telemetrySender.updateSubscriptionResult(subscription, time.millis... |
public static void updateDetailMessage(
@Nullable Throwable root, @Nullable Function<Throwable, String> throwableToMessage) {
if (throwableToMessage == null) {
return;
}
Throwable it = root;
while (it != null) {
String newMessage = throwableToMessage.... | @Test
void testUpdateDetailMessageOfRelevantThrowableAsCause() {
Throwable oomCause =
new IllegalArgumentException("another message deep down in the cause tree");
Throwable oom = new OutOfMemoryError("old message").initCause(oomCause);
oom.setStackTrace(
new ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.