focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public Collection<DatabasePacket> execute() {
SQLParserEngine sqlParserEngine = createShardingSphereSQLParserEngine(connectionSession.getUsedDatabaseName());
String sql = packet.getSQL();
SQLStatement sqlStatement = sqlParserEngine.parse(sql, true);
String escapedSql = esca... | @Test
void assertExecuteWithNonOrderedParameterizedSQL() throws ReflectiveOperationException {
final String rawSQL = "update t_test set name=$2 where id=$1";
final String expectedSQL = "update t_test set name=? where id=?";
final String statementId = "S_2";
when(parsePacket.getSQL())... |
protected static KeyPair signWithRsa() {
KeyPair keyPair = null;
try {
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
kpGenerator.initialize(4096);
java.security.KeyPair keypair = kpGenerator.generateKeyPair();
PublicKey publicKey = ke... | @Test
void testSignWithRsa() {
DubboCertManager.KeyPair keyPair = DubboCertManager.signWithRsa();
Assertions.assertNotNull(keyPair);
Assertions.assertNotNull(keyPair.getPrivateKey());
Assertions.assertNotNull(keyPair.getPublicKey());
Assertions.assertNotNull(keyPair.getSigner... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.NOTIFY_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteNotifyTemplate(Long id) {
// 校验存在
validateNotifyTemplateExists(id);
// 删除
notifyTemplateMapper.deleteById(id);
} | @Test
public void testDeleteNotifyTemplate_success() {
// mock 数据
NotifyTemplateDO dbNotifyTemplate = randomPojo(NotifyTemplateDO.class);
notifyTemplateMapper.insert(dbNotifyTemplate);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbNotifyTemplate.getId();
// 调用
noti... |
public static String getS3EncryptionContext(String bucket, Configuration conf)
throws IOException {
// look up the per-bucket value of the encryption context
String encryptionContext = S3AUtils.lookupBucketSecret(bucket, conf, S3_ENCRYPTION_CONTEXT);
if (encryptionContext == null) {
// look up t... | @Test
public void testGetS3EncryptionContextPerBucket() throws IOException {
Configuration configuration = new Configuration(false);
configuration.set("fs.s3a.bucket.bucket1.encryption.context", BUCKET_CONTEXT);
configuration.set(S3_ENCRYPTION_CONTEXT, GLOBAL_CONTEXT);
final String result = S3AEncrypt... |
static void parseServerIpAndPort(MysqlConnection connection, Span span) {
try {
URI url = URI.create(connection.getURL().substring(5)); // strip "jdbc:"
String remoteServiceName = connection.getProperties().getProperty("zipkinServiceName");
if (remoteServiceName == null || "".equals(remoteServiceN... | @Test void parseServerIpAndPort_serviceNameFromDatabaseName() throws SQLException {
setupAndReturnPropertiesForHost("1.2.3.4");
when(connection.getCatalog()).thenReturn("mydatabase");
TracingQueryInterceptor.parseServerIpAndPort(connection, span);
verify(span).remoteServiceName("mysql-mydatabase");
... |
@Override
public void writeAttribute(String prefix, String namespaceURI, String localName, String value)
throws XMLStreamException {
String filteredValue = nonXmlCharFilterer.filter(value);
writer.writeAttribute(prefix, namespaceURI, localName, filteredValue);
} | @Test
public void testWriteAttribute2Args() throws XMLStreamException {
filteringXmlStreamWriter.writeAttribute("localName", "value");
verify(xmlStreamWriterMock).writeAttribute("localName", "filteredValue");
} |
@Override
public double cdf(double x) {
if (x <= 0) {
return 0.0;
} else if (x >= 1) {
return 1.0;
} else {
return Beta.regularizedIncompleteBetaFunction(alpha, beta, x);
}
} | @Test
public void testCdf() {
System.out.println("cdf");
BetaDistribution instance = new BetaDistribution(2, 5);
instance.rand();
assertEquals(0, instance.cdf(-0.1), 1E-5);
assertEquals(0, instance.cdf(0.0), 1E-5);
assertEquals(0.114265, instance.cdf(0.1), 1E-5);
... |
@Override
public List<Intent> compile(PointToPointIntent intent, List<Intent> installable) {
log.trace("compiling {} {}", intent, installable);
ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint();
ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint();
... | @Test
public void testSuggestedPathNotAvailable() {
String[] suggestedPathHops = {S1, S3, S8};
String[] shortestPath = {S1, S2, S8};
List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
PointToPointIntent intent = makeIntentSuggestedPath(new ConnectPoint(DI... |
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("name", name())
.add("monitorsrcports", monitorSrcPorts())
.add("monitordstports", monitorDstPorts())
.add("monitorvlans", monitorVlans())
.add("m... | @Test
public void testToString() {
String result = md1.toString();
assertThat(result, notNullValue());
assertThat(result, containsString("name=" + NAME_1.toString()));
assertThat(result, containsString("monitorsrcports=" + MONITOR_SRC_PORTS_1.toString()));
assertThat(result, ... |
@Override
public void checkBeforeUpdate(final CreateEncryptRuleStatement sqlStatement) {
if (!sqlStatement.isIfNotExists()) {
checkDuplicateRuleNames(sqlStatement);
}
checkColumnNames(sqlStatement);
checkAlgorithmTypes(sqlStatement);
checkToBeCreatedEncryptors(sql... | @Test
void assertCheckSQLStatementWithDuplicateEncryptRule() {
EncryptRule rule = mock(EncryptRule.class);
when(rule.getAllTableNames()).thenReturn(Arrays.asList("t_user", "t_order"));
executor.setRule(rule);
assertThrows(DuplicateRuleException.class, () -> executor.checkBeforeUpdate... |
public static void verifyIncrementPubContent(String content) {
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("The content for publishing or deleting cannot be null!");
}
for (int i = 0; i < content.length(); i++) {
char c = content.cha... | @Test
void testVerifyIncrementPubContent() {
String content = "";
try {
ContentUtils.verifyIncrementPubContent(content);
fail();
} catch (IllegalArgumentException e) {
assertNotNull(e.toString());
}
content = "\r";
... |
public static KsqlWindowExpression parseWindowExpression(final String expressionText) {
final ParserRuleContext parseTree = GrammarParseUtil.getParseTree(
expressionText,
SqlBaseParser::windowExpression
);
final WindowExpression windowExpression =
new AstBuilder(TypeRegistry.EMPTY).b... | @Test
public void shouldParseWindowExpression() {
// When:
final KsqlWindowExpression parsed = ExpressionParser.parseWindowExpression(
"TUMBLING (SIZE 1 DAYS)"
);
// Then:
assertThat(
parsed,
equalTo(new TumblingWindowExpression(
parsed.getLocation(),
... |
public RingbufferStoreConfig setFactoryClassName(@Nonnull String factoryClassName) {
this.factoryClassName = checkHasText(factoryClassName, "Ringbuffer store factory class name must contain text");
this.factoryImplementation = null;
return this;
} | @Test
public void setFactoryClassName() {
config.setFactoryClassName("myFactoryClassName");
assertEquals("myFactoryClassName", config.getFactoryClassName());
} |
@Override
public void changeLimitForPeriod(final int limitForPeriod) {
RateLimiterConfig newConfig = RateLimiterConfig.from(state.get().config)
.limitForPeriod(limitForPeriod)
.build();
state.updateAndGet(currentState -> new State(
newConfig, currentState.activeCy... | @Test
public void changeLimitForPeriod() throws Exception {
setup(Duration.ZERO);
RateLimiterConfig rateLimiterConfig = rateLimiter.getRateLimiterConfig();
then(rateLimiterConfig.getTimeoutDuration()).isEqualTo(Duration.ZERO);
then(rateLimiterConfig.getLimitForPeriod()).isEqualTo(PE... |
public static Write write() {
return new Write(null /* Configuration */, "");
} | @Test
public void testWriteBuildsCorrectly() {
HBaseIO.Write write = HBaseIO.write().withConfiguration(conf).withTableId("table");
assertEquals("table", write.getTableId());
assertNotNull("configuration", write.getConfiguration());
} |
DefaultHttp2FrameStream newStream() {
return new DefaultHttp2FrameStream();
} | @Test
public void multipleNewOutboundStreamsShouldBeBuffered() throws Exception {
// We use a limit of 1 and then increase it step by step.
setUp(Http2FrameCodecBuilder.forServer().encoderEnforceMaxConcurrentStreams(true),
new Http2Settings().maxConcurrentStreams(1));
Http2F... |
@Override
public CompletableFuture<Boolean> triggerCheckpointAsync(
CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) {
if (!isExternallyInducedSource()) {
return triggerCheckpointNowAsync(checkpointMetaData, checkpointOptions);
}
Completable... | @Test
void testTriggeringStopWithSavepointWithDrain() throws Exception {
SourceOperatorFactory<Integer> sourceOperatorFactory =
new SourceOperatorFactory<>(
new MockSource(Boundedness.CONTINUOUS_UNBOUNDED, 2),
WatermarkStrategy.noWatermarks());... |
public static String hex(byte[] bytes) {
return StringUtils.encodeHex(bytes(bytes));
} | @Test
public void testHash() {
// Test null
// @TODO - should the StringUtils.hash(String) method be fixed to handle null input?
try {
SHA1.hex((String) null);
fail();
}
catch (NullPointerException npe) {
assertTrue(true);
}
... |
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
if (listClass != null || inner != null) {
log.error("Could not configure ListDeserializer as some parameters were already set -- listClass: {}, inner: {}", listClass, inner);
throw new ConfigException("List dese... | @Test
public void testListKeyDeserializerShouldThrowConfigExceptionDueAlreadyInitialized() {
props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_TYPE_CLASS, ArrayList.class);
props.put(CommonClientConfigs.DEFAULT_LIST_KEY_SERDE_INNER_CLASS, Serdes.StringSerde.class);
final ListDeserializer<... |
public CacheConfig<K, V> setBackupCount(int backupCount) {
this.backupCount = checkBackupCount(backupCount, asyncBackupCount);
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setBackupCount_whenItsNegative() {
CacheConfig config = new CacheConfig();
config.setBackupCount(-1);
} |
@Override
public TImmutablePartitionResult updateImmutablePartition(TImmutablePartitionRequest request) throws TException {
LOG.info("Receive update immutable partition: {}", request);
TImmutablePartitionResult result;
try {
result = updateImmutablePartitionInternal(request);
... | @Test
public void testUpdateImmutablePartitionException() throws TException {
new MockUp<FrontendServiceImpl>() {
@Mock
public synchronized TImmutablePartitionResult updateImmutablePartitionInternal(
TImmutablePartitionRequest request) {
throw new ... |
@Override
public RefreshQueuesResponse refreshQueues(RefreshQueuesRequest request)
throws StandbyException, YarnException, IOException {
// parameter verification.
if (request == null) {
routerMetrics.incrRefreshQueuesFailedRetrieved();
RouterServerUtil.logAndThrowException("Missing Refresh... | @Test
public void testRefreshQueues() throws Exception {
// We will test 2 cases:
// case 1, request is null.
// case 2, normal request.
// If the request is null, a Missing RefreshQueues request exception will be thrown.
// null request.
LambdaTestUtils.intercept(YarnException.class, "Missin... |
public static boolean isServiceDiscoveryURL(URL url) {
return hasServiceDiscoveryRegistryProtocol(url) || hasServiceDiscoveryRegistryTypeKey(url);
} | @Test
public void testIsServiceDiscoveryURL() {
String address1 = "http://example.com";
URL url1 = UrlUtils.parseURL(address1, null);
String address2 = "service-discovery-registry://example.com";
URL url2 = UrlUtils.parseURL(address2, null);
String address3 = "SERVICE-DISCOVE... |
public ServiceBuilder<U> providerIds(String providerIds) {
this.providerIds = providerIds;
return getThis();
} | @Test
void providerIds() {
ServiceBuilder builder = new ServiceBuilder();
builder.providerIds("providerIds");
Assertions.assertEquals("providerIds", builder.build().getProviderIds());
} |
@Override
public ListenableFuture<BufferResult> get(OutputBufferId outputBufferId, long startingSequenceId, DataSize maxSize)
{
requireNonNull(outputBufferId, "outputBufferId is null");
checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte");
return partitions.get(output... | @Test
public void testDuplicateRequests()
{
PartitionedOutputBuffer buffer = createPartitionedBuffer(
createInitialEmptyOutputBuffers(PARTITIONED)
.withBuffer(FIRST, 0)
.withNoMoreBufferIds(),
sizeOfPages(10));
// a... |
public static long timeUnitToMill(String timeStrWithUnit) {
// If `timeStrWithUnit` doesn't include time unit,
// `Duration.parse` would fail to parse and throw Exception.
if (timeStrWithUnit.endsWith("ms")) {
return Long.parseLong(timeStrWithUnit.substring(0, timeStrWithUnit.length() - 2));
}
... | @Test
void testTimeUnitToMill() {
assertEquals(10L, ZeppelinConfiguration.timeUnitToMill("10ms"));
assertEquals(2000L, ZeppelinConfiguration.timeUnitToMill("2s"));
assertEquals(60000L, ZeppelinConfiguration.timeUnitToMill("1m"));
assertEquals(3600000L, ZeppelinConfiguration.timeUnitToMill("1h"));
} |
@Override
public void emit(String emitKey, List<Metadata> metadataList, ParseContext parseContext) throws IOException, TikaEmitterException {
if (metadataList == null || metadataList.isEmpty()) {
throw new TikaEmitterException("metadata list must not be null or of size 0");
}
//T... | @Test
public void testBasic() throws Exception {
EmitterManager emitterManager = EmitterManager.load(getConfig("tika-config-az-blob.xml"));
Emitter emitter = emitterManager.getEmitter("az-blob");
List<Metadata> metadataList = new ArrayList<>();
Metadata m = new Metadata();
m.... |
public static String getClassName(Schema schema) {
String namespace = schema.getNamespace();
String name = schema.getName();
if (namespace == null || "".equals(namespace))
return name;
String dot = namespace.endsWith("$") ? "" : "."; // back-compatibly handle $
return mangle(namespace) + dot +... | @Test
void classNameContainingReservedWords() {
final Schema schema = Schema.createRecord("AnyName", null, "db.public.table", false);
assertEquals("db.public$.table.AnyName", SpecificData.getClassName(schema));
} |
public static void raftReadFromLeader() {
RAFT_FROM_LEADER.record(1);
} | @Test
void testRaftReadFromLeader() {
MetricsMonitor.raftReadFromLeader();
assertEquals(1D, MetricsMonitor.getRaftFromLeader().totalAmount(), 0.01);
} |
@Override
public String format(final Schema schema) {
final String converted = SchemaWalker.visit(schema, new Converter()) + typePostFix(schema);
return options.contains(Option.AS_COLUMN_LIST)
? stripTopLevelStruct(converted)
: converted;
} | @Test
public void shouldFormatOptionalBytes() {
assertThat(DEFAULT.format(Schema.OPTIONAL_BYTES_SCHEMA), is("BYTES"));
assertThat(STRICT.format(Schema.OPTIONAL_BYTES_SCHEMA), is("BYTES"));
} |
@Override
public void getConfig(StorServerConfig.Builder builder) {
super.getConfig(builder);
provider.getConfig(builder);
} | @Test
void testCommunicationManagerDefaults() {
StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder();
DistributorCluster cluster =
parse("<cluster id=\"storage\">" +
" <redundancy>3</redundancy>" +
... |
public static String getDecodeQuery(final String uri) {
try {
URI u = new URI(uri);
String query = URISupport.prepareQuery(u);
String uriWithoutQuery = URISupport.stripQuery(uri);
if (query == null) {
return uriWithoutQuery;
} else {
... | @Test
public void testGetDecodeQuery() throws Exception {
String out = URISupport.normalizeUri("smtp://localhost?username=davsclaus&password=secret");
String enc = UnsafeUriCharactersEncoder.encode(out);
String dec = URISupport.getDecodeQuery(enc);
assertEquals(out, dec);
ou... |
@Override
public Object evaluateUnsafe(EvaluationContext context) {
final Object idxObj = this.index.evaluateUnsafe(context);
final Object indexable = indexableObject.evaluateUnsafe(context);
if (idxObj == null || indexable == null) {
return null;
}
if (idxObj in... | @Test
public void invalidObject() {
final IndexedAccessExpression expression = new IndexedAccessExpression(START, obj(23), num(0));
// this should throw an exception
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> expression.evaluateUnsafe(context... |
public static void doRegister(final String json, final String url, final String type, final String accessToken) throws IOException {
if (StringUtils.isBlank(accessToken)) {
LOGGER.error("{} client register error accessToken is null, please check the config : {} ", type, json);
return;
... | @Test
public void testDoRegisterWhenThrowException() throws IOException {
when(okHttpTools.post(url, json)).thenThrow(IOException.class);
assertThrows(IOException.class, () -> {
try (MockedStatic<OkHttpTools> okHttpToolsMockedStatic = mockStatic(OkHttpTools.class)) {
okHt... |
@Override
public void run() {
// top-level command, do nothing
} | @Test
public void test_submit_withClassName() {
run("submit", "--class", "com.hazelcast.jet.testjob.TestJob", testJobJarFile.toString());
assertTrueEventually(() -> assertEquals(1, hz.getJet().getJobs().size()), 5);
Job job = hz.getJet().getJobs().get(0);
assertThat(job).eventuallyHa... |
public CompletableFuture<Integer> read(ByteBuffer buf, long offset, long len, FileId fileId,
String ufsPath, UfsReadOptions options) {
Objects.requireNonNull(buf);
if (offset < 0 || len < 0 || len > buf.remaining()) {
throw new OutOfRangeRuntimeException(String.format(
"offset is negative,... | @Test
public void offset() throws Exception {
mUfsIOManager.read(TEST_BUF, 2, TEST_BLOCK_SIZE - 2, FIRST_BLOCK_ID, mTestFilePath,
UfsReadOptions.getDefaultInstance()).get();
assertTrue(checkBuf(2, (int) TEST_BLOCK_SIZE - 2, TEST_BUF));
TEST_BUF.clear();
} |
@Override
public <I, O> List<O> flatMap(List<I> data, SerializableFunction<I, Stream<O>> func, int parallelism) {
return data.stream().parallel().flatMap(throwingFlatMapWrapper(func)).collect(Collectors.toList());
} | @Test
public void testFlatMap() {
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> list3 = Arrays.asList("g", "h", "i");
List<List<String>> inputList = new ArrayList<>();
inputList.add(list1);
inputList.add(list2);
inputLis... |
public synchronized void synchronizeClusterSchemas( ClusterSchema clusterSchema ) {
synchronizeClusterSchemas( clusterSchema, clusterSchema.getName() );
} | @Test
public void synchronizeClusterSchemas_should_not_sync_unshared() throws Exception {
final String clusterSchemaName = "ClusterSchema";
TransMeta transformarion1 = createTransMeta();
ClusterSchema clusterSchema1 = createClusterSchema( clusterSchemaName, true );
transformarion1.setClusterSchemas( C... |
public static ResourceProfile generateTaskManagerTotalResourceProfile(
WorkerResourceSpec workerResourceSpec) {
return ResourceProfile.newBuilder()
.setCpuCores(workerResourceSpec.getCpuCores())
.setTaskHeapMemory(workerResourceSpec.getTaskHeapSize())
... | @Test
void testGenerateTaskManagerTotalResourceProfile() {
final ResourceProfile resourceProfile =
ResourceProfile.newBuilder()
.setCpuCores(1.0)
.setTaskHeapMemoryMB(1)
.setTaskOffHeapMemoryMB(2)
... |
public static Optional<CeTaskInterruptedException> isTaskInterruptedException(Throwable e) {
if (e instanceof CeTaskInterruptedException ceTaskInterruptedException) {
return Optional.of(ceTaskInterruptedException);
}
return isCauseInterruptedException(e);
} | @Test
public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass_in_cause_chain() {
String message = randomAlphabetic(50);
CeActivityDto.Status status = randomStatus();
CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) {
};
CeTaskInterrupt... |
@Override
public VarianceAccumulator addInput(VarianceAccumulator currentVariance, T rawInput) {
if (rawInput == null) {
return currentVariance;
}
return currentVariance.combineWith(
VarianceAccumulator.ofSingleElement(SqlFunctions.toBigDecimal(rawInput)));
} | @Test
public void testReturnsAccumulatorUnchangedForNullInput() {
VarianceAccumulator accumulator = newVarianceAccumulator(ZERO, BigDecimal.ONE, BigDecimal.TEN);
assertEquals(accumulator, varianceFn.addInput(accumulator, null));
} |
public List<CounterRequest> getRequests() {
// thread-safe :
// on crée une copie de la collection et on clone ici chaque CounterRequest de manière synchronisée
// de manière à ce que l'appelant n'ai pas à se préoccuper des synchronisations nécessaires
// Rq : l'Iterator sur ConcurrentHashMap.values() est garan... | @Test
public void testGetRequests() {
counter.clear();
final CounterRequest counterRequest = createCounterRequest();
counter.addHits(counterRequest);
final List<CounterRequest> requests = counter.getRequests();
assertEquals("requests size", 1, requests.size());
assertEquals("request", counterRequest.toStri... |
@Override
public void markFailed(Throwable t) {
currentExecutions.values().forEach(e -> e.markFailed(t));
} | @Test
void testMarkFailed() throws Exception {
final SpeculativeExecutionVertex ev = createSpeculativeExecutionVertex();
final Execution e1 = ev.getCurrentExecutionAttempt();
final Execution e2 = ev.createNewSpeculativeExecution(System.currentTimeMillis());
ev.markFailed(new Excepti... |
@Override
public Object evaluateUnsafe(EvaluationContext context) {
final Object idxObj = this.index.evaluateUnsafe(context);
final Object indexable = indexableObject.evaluateUnsafe(context);
if (idxObj == null || indexable == null) {
return null;
}
if (idxObj in... | @Test
public void accessArray() {
int ary[] = new int[] {23};
final IndexedAccessExpression idxExpr = new IndexedAccessExpression(START, obj(ary), num(0));
final Object evaluate = idxExpr.evaluateUnsafe(context);
assertThat(evaluate).isOfAnyClassIn(Integer.class);
assertThat... |
public RingbufferConfig setTimeToLiveSeconds(int timeToLiveSeconds) {
this.timeToLiveSeconds = checkNotNegative(timeToLiveSeconds, "timeToLiveSeconds can't be smaller than 0");
return this;
} | @Test(expected = IllegalArgumentException.class)
public void setTimeToLiveSeconds_whenNegative() {
RingbufferConfig config = new RingbufferConfig(NAME);
config.setTimeToLiveSeconds(-1);
} |
public DropTypeCommand create(final DropType statement) {
final String typeName = statement.getTypeName();
final boolean ifExists = statement.getIfExists();
if (!ifExists && !metaStore.resolveType(typeName).isPresent()) {
throw new KsqlException("Type " + typeName + " does not exist.");
}
re... | @Test
public void shouldFailCreateTypeIfTypeDoesNotExist() {
// Given:
final DropType dropType = new DropType(Optional.empty(), NOT_EXISTING_TYPE, false);
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> factory.create(dropType)
);
// Then:
assertThat... |
public static <T> JSONSchema<T> of(SchemaDefinition<T> schemaDefinition) {
SchemaReader<T> reader = schemaDefinition.getSchemaReaderOpt()
.orElseGet(() -> new JacksonJsonReader<>(jsonMapper(), schemaDefinition.getPojo()));
SchemaWriter<T> writer = schemaDefinition.getSchemaWriterOpt()
... | @Test
public void testNotAllowNullEncodeAndDecode() {
JSONSchema<Foo> jsonSchema = JSONSchema.of(SchemaDefinition.<Foo>builder().withPojo(Foo.class).withAlwaysAllowNull(false).build());
Foo foo1 = new Foo();
foo1.setField1("foo1");
foo1.setField2("bar1");
foo1.setField4(new ... |
public void validateFilterExpression(final Expression exp) {
final SqlType type = getExpressionReturnType(exp);
if (!SqlTypes.BOOLEAN.equals(type)) {
throw new KsqlStatementException(
"Type error in " + filterType.name() + " expression: "
+ "Should evaluate to boolean but is"
... | @Test
public void shouldThrowOnBadTypeCompoundComparison_leftError() {
// Given:
final Expression left1 = new UnqualifiedColumnReferenceExp(COLUMN1);
final Expression right1 = new UnqualifiedColumnReferenceExp(COLUMN2);
final Expression comparision1 = new ComparisonExpression(Type.EQUAL, left1, right1... |
@Override
public final void isEqualTo(@Nullable Object other) {
if (Objects.equal(actual, other)) {
return;
}
// Fail but with a more descriptive message:
if (actual == null || !(other instanceof Map)) {
super.isEqualTo(other);
return;
}
containsEntriesInAnyOrder((Map<?, ?... | @Test
public void isEqualToFailureDiffering_sameToString() {
ImmutableMap<String, Number> actual =
ImmutableMap.<String, Number>of("jan", 1, "feb", 2, "march", 3L);
ImmutableMap<String, Integer> expectedMap = ImmutableMap.of("jan", 1, "feb", 2, "march", 3);
expectFailureWhenTestingThat(actual).is... |
@Override
public RLock readLock() {
return new RedissonReadLock(commandExecutor, getName());
} | @Test
public void testIsLockedOtherThread() throws InterruptedException {
RReadWriteLock rwlock = redisson.getReadWriteLock("lock");
RLock lock = rwlock.readLock();
lock.lock();
Thread t = new Thread() {
public void run() {
RReadWriteLock rwlock = redisso... |
public int addWritePermOfBrokerByLock(final String brokerName) {
try {
try {
this.lock.writeLock().lockInterruptibly();
return operateWritePermOfBroker(brokerName, RequestCode.ADD_WRITE_PERM_OF_BROKER);
} finally {
this.lock.writeLock().unl... | @Test
public void testAddWritePermOfBrokerByLock() throws Exception {
Map<String, QueueData> qdMap = new HashMap<>();
QueueData qd = new QueueData();
qd.setPerm(PermName.PERM_READ);
qd.setBrokerName("broker-a");
qdMap.put("broker-a",qd);
HashMap<String, Map<String, Qu... |
@Override
public void execute(ComputationStep.Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) {
@Override
public void visitProject(Component project) {
executeForProject(project);
}
}).visit(tree... | @Test
void new_measure_has_ERROR_level_of_all_conditions_for_a_specific_metric_if_its_the_worst() {
int rawValue = 3;
Condition fixedCondition = createLessThanCondition(INT_METRIC_1, "4");
Condition periodCondition = createLessThanCondition(INT_METRIC_1, "2");
qualityGateHolder.setQualityGate(new Qua... |
@Override
public void onWorkflowFinalized(Workflow workflow) {
WorkflowSummary summary = StepHelper.retrieveWorkflowSummary(objectMapper, workflow.getInput());
WorkflowRuntimeSummary runtimeSummary = retrieveWorkflowRuntimeSummary(workflow);
String reason = workflow.getReasonForIncompletion();
LOG.inf... | @Test
public void testNonRetryableErrorOnWorkflowFinalized() {
Task task1 = new Task();
task1.setReferenceTaskName("bar");
Map<String, Object> summary = new HashMap<>();
summary.put("runtime_state", Collections.singletonMap("status", "SUCCEEDED"));
summary.put("type", "NOOP");
task1.setOutputD... |
@VisibleForTesting
static int checkJar(Path file) throws Exception {
final URI uri = file.toUri();
int numSevereIssues = 0;
try (final FileSystem fileSystem =
FileSystems.newFileSystem(
new URI("jar:file", uri.getHost(), uri.getPath(), uri.getFragment... | @Test
void testIgnoreLicenseDirectories(@TempDir Path tempDir) throws Exception {
assertThat(
JarFileChecker.checkJar(
createJar(
tempDir,
Entry.fileEntry(VALID_NOTICE_CONT... |
public static boolean acceptEndpoint(String endpointUrl) {
return endpointUrl != null && endpointUrl.matches(ENDPOINT_PATTERN_STRING);
} | @Test
public void testAcceptEndpointFailures() {
assertFalse(AMQPMessageConsumptionTask.acceptEndpoint("amqp://localhost/x/testQueue"));
assertFalse(AMQPMessageConsumptionTask.acceptEndpoint("rabbit://localhost/x/testQueue"));
} |
@Override
public void resetConfigStats(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<Void> f = executorService.writeAsync(entry, StringCodec.INSTANCE, RedisCommands.CONFIG_RESETSTAT);
syncFuture(f);
} | @Test
public void testResetConfigStats() {
RedisClusterNode master = getFirstMaster();
connection.resetConfigStats(master);
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void leaveChat() {
BaseResponse response = bot.execute(new LeaveChat(chatId));
assertFalse(response.isOk());
assertEquals(400, response.errorCode());
assertEquals("Bad Request: chat member status can't be changed in private chats", response.description());
} |
@Override
protected Set<StepField> getUsedFields( RestMeta stepMeta ) {
Set<StepField> usedFields = new HashSet<>();
// add url field
if ( stepMeta.isUrlInField() && StringUtils.isNotEmpty( stepMeta.getUrlField() ) ) {
usedFields.addAll( createStepFields( stepMeta.getUrlField(), getInputs() ) );
... | @Test
public void testGetUsedFields_parameterField() throws Exception {
Set<StepField> fields = new HashSet<>();
when( meta.getParameterField() ).thenReturn( new String[] { "param1", "param2" } );
doReturn( stepNodes ).when( analyzer ).getInputs();
doReturn( fields ).when( analyzer ).createStepFields(... |
@Override
public Boolean update(List<ModifyRequest> modifyRequests, BiConsumer<Boolean, Throwable> consumer) {
return update(transactionTemplate, jdbcTemplate, modifyRequests, consumer);
} | @Test
void testUpdate1() {
List<ModifyRequest> modifyRequests = new ArrayList<>();
ModifyRequest modifyRequest1 = new ModifyRequest();
String sql = "UPDATE config_info SET data_id = 'test' WHERE id = ?;";
modifyRequest1.setSql(sql);
Object[] args = new Object[] {1};
m... |
@Override
public void upgrade() {
if (hasBeenRunSuccessfully()) {
LOG.debug("Migration already completed.");
return;
}
final Set<String> dashboardIdToViewId = new HashSet<>();
final Consumer<String> recordMigratedDashboardIds = dashboardIdToViewId::add;
... | @Test
@MongoDBFixtures("ops_dashboards.json")
public void migrateOpsDashboards() throws Exception {
this.migration.upgrade();
final MigrationCompleted migrationCompleted = captureMigrationCompleted();
assertThat(migrationCompleted.migratedDashboardIds())
.containsExactly... |
public FEELFnResult<String> invoke(@ParameterName( "string" ) String string, @ParameterName( "match" ) String match) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
}
if ( match == null ) {
ret... | @Test
void invokeMatchExists() {
FunctionTestUtil.assertResult(substringAfterFunction.invoke("foobar", "ob"), "ar");
FunctionTestUtil.assertResult(substringAfterFunction.invoke("foobar", "o"), "obar");
} |
public static TypeInformation<?> readTypeInfo(String typeString) {
final List<Token> tokens = tokenize(typeString);
final TokenConverter converter = new TokenConverter(typeString, tokens);
return converter.convert();
} | @Test
void testSyntaxError2() {
assertThatThrownBy(
() -> TypeStringUtils.readTypeInfo("ROW<f0 DECIMAL DECIMAL, f1 TINYINT>"))
.isInstanceOf(ValidationException.class); // duplicate type
} |
public static <T> RestResult<T> failedWithMsg(int code, String errMsg) {
return RestResult.<T>builder().withCode(code).withMsg(errMsg).build();
} | @Test
void testFailedWithMsgMethod() {
RestResult<String> restResult = RestResultUtils.failedWithMsg(400, "content");
assertRestResult(restResult, 400, "content", null, false);
} |
public MessagesRequestSpec simpleQueryParamsToFullRequestSpecification(final String query,
final Set<String> streams,
final String timerangeKeyword,
... | @Test
void throwsExceptionOnWrongMetricFormat() {
assertThrows(IllegalArgumentException.class, () -> toTest.simpleQueryParamsToFullRequestSpecification("*",
Set.of(),
"42d",
List.of("http_method"),
List.of("avg:joe", "ayayayayay!")));
} |
@Override
protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance)
throws RpcException {
RetryContext.INSTANCE.markRetry(retry);
checkInvokers(invokers, invocation);
final List<io.github.resilience4j.retry.Retry> handlers = retryHandler... | @Test
public void doInvoke() {
final Directory<Result> directory = Mockito.mock(Directory.class);
Mockito.when(directory.getUrl()).thenReturn(new URL("dubbo", "localhost", 8080));
final ApacheDubboClusterInvoker<Result> clusterInvoker = new ApacheDubboClusterInvoker<>(directory);
fin... |
@Nullable
@Override
public Session load(@NonNull String sessionId) {
var session = store.getIfPresent(sessionId);
if (session == null || session.createdAt().plus(timeToLive).isBefore(Instant.now())) {
return null;
}
return session;
} | @Test
void load_realCache_bounded() {
var maxSize = 10;
var ttl = Duration.ofMinutes(5);
Cache<String, Session> store = Caffeine.newBuilder().maximumSize(maxSize).build();
var sut = new CaffeineSessionRepo(store, ttl);
var state = "myState";
var nonce = UUID.randomUUID().toString();
var ... |
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String uri = request.getRequestURI();
String method = request.getMethod()... | @Test
void testDoFilterForBeatUri() throws IOException {
when(request.getParameter("ip")).thenReturn("127.0.0.1");
when(request.getParameter("port")).thenReturn("8848");
when(request.getParameter("encoding")).thenReturn("utf-8");
when(clientManager.getClient("127.0.0.1:8848#true")).t... |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback callback, final ConnectionCallback connectionCallback) throws BackgroundException {
try {
if(status.isExists()) {
if(log.isWarnEnabled()) {
log.w... | @Test
public void testMoveDirectory() throws Exception {
final Path sourceDirectory = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory));
final Path targetDirectory = new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new Alp... |
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Comparable<?>> shardingValue) {
ShardingSpherePreconditions.checkNotNull(shardingValue.getValue(), NullShardingValueException::new);
String suffix = String.valueOf(hashShardingValue(shardingV... | @Test
void assertRangeDoSharding() {
List<String> availableTargetNames = Arrays.asList("t_order_0", "t_order_1", "t_order_2", "t_order_3");
Collection<String> actual = shardingAlgorithm.doSharding(availableTargetNames, new RangeShardingValue<>("t_order", "create_time", DATA_NODE_INFO, Range.closed("... |
public PrepareResult prepare(HostValidator hostValidator, DeployLogger logger, PrepareParams params,
Optional<ApplicationVersions> activeApplicationVersions, Instant now, File serverDbSessionDir,
ApplicationPackage applicationPackage, SessionZooKeeperCli... | @Test
public void require_that_application_id_is_written_in_prepare() throws IOException {
PrepareParams params = new PrepareParams.Builder().applicationId(applicationId()).build();
int sessionId = 1;
prepare(testApp, params);
assertEquals(applicationId(), createSessionZooKeeperClien... |
@POST
@ZeppelinApi
public Response createNote(String message) throws IOException {
String user = authenticationService.getPrincipal();
LOGGER.info("Creating new note by JSON {}", message);
NewNoteRequest request = GSON.fromJson(message, NewNoteRequest.class);
String defaultInterpreterGroup = request... | @Test
void testCancelNoteJob() throws Exception {
LOG.info("Running testCancelNoteJob");
String note1Id = null;
try {
note1Id = notebook.createNote("note1", anonymous);
// Add 3 paragraphs for the note.
List<Paragraph> paragraphs = notebook.processNote(note1Id,
note1 -> {
... |
public static FEEL_1_1Parser parse(FEELEventListenersManager eventsManager, String source, Map<String, Type> inputVariableTypes, Map<String, Object> inputVariables, Collection<FEELFunction> additionalFunctions, List<FEELProfile> profiles, FEELTypeRegistry typeRegistry) {
CharStream input = CharStreams.fromStrin... | @Test
void power1() {
String inputExpression = "y * 5 ** 3";
BaseNode infix = parse( inputExpression, mapOf(entry("y", BuiltInType.NUMBER)) );
assertThat( infix).isInstanceOf(InfixOpNode.class);
assertThat( infix.getResultType()).isEqualTo(BuiltInType.NUMBER);
assertThat( in... |
@Override
public boolean supports(String hashedPassword) {
return prefixPattern.matcher(hashedPassword).matches();
} | @Test
public void testSupports() throws Exception {
assertThat(SHA1HashPasswordAlgorithm.supports("deadbeefaffedeadbeefdeadbeefaffedeadbeef")).isTrue();
assertThat(SHA1HashPasswordAlgorithm.supports("{bcrypt}foobar")).isFalse();
assertThat(SHA1HashPasswordAlgorithm.supports("{foobar}foobar")... |
public static SlaveConnectionManager getInstance() {
if ( slaveConnectionManager == null ) {
slaveConnectionManager = new SlaveConnectionManager();
}
return slaveConnectionManager;
} | @Test
public void shouldOverrideDefaultSSLContextByDefault() throws Exception {
System.clearProperty( "javax.net.ssl.keyStore" );
SlaveConnectionManager instance = SlaveConnectionManager.getInstance();
assertNotEquals( defaultContext, SSLContext.getDefault() );
} |
@Override public HashSlotCursor8byteKey cursor() {
return new Cursor();
} | @Test
public void testCursor_valueAddress() {
final SlotAssignmentResult slot = insert(random.nextLong());
HashSlotCursor8byteKey cursor = hsa.cursor();
cursor.advance();
assertEquals(slot.address(), cursor.valueAddress());
} |
@Override
@MethodNotAvailable
public CompletionStage<V> putAsync(K key, V value) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testPutAsync() {
adapter.putAsync(42, "newValue");
} |
@Override
@PublicAPI(usage = ACCESS)
public String getName() {
return WILDCARD_TYPE_NAME + boundsToString();
} | @Test
public void wildcard_name_lower_bounded() {
@SuppressWarnings("unused")
class LowerBounded<T extends List<? super String>> {
}
JavaWildcardType wildcardType = importWildcardTypeOf(LowerBounded.class);
assertThat(wildcardType.getName()).isEqualTo("? super java.lang.Str... |
@Bean
public SyncDataService websocketSyncDataService(final ObjectProvider<WebsocketConfig> websocketConfig, final ObjectProvider<PluginDataSubscriber> pluginSubscriber,
final ObjectProvider<List<MetaDataSubscriber>> metaSubscribers, final ObjectProvider<List<Auth... | @Test
public void testWebsocketSyncDataService() {
assertNotNull(websocketSyncDataService);
} |
@Override
public String telnet(AbstractChannel channel, String message) {
StringBuilder result = new StringBuilder();
if (StringUtils.isNotBlank(message)) {
TelnetHandler handler = TelnetHandlerFactory.getHandler(message);
if (handler != null) {
result.append(... | @Test
public void telnet() throws Exception {
Assert.assertNotNull(new HelpTelnetHandler().telnet(null, ""));
Assert.assertNotNull(new HelpTelnetHandler().telnet(null, null));
Assert.assertNotNull(new HelpTelnetHandler().telnet(null, "xx"));
} |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test
public void testMergeDifferentClassName() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createUpdatedSinkConfig("className", "Different");
SinkConfig mergedConfig = SinkConfigUtils.validateUpdate(sinkConfig, newSinkConfig);
assertEquals(
... |
public static void hookIntentGetService(Context context, int requestCode, Intent intent, int flags) {
hookIntent(intent);
} | @Test
public void hookIntentGetService() {
PushAutoTrackHelper.hookIntentGetService(mApplication, 100, MockDataTest.mockJPushIntent(), 100);
} |
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath)
throws IOException, ParseException, RestHandlerException {
// make sure we request the "index.html" in case there is a directory request
if (requestPath.endsWith("/")) {
requestPath ... | @Test
void testRespondWithFile(@TempDir Path tmpDir) throws Exception {
final Path webDir = Files.createDirectory(tmpDir.resolve("webDir"));
final Path uploadDir = Files.createDirectory(tmpDir.resolve("uploadDir"));
Router router =
new Router()
.addGe... |
public static String printDistributed(SubPlan plan, FunctionAndTypeManager functionAndTypeManager, Session session)
{
List<PlanFragment> fragments = plan.getAllFragments();
Map<PlanFragmentId, PlanFragment> fragmentsById = Maps.uniqueIndex(fragments, PlanFragment::getId);
PlanNodeIdGenerator... | @Test
public void testPrintDistributed()
{
SubPlan tableScanNodeSubPlan = new SubPlan(
createTestPlanFragment(0, TEST_TABLE_SCAN_NODE),
ImmutableList.of());
SubPlan nestedSubPlan = new SubPlan(
createTestPlanFragment(1, TEST_TABLE_SCAN_NODE),
... |
@Override
public Set<Long> calculateUsers(DelegateExecution execution, String param) {
Set<Long> deptIds = StrUtils.splitToLongSet(param);
List<DeptRespDTO> depts = deptApi.getDeptList(deptIds);
return convertSet(depts, DeptRespDTO::getLeaderUserId);
} | @Test
public void testCalculateUsers() {
// 准备参数
String param = "1,2";
// mock 方法
DeptRespDTO dept1 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(11L));
DeptRespDTO dept2 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(22L));
when(deptApi.getDeptList(e... |
public static Gson instance() {
return SingletonHolder.INSTANCE;
} | @Test
void rejectsDeserializationOfAESCipherProvider() {
final IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
Serialization.instance().fromJson("{}", AESCipherProvider.class));
assertEquals(format("Refusing to deserialize a %s in the JSON stream!", AE... |
@VisibleForTesting
static ImmutableSet<Port> portMapToSet(@Nullable Map<String, Map<String, String>> portMap)
throws BadContainerConfigurationFormatException {
if (portMap == null) {
return ImmutableSet.of();
}
ImmutableSet.Builder<Port> ports = new ImmutableSet.Builder<>();
for (Map.Entry... | @Test
public void testPortMapToList() throws BadContainerConfigurationFormatException {
ImmutableSortedMap<String, Map<String, String>> input =
ImmutableSortedMap.of(
"1000",
ImmutableMap.of(),
"2000/tcp",
ImmutableMap.of(),
"3000/udp",
... |
public static Object getConstructorArg(Class<?> cl) {
if (boolean.class.equals(cl) || Boolean.class.equals(cl)) {
return Boolean.FALSE;
}
if (byte.class.equals(cl) || Byte.class.equals(cl)) {
return (byte) 0;
}
if (short.class.equals(cl) || Short.class.e... | @Test
void testConstructorArg() {
Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(boolean.class));
Assertions.assertFalse((boolean) JavaBeanSerializeUtil.getConstructorArg(Boolean.class));
Assertions.assertEquals((byte) 0, JavaBeanSerializeUtil.getConstructorArg(byte... |
@Override
public MapperResult findDeletedConfig(MapperContext context) {
return new MapperResult(
"SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' AND "
+ "gmt_modified >= ? and nid > ? order by nid OFFSET 0 ROWS FETCH NEX... | @Test
void testFindDeletedConfig() {
MapperResult mapperResult = historyConfigInfoMapperByDerby.findDeletedConfig(context);
assertEquals(mapperResult.getSql(), "SELECT data_id, group_id, tenant_id,gmt_modified,nid FROM his_config_info WHERE op_type = 'D' "
+ "AND gmt_modified >= ? an... |
OutputT apply(InputT input) throws UserCodeExecutionException {
Optional<UserCodeExecutionException> latestError = Optional.empty();
long waitFor = 0L;
while (waitFor != BackOff.STOP) {
try {
sleepIfNeeded(waitFor);
incIfPresent(getCallCounter());
return getThrowableFunction().... | @Test
public void givenCallerTimeoutErrorsExceedsLimit_emitsIntoFailurePCollection() {
PCollectionTuple pct =
pipeline
.apply(Create.of(1))
.apply(
ParDo.of(
new DoFnWithRepeaters(
new CallerImpl(LIMIT + 1, UserCod... |
@Override
public BulkOperationResponse executeBulkOperation(final BulkOperationRequest bulkOperationRequest, final C userContext, final AuditParams params) {
if (bulkOperationRequest.entityIds() == null || bulkOperationRequest.entityIds().isEmpty()) {
throw new BadRequestException(NO_ENTITY_IDS_... | @Test
void returnsProperResponseOnFailedBulkRemoval() throws Exception {
mockUserContext();
doThrow(new NotFoundException("!?!?")).when(singleEntityOperationExecutor).execute(any(), eq(context));
final BulkOperationResponse bulkOperationResponse = toTest.executeBulkOperation(new BulkOperatio... |
public AuthenticationProvider getAuthenticationProvider() {
return authenticationProvider;
} | @Test(timeOut = 30000)
public void testConnectCommandWithInvalidRoleCombinations() throws Exception {
AuthenticationService authenticationService = mock(AuthenticationService.class);
AuthenticationProvider authenticationProvider = new MockAuthenticationProvider();
String authMethodName = aut... |
@Override
public PayloadSerializer getSerializer(Schema schema, Map<String, Object> tableParams) {
Class<? extends TBase> thriftClass = getMessageClass(tableParams);
TProtocolFactory protocolFactory = getProtocolFactory(tableParams);
inferAndVerifySchema(thriftClass, schema);
return getPayloadSerializ... | @Test
public void invalidArgs() {
assertThrows(
IllegalArgumentException.class,
() -> provider.getSerializer(SHUFFLED_SCHEMA, ImmutableMap.of()));
assertThrows(
IllegalArgumentException.class,
() ->
provider.getSerializer(
SHUFFLED_SCHEMA,
... |
public String swVersion() {
return get(SW_VERSION, null);
} | @Test
public void testSetSwVersion() {
SW_BDC.swVersion(SW_VERSION_NEW);
assertEquals("Incorrect swVersion", SW_VERSION_NEW, SW_BDC.swVersion());
} |
@VisibleForTesting
public Path getBasePath() {
return this.basePath;
} | @Test
void testBasePath() throws IOException {
JobID jobID = JobID.generate();
String rootPath = "/dstl-root-path";
Path oriBasePath = new Path(rootPath);
ChangelogStorageMetricGroup metrics =
new ChangelogStorageMetricGroup(createUnregisteredTaskManagerJobMetricGrou... |
public void setCancellationContext(CancellationContext cancellationContext) {
this.cancellationContext = cancellationContext;
} | @Test
void setCancellationContext() {
CancelableStreamObserver<Object> observer = new CancelableStreamObserver<Object>() {
@Override
public void onNext(Object data) {}
@Override
public void onError(Throwable throwable) {}
@Override
pu... |
public static ResourceModel processResource(final Class<?> resourceClass)
{
return processResource(resourceClass, null);
} | @Test(expectedExceptions = ResourceConfigException.class)
public void failsOnMissingParamAnnotation() {
@RestLiCollection(name = "noParamAnnotation")
class LocalClass extends CollectionResourceTemplate<Long, EmptyRecord> {
@Action(name = "noParamAnnotation")
public void noParamAnnotation(String s... |
@Override
public void open() throws InterpreterException {
try {
SparkConf conf = new SparkConf();
for (Map.Entry<Object, Object> entry : getProperties().entrySet()) {
if (!StringUtils.isBlank(entry.getValue().toString())) {
conf.set(entry.getKey().toString(), entry.getValue().toStri... | @Test
void testDisableSparkUI_1() throws InterpreterException {
Properties properties = new Properties();
properties.setProperty(SparkStringConstants.MASTER_PROP_NAME, "local");
properties.setProperty(SparkStringConstants.APP_NAME_PROP_NAME, "test");
properties.setProperty("zeppelin.spark.maxResult", ... |
public static RowCoder of(Schema schema) {
return new RowCoder(schema);
} | @Test
public void testConsistentWithEqualsIterableWithNull() throws Exception {
Schema schema =
Schema.builder()
.addField("a", Schema.FieldType.iterable(Schema.FieldType.INT32.withNullable(true)))
.build();
Row row = Row.withSchema(schema).addValue(Arrays.asList(1, null)).bui... |
@Override
public String getScheme() {
return "file";
} | @Test
public void testStatistics() throws Exception {
int fileSchemeCount = 0;
for (Statistics stats : FileSystem.getAllStatistics()) {
if (stats.getScheme().equals("file")) {
fileSchemeCount++;
}
}
assertEquals(1, fileSchemeCount);
} |
@Override
public void write( int b ) throws IOException {
write( new byte[] { (byte) b, } );
} | @Test
public void testWrite() throws IOException {
WriterOutputStream stream = new WriterOutputStream( writer );
stream.write( 68 );
stream.write( "value".getBytes(), 1, 3 );
stream.write( "value".getBytes() );
stream.flush();
stream.close();
verify( writer ).append( new String( new byte[]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.