focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public long estimate() {
final double raw = (1 / computeE()) * alpha() * m * m;
return applyRangeCorrection(raw);
} | @Test
public void testAlpha_withMemoryFootprintOf16() {
DenseHyperLogLogEncoder encoder = new DenseHyperLogLogEncoder(4);
encoder.estimate();
} |
private String getAwsCredentialType() {
if (Config.aws_s3_use_aws_sdk_default_behavior) {
return "default";
}
if (Config.aws_s3_use_instance_profile) {
if (Config.aws_s3_iam_role_arn.isEmpty()) {
return "instance_profile";
}
retur... | @Test
public void testGetAwsCredentialType() throws Exception {
boolean oldAwsS3UseAwsSdkDefaultBehavior = Config.aws_s3_use_aws_sdk_default_behavior;
boolean oldAwsS3UseInstanceProfile = Config.aws_s3_use_instance_profile;
String oldAwsS3AccessKey = Config.aws_s3_access_key;
String ... |
@Override
@CheckForNull
public Measure getMeasure(String metric) {
validateInputMetric(metric);
Optional<org.sonar.ce.task.projectanalysis.measure.Measure> measure = measureRepository.getRawMeasure(internalComponent, metricRepository.getByKey(metric));
if (measure.isPresent()) {
return new Measure... | @Test
public void get_measure() {
measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10));
MeasureComputerContextImpl underTest = newContext(FILE_1_REF, NCLOC_KEY, COMMENT_LINES_KEY);
assertThat(underTest.getMeasure(NCLOC_KEY).getIntValue()).isEqualTo(10);
} |
public synchronized boolean sendHttpEvent(SplunkEvent event) {
return sendHttpEvents(Collections.singletonList(event));
} | @Test
public void testSendHttpEventsShouldThrowErrorWhenHttpClientFailsToExecuteRequest()
throws IOException {
SplunkEvent event = SplunkEvent.newBuilder().withEvent(EVENT).create();
CloseableHttpClient mockHttpClient = clientFactory.getHttpClient();
doThrow(IOException.class).when(mockHttpClient).... |
@Override
public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) {
if (requestData == null) {
return super.handle(targetName, instances, null);
}
if (!shouldHandle(instances)) {
return instances;
}
List<Object> r... | @Test
public void testGetTargetInstancesByGlobalRules() {
RuleInitializationUtils.initGlobalFlowMatchRules();
List<Object> instances = new ArrayList<>();
ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInstance("1.0.0");
instances.add(instance1);
S... |
List<String> zones(String project, String region, String accessToken) {
String url = String.format("%s/compute/v1/projects/%s/regions/%s?alt=json&fields=zones", endpoint, project, region);
String response = RestClient
.create(url)
.withHeader("Authorization", String.forma... | @Test
public void zones() {
// given
stubFor(get(urlEqualTo(
String.format("/compute/v1/projects/%s/regions/%s?alt=json&fields=zones", PROJECT, REGION)))
.withHeader("Authorization", equalTo(String.format("OAuth %s", ACCESS_TOKEN)))
.willReturn(aRespon... |
void moveHeadIndexByOne() {
this.headIndex = (headIndex + 1) % timeWindowSizeInSeconds;
} | @Test
public void testMoveHeadIndexByOne() {
MockClock clock = MockClock.at(2019, 8, 4, 12, 0, 0, ZoneId.of("UTC"));
SlidingTimeWindowMetrics metrics = new SlidingTimeWindowMetrics(3, clock);
assertThat(metrics.headIndex).isZero();
metrics.moveHeadIndexByOne();
assertThat(... |
@Override
public String getImplMethodName() {
return name;
} | @Test
void test() throws NoSuchMethodException, IllegalAccessException {
MethodHandles.Lookup lookup = MethodHandles.lookup();
MethodHandle handle = lookup.findStatic(IdeaProxyLambdaMetaTest.class, "s", MethodType.methodType(int.class));
// 模拟 IDEA 的 lambda 生成
IntSupplier supplier =... |
@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws BackgroundException {
final InputStream normalized = this.normalize(in, status);
final CRC32 crc32 = new CRC32();
try {
byte[] buffer = new byte[16384];
int bytesRead;
... | @Test
public void testCompute() throws Exception {
assertEquals("0",
new CRC32ChecksumCompute().compute(new NullInputStream(0), new TransferStatus()).hash);
assertEquals("d202ef8d",
new CRC32ChecksumCompute().compute(new NullInputStream(1L), new TransferStatus()).hash... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void testAsyncCallback() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
bot.execute(new GetMe(), new Callback<GetMe, GetMeResponse>() {
@Override
public void onResponse(GetMe request, GetMeResponse response) {
latch.countDown();
... |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "{namespace}/files")
@Operation(tags = {"Files"}, summary = "Delete a file or directory")
public void delete(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The internal storage uri of the file... | @Test
void forbiddenPaths() {
assertForbiddenErrorThrown(() -> client.toBlocking().retrieve(HttpRequest.GET("/api/v1/namespaces/" + NAMESPACE + "/files?path=/_flows/test.yml")));
assertForbiddenErrorThrown(() -> client.toBlocking().retrieve(HttpRequest.GET("/api/v1/namespaces/" + NAMESPACE + "/files... |
public static List<String> parseAsList(String value, String delimiter) {
return Lists.newArrayList(Splitter.on(delimiter).trimResults().omitEmptyStrings()
.split(value));
} | @Test
public void parseAsList() {
assertEquals(Lists.newArrayList("a"), ConfigurationUtils.parseAsList("a", ","));
assertEquals(Lists.newArrayList("a", "b", "c"), ConfigurationUtils.parseAsList("a,b,c", ","));
assertEquals(Lists.newArrayList("a", "b", "c"),
ConfigurationUtils.parseAsList(" a , b ,... |
@Override
public String toString() {
if (isUnspecified())
return "unspecified resources";
StringBuilder sb = new StringBuilder("[vcpu: ");
appendDouble(sb, vcpu);
sb.append(", memory: ");
appendDouble(sb, memoryGiB);
sb.append(" Gb, disk: ");
appe... | @Test
void testToString() {
assertEquals("[vcpu: 1.0, memory: 10.0 Gb, disk: 100.0 Gb, architecture: any]",
new NodeResources(1., 10., 100., 0).toString());
assertEquals("[vcpu: 0.3, memory: 3.3 Gb, disk: 33.3 Gb, bandwidth: 0.3 Gbps, architecture: any]",
... |
public void writeReference(Reference reference) throws IOException {
if (reference instanceof StringReference) {
writeQuotedString((StringReference) reference);
} else if (reference instanceof TypeReference) {
writeType((TypeReference) reference);
} else if (reference ins... | @Test
public void testWriteReference_field() throws IOException {
DexFormattedWriter writer = new DexFormattedWriter(output);
writer.writeReference(getFieldReference());
Assert.assertEquals(
"Ldefining/class;->fieldName:Lfield/type;",
output.toString());
... |
@Override
public void replyComment(ProductCommentReplyReqVO replyVO, Long userId) {
// 校验评论是否存在
validateCommentExists(replyVO.getId());
// 回复评论
productCommentMapper.updateById(new ProductCommentDO().setId(replyVO.getId())
.setReplyTime(LocalDateTime.now()).setReplyUse... | @Test
public void testCommentReply_success() {
// mock 测试
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
productCommentMapper.insert(productComment);
Long productCommentId = productComment.getId();
ProductCommentReplyReqVO replyVO = new ProductComment... |
public boolean onDemandUpdate() {
if (rateLimiter.acquire(burstSize, allowedRatePerMinute)) {
if (!scheduler.isShutdown()) {
scheduler.submit(new Runnable() {
@Override
public void run() {
logger.debug("Executing on-dema... | @Test
public void testOnDemandUpdate() throws Throwable {
assertTrue(replicator.onDemandUpdate());
Thread.sleep(10); // give some time for execution
assertTrue(replicator.onDemandUpdate());
Thread.sleep(1000 * refreshRateSeconds / 2);
assertTrue(replicator.onDemandUpdate());... |
public static long getTimestampMillis(Binary timestampBinary)
{
if (timestampBinary.length() != 12) {
throw new PrestoException(NOT_SUPPORTED, "Parquet timestamp must be 12 bytes, actual " + timestampBinary.length());
}
byte[] bytes = timestampBinary.getBytes();
// littl... | @Test
public void testInvalidBinaryLength()
{
try {
byte[] invalidLengthBinaryTimestamp = new byte[8];
getTimestampMillis(Binary.fromByteArray(invalidLengthBinaryTimestamp));
}
catch (PrestoException e) {
assertEquals(e.getErrorCode(), NOT_SUPPORTED.to... |
private static ClientAuthenticationMethod getClientAuthenticationMethod(
List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
if (metadataAuthMethods == null || metadataAuthMethods
.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
// If ... | @Test
public void buildWhenAuthorizationCodeGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationGrantType(Authori... |
public static String hashpw(String password, String salt) throws IllegalArgumentException {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char) 0;
int rounds, off = 0;
StringBuilder rs = new StringBuilder();
if (salt == null) {
... | @Test
public void testHashpwSaltTooShort() throws IllegalArgumentException {
thrown.expect(IllegalArgumentException.class);
BCrypt.hashpw("foo", "foo");
} |
public Set<String> referencedPackagesMissingFrom(Set<String> definedAndExportedPackages) {
return Sets.difference(referencedPackages(), definedAndExportedPackages).stream()
.filter(pkg -> !pkg.startsWith("java."))
.filter(pkg -> !pkg.equals(com.yahoo.api.annotations.PublicApi.cla... | @Test
void referenced_packages_missing_from_available_packages_are_detected() {
PackageTally tally = new PackageTally(Map.of(), Set.of("p1", "java.util", "com.yahoo.api.annotations", "missing"));
Set<String> missingPackages = tally.referencedPackagesMissingFrom(Set.of("p1"));
assertEquals(Se... |
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFloatingIp(InputStream input) throws IOException {
log.trace(String.format(MESSAGE, "CREATE"));
String inputStr = IOUtils.toString(input, REST_UTF8);
if (!haService.isActive()
... | @Test
public void testCreateFloatingIpWithCreationOperation() {
mockOpenstackRouterAdminService.createFloatingIp(anyObject());
replay(mockOpenstackRouterAdminService);
expect(mockOpenstackHaService.isActive()).andReturn(true).anyTimes();
replay(mockOpenstackHaService);
final... |
public static String toJSONString(Object object) {
if (object == null) {
return null;
}
return JSON_FACADE.toJSONString(object);
} | @Test
public void assertToJSONString() {
Assert.assertNull(JSONUtil.toJSONString(null));
try {
JSONAssert.assertEquals(EXPECTED_FOO_JSON, JSONUtil.toJSONString(EXPECTED_FOO), false);
} catch (JSONException jse) {
throw new RuntimeException(jse);
}
} |
StreamOperatorStateContext build(Logger logger) throws IOException {
final Environment environment =
new SavepointEnvironment.Builder(ctx, executionConfig, maxParallelism)
.setConfiguration(configuration)
.setSubtaskIndex(split.getSplitNumber())
... | @Test(expected = CustomStateBackendFactory.ExpectedException.class)
public void testStateBackendLoading() throws Exception {
Configuration configuration = new Configuration();
configuration.set(
StateBackendOptions.STATE_BACKEND,
CustomStateBackendFactory.class.getCan... |
public static void run(String[] args, Properties properties) {
if (args.length == 0) {
System.err.println("You must specify a classname to launch");
}
// Scan the arguments looking for -s, --server-root=, -P, --properties=
String root = null;
String propertyFile = null;
for ... | @Test
public void testLoaderViaPropertyFile() throws IOException {
Properties properties = new Properties();
properties.put(Loader.INFINISPAN_SERVER_LIB_PATH, String.join(File.pathSeparator, lib1.toString(), lib2.toString(), lib3.toString()));
Path propertyFile = Paths.get(System.getProperty("build... |
public static boolean[] byte2Booleans(byte b) {
boolean[] array = new boolean[8];
for (int i = 7; i >= 0; i--) { //对于byte的每bit进行判定
array[i] = (b & 1) == 1; //判定byte的最后一位是否为1,若为1,则是true;否则是false
b = (byte) (b >> 1); //将byte右移一位
}
return array;
} | @Test
public void byte2Booleans() {
Assert.assertEquals(0, CodecUtils.booleansToByte(null));
Assert.assertEquals(0, CodecUtils.booleansToByte(new boolean[0]));
// 01010101
boolean[] bs = new boolean[] { false, true, false, true, false, true, false, true };
byte b = CodecUtil... |
@Override
public ListConsumerGroupOffsetsResult listConsumerGroupOffsets(Map<String, ListConsumerGroupOffsetsSpec> groupSpecs,
ListConsumerGroupOffsetsOptions options) {
SimpleAdminApiFuture<CoordinatorKey, Map<TopicPartition, OffsetAndMetad... | @Test
public void testListConsumerGroupOffsetsNonRetriableErrors() throws Exception {
// Non-retriable errors throw an exception
final List<Errors> nonRetriableErrors = asList(
Errors.GROUP_AUTHORIZATION_FAILED, Errors.INVALID_GROUP_ID, Errors.GROUP_ID_NOT_FOUND,
Errors.UNKNO... |
public Socket awaitConnection() throws InterruptedException {
return awaitConnection(Long.MAX_VALUE);
} | @Test
public void testConnectEventually() throws Exception {
serverSocket.close();
Thread thread = new Thread();
thread.start();
Socket socket = connector.awaitConnection(2 * DELAY);
assertNull(socket);
Exception lastException = exceptionHandler.awaitConnectionFailed(DELAY);
assertTrue(la... |
public static void scale(File srcImageFile, File destImageFile, float scale) {
BufferedImage image = null;
try {
image = read(srcImageFile);
scale(image, destImageFile, scale);
} finally {
flush(image);
}
} | @Test
@Disabled
public void scalePngTest() {
ImgUtil.scale(FileUtil.file("f:/test/test.png"), FileUtil.file("f:/test/test_result.png"), 0.5f);
} |
public Optional<String> getType(Set<String> streamIds, String field) {
final Map<String, Set<String>> allFieldTypes = this.get(streamIds);
final Set<String> fieldTypes = allFieldTypes.get(field);
return typeFromFieldType(fieldTypes);
} | @Test
void returnsEmptyOptionalIfNoTypesExistForStream() {
final Pair<IndexFieldTypesService, StreamService> services = mockServices(
IndexFieldTypesDTO.create("indexSet1", "stream1", ImmutableSet.of(
FieldTypeDTO.create("somefield", "long")
))
... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof NiciraEncapEthType) {
NiciraEncapEthType that = (NiciraEncapEthType) obj;
return Objects.equals(encapEthType, that.encapEthType);
}
return f... | @Test
public void testEquals() {
final NiciraEncapEthType encapEthType1 = new NiciraEncapEthType(ethType1);
final NiciraEncapEthType sameAsEncapEthType1 = new NiciraEncapEthType(ethType1);
final NiciraEncapEthType encapEthType2 = new NiciraEncapEthType(ethType2);
new EqualsTester().... |
@Override
public ParamCheckResponse checkParamInfoList(List<ParamInfo> paramInfos) {
ParamCheckResponse paramCheckResponse = new ParamCheckResponse();
if (paramInfos == null) {
paramCheckResponse.setSuccess(true);
return paramCheckResponse;
}
for (ParamInfo pa... | @Test
void testCheckEmptyParamInfo() {
ParamInfo paramInfo = new ParamInfo();
ArrayList<ParamInfo> paramInfos = new ArrayList<>();
paramInfos.add(paramInfo);
paramInfos.add(null);
ParamCheckResponse actual = paramChecker.checkParamInfoList(paramInfos);
assertTrue(actu... |
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer)
{
return read(buffer, consumer, 0);
} | @Test
void shouldReadNoExceptionsFromEmptyLog()
{
final ErrorConsumer consumer = mock(ErrorConsumer.class);
assertThat(ErrorLogReader.read(buffer, consumer), is(0));
verifyNoInteractions(consumer);
} |
@Override
public void execute() throws MojoExecutionException {
if (skip) {
getLog().info("Skipped execution of ActiveMQ Broker");
return;
}
addActiveMQSystemProperties();
getLog().info("Loading broker configUri: " + configUri);
if (this.xBeanFileRes... | @Test
public void testDoNotUseXbeanConfigFile () throws Exception {
Mockito.when(this.mockXbeanFileResolver.isXBeanFile("x-config-uri-x")).thenReturn(false);
this.startBrokerMojo.execute();
Mockito.verify(this.mockMavenLog, Mockito.times(0)).debug("configUri before transformation: x-config... |
@Override
public Integer clusterGetSlotForKey(byte[] key) {
RFuture<Integer> f = executorService.readAsync((String)null, StringCodec.INSTANCE, RedisCommands.KEYSLOT, key);
return syncFuture(f);
} | @Test
public void testClusterGetSlotForKey() {
testInCluster(connection -> {
Integer slot = connection.clusterGetSlotForKey("123".getBytes());
assertThat(slot).isNotNull();
});
} |
static Node selectNodeByRequesterAndStrategy(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node) {
// The limit app should not be empty.
String limitApp = rule.getLimitApp();
int strategy = rule.getStrategy();
String origin = context.getOrigin();
if (limitApp.equals(o... | @Test
public void testDefaultLimitAppFlowSelectNode() {
DefaultNode node = mock(DefaultNode.class);
ClusterNode cn = mock(ClusterNode.class);
when(node.getClusterNode()).thenReturn(cn);
Context context = mock(Context.class);
// limitApp: default
FlowRule rule = new F... |
public int getNumRefreshAdminAclsFailedRetrieved() {
return numRefreshAdminAclsFailedRetrieved.value();
} | @Test
public void testRefreshAdminAclsRetrievedFailed() {
long totalBadBefore = metrics.getNumRefreshAdminAclsFailedRetrieved();
badSubCluster.getRefreshAdminAclsFailedRetrieved();
Assert.assertEquals(totalBadBefore + 1,
metrics.getNumRefreshAdminAclsFailedRetrieved());
} |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "{namespace}/{id}")
@Operation(tags = {"Templates"}, summary = "Delete a template")
@ApiResponse(responseCode = "204", description = "On success")
public HttpResponse<Void> delete(
@Parameter(description = "The template namespace") @PathVariable String ... | @Test
void deleteTemplatesByQuery() {
Template template = createTemplate("toDelete", "kestra.test.delete");
client.toBlocking().retrieve(POST("/api/v1/templates", template), String.class);
HttpResponse<BulkResponse> response = client
.toBlocking()
.exchange(DELETE("/... |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
try {
if(containerService.isContainer(file)) {
final Storage.Buckets.Get request ... | @Test
public void testFindBucket() throws Exception {
final Path container = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttributes attributes = new GoogleStorageAttributesFinderFeature(session).find(container);
assertNotSame(PathAttributes.EMP... |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void literalWithTwoAccolades() throws ScanException {
Tokenizer tokenizer = new Tokenizer("%x{y} %a{b} c");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.LITERAL, "%x");
Node t = witness.next = n... |
public RemotingCommand resetOffset(ChannelHandlerContext ctx,
RemotingCommand request) throws RemotingCommandException {
final ResetOffsetRequestHeader requestHeader =
(ResetOffsetRequestHeader) request.decodeCommandCustomHeader(ResetOffsetRequestHeader.class);
logger.info("invoke re... | @Test
public void testResetOffset() throws Exception {
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
RemotingCommand request = mock(RemotingCommand.class);
when(request.getCode()).thenReturn(RequestCode.RESET_CONSUMER_CLIENT_OFFSET);
ResetOffsetBody offsetBody = new ... |
@Override
public void upgrade() {
Map<String, Set<String>> encryptedFieldsByInputType = getEncryptedFieldsByInputType();
if (getMigratedField().equals(encryptedFieldsByInputType)) {
LOG.debug("Migration already completed.");
return;
}
final MongoCollection<D... | @SuppressWarnings("unchecked")
@Test
public void migrateMissingSecret() {
migration.upgrade();
final Document migrated =
collection.find(Filters.eq(FIELD_TITLE, "missing-secret")).first();
assertThat(migrated).isNotNull().satisfies(doc ->
assertThat((Map... |
@Override
public boolean disable(String pluginId) {
return false;
} | @Test
public void testDisable() {
ThreadPoolPlugin plugin = new TestPlugin();
Assert.assertFalse(manager.disable(plugin.getId()));
manager.register(plugin);
Assert.assertFalse(manager.disable(plugin.getId()));
Assert.assertFalse(manager.disable(plugin.getId()));
Ass... |
public NetworkConfig setPort(int port) {
if (port < 0 || port > PORT_MAX) {
throw new IllegalArgumentException("Port out of range: " + port + ". Allowed range [0,65535]");
}
this.port = port;
return this;
} | @Test(expected = IllegalArgumentException.class)
public void testNegativePort() {
int port = -1;
networkConfig.setPort(port);
} |
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
if (schema != null && schema.type() != Schema.Type.BYTES)
throw new DataException("Invalid schema type for ByteArrayConverter: " + schema.type().toString());
if (value != null && !(value instanceof byte... | @Test
public void testFromConnectNull() {
assertNull(converter.fromConnectData(TOPIC, Schema.BYTES_SCHEMA, null));
} |
@Override
@SuppressWarnings("unchecked")
public void forward(ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
if (lambdaContainerHandler == null) {
throw new IllegalStateException("Null container handler in dispatcher");
... | @Test
void forwardRequest_partiallyWrittenResponse_resetsBuffer() throws InvalidRequestEventException {
AwsProxyRequest proxyRequest = new AwsProxyRequestBuilder("/hello", "GET").build();
HttpServletRequest servletRequest = requestReader.readRequest(proxyRequest, null, new MockLambdaContext(), Conta... |
@Override
public boolean useAddressServer() {
return false;
} | @Test
void testUseAddressServer() {
assertFalse(fileConfigMemberLookup.useAddressServer());
} |
@Override
public ExecuteResult execute(final ServiceContext serviceContext, final ConfiguredKsqlPlan plan,
final boolean restoreInProgress) {
try {
final ExecuteResult result = EngineExecutor
.create(primaryContext, serviceContext, plan.getConfig())
.execut... | @Test
public void shouldShowHintWhenFailingToDropTableWithSourceNameWithoutQuotes() {
// Given:
setupKsqlEngineWithSharedRuntimeEnabled();
KsqlEngineTestUtil.execute(
serviceContext,
ksqlEngine,
"create table \"bar\" as select * from test2;",
ksqlConfig,
Collections... |
@Override
public Output run(RunContext runContext) throws Exception {
String taskSpec = runContext.render(this.spec);
try {
Task task = OBJECT_MAPPER.readValue(taskSpec, Task.class);
if (task instanceof TemplatedTask) {
throw new IllegalArgumentException("The ... | @Test
void templatedTemplated() {
RunContext runContext = runContextFactory.of();
TemplatedTask templatedTask = TemplatedTask.builder()
.id("template")
.type(TemplatedTask.class.getName())
.spec("""
type: io.kestra.plugin.core.templating.TemplatedT... |
public static Comparator<StructLike> forType(Types.StructType struct) {
return new StructLikeComparator(struct);
} | @Test
public void testDecimal() {
assertComparesCorrectly(
Comparators.forType(Types.DecimalType.of(5, 7)),
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(0.2));
} |
@Override
public final Iterator<E> iterator() {
throw new UnsupportedOperationException();
} | @Test(dataProvider = "full")
public void iterator(MpscGrowableArrayQueue<Integer> queue) {
assertThrows(UnsupportedOperationException.class, queue::iterator);
} |
@Override
public LeaderElection getResourceManagerLeaderElection() {
return resourceManagerLeaderService.createLeaderElectionService("resource_manager");
} | @Test
public void testResourceManagerLeaderElection() throws Exception {
LeaderContender leaderContender1 = mock(LeaderContender.class);
LeaderContender leaderContender2 = mock(LeaderContender.class);
LeaderElection leaderElection1 = embeddedHaServices.getResourceManagerLeaderElection();
... |
public URI getHttpPublishUri() {
if (httpPublishUri == null) {
final URI defaultHttpUri = getDefaultHttpUri();
LOG.debug("No \"http_publish_uri\" set. Using default <{}>.", defaultHttpUri);
return defaultHttpUri;
} else {
final InetAddress inetAddress = to... | @Test
public void testHttpPublishUriWithCustomScheme() throws RepositoryException, ValidationException {
final Map<String, String> properties = ImmutableMap.of(
"http_publish_uri", "https://example.com:12900/",
"http_enable_tls", "false");
jadConfig.setRepository(new... |
public static <T> List<T> list(boolean isLinked) {
return ListUtil.list(isLinked);
} | @Test
public void listTest3() {
final HashSet<String> set = new LinkedHashSet<>();
set.add("a");
set.add("b");
set.add("c");
final List<String> list1 = CollUtil.list(false, set);
final List<String> list2 = CollUtil.list(true, set);
assertEquals("[a, b, c]", list1.toString());
assertEquals("[a, b, c]",... |
static UBreak create(@Nullable CharSequence label) {
return new UBreak((label == null) ? null : StringName.of(label));
} | @Test
public void equality() {
new EqualsTester()
.addEqualityGroup(UBreak.create(null))
.addEqualityGroup(UBreak.create("foo"))
.addEqualityGroup(UBreak.create("bar"))
.testEquals();
} |
public static int replaceValue(String regex, String replaceBy, boolean caseSensitive, String value, Consumer<? super String> setter) {
if (StringUtils.isBlank(value)) {
return 0;
}
Object[] result = replaceAllWithRegex(value, regex, replaceBy, caseSensitive);
int nbReplaced =... | @Test
public void testReplaceValueWithNullSetterThatGetsCalled() {
Assertions.assertThrows(
NullPointerException.class,
() -> JOrphanUtils.replaceValue("\\d+", "${port}", true, "80", null));
} |
public static SimpleTransform threshold(double min, double max) {
return new SimpleTransform(Operation.threshold,min,max);
} | @Test
public void testThreshold() {
double min = 0.0;
double max = 1.0;
TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.threshold(min, max)),new HashMap<>());
testThresholding(t,min,max);
} |
@Override
public List<String> getUpdateColumns() {
List<SQLUpdateSetItem> updateSetItems = ast.getItems();
List<String> list = new ArrayList<>(updateSetItems.size());
for (SQLUpdateSetItem updateSetItem : updateSetItems) {
SQLExpr expr = updateSetItem.getColumn();
if ... | @Test
public void testGetUpdateColumns() {
// test with normal
String sql = "update t set a = ?, b = ?, c = ?";
SQLStatement sqlStatement = getSQLStatement(sql);
SqlServerUpdateRecognizer recognizer = new SqlServerUpdateRecognizer(sql, sqlStatement);
List<String> updateColum... |
public static Object[] generalize(Object[] objs) {
Object[] dests = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
dests[i] = generalize(objs[i]);
}
return dests;
} | @Test
void testGeneralizePersons() throws Exception {
Object persons = new Person[] {new Person(), new Person()};
Object o = PojoUtils.generalize(persons);
assertTrue(o instanceof Object[]);
assertEquals(((Object[]) o).length, 2);
} |
public static boolean isValidAddress(String input) {
return isValidAddress(input, ADDRESS_LENGTH_IN_HEX);
} | @Test
public void testIsValidAddress() {
assertTrue(isValidAddress(SampleKeys.ADDRESS));
assertTrue(isValidAddress(SampleKeys.ADDRESS_NO_PREFIX));
assertFalse(isValidAddress(""));
assertFalse(isValidAddress(SampleKeys.ADDRESS + 'a'));
assertFalse(isValidAddress(SampleKeys.AD... |
public void addAll(StatsBuckets other) {
checkArgument(boundaries.length == other.boundaries.length,
"boundaries size %s doesn't match with given boundaries size %s", boundaries.length,
other.boundaries.length);
for (int i = 0; i < buckets.length; i++) {
buck... | @Test
public void testAddAll() {
StatsBuckets stats = new StatsBuckets(10, 20, 30);
stats.addValue(1);
stats.addValue(2);
stats.refresh();
StatsBuckets stats2 = new StatsBuckets(10, 20, 30);
stats2.addAll(stats);
stats2.refresh();
assertEquals(stats2.g... |
@SuppressWarnings("FutureReturnValueIgnored")
public void start() {
budgetRefreshExecutor.submit(this::subscribeToRefreshBudget);
} | @Test
public void testScheduledBudgetRefresh() throws InterruptedException {
CountDownLatch redistributeBudgetLatch = new CountDownLatch(1);
Runnable redistributeBudget = redistributeBudgetLatch::countDown;
GetWorkBudgetRefresher budgetRefresher = createBudgetRefresher(redistributeBudget);
budgetRefre... |
public final int size() {
return this.size;
} | @Test
public void testSize() {
this.list.add( this.node1 );
assertThat(this.list.size()).as("LinkedList should have 1 node").isEqualTo(1);
this.list.add( this.node2 );
assertThat(this.list.size()).as("LinkedList should have 2 node").isEqualTo(2);
this.list.add( this.node3 )... |
public static YarnConfiguration getYarnConfiguration(
org.apache.flink.configuration.Configuration flinkConfig) {
final YarnConfiguration yarnConfig = new YarnConfiguration();
for (String key : flinkConfig.keySet()) {
for (String prefix : FLINK_CONFIG_PREFIXES) {
... | @Test
void testGetYarnConfiguration() {
final String flinkPrefix = "flink.yarn.";
final String yarnPrefix = "yarn.";
final String k1 = "brooklyn";
final String v1 = "nets";
final String k2 = "golden.state";
final String v2 = "warriors";
final String k3 = "m... |
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 givenStringWithSurroundingSpaces_parsesIncorrectly() {
DefaultMapEntry cellToExpectedValue = new DefaultMapEntry(" a ", "a");
Schema schema = Schema.builder().addStringField("a_string").addInt64Field("a_long").build();
assertEquals(
cellToExpectedValue.getKey(),
CsvIOP... |
@Override
public void warmUpEncryptedKeys(String... keyNames) throws IOException {
Preconditions.checkArgument(providers.length > 0,
"No providers are configured");
boolean success = false;
IOException e = null;
for (KMSClientProvider provider : providers) {
try {
provider.warmUp... | @Test
public void testWarmUpEncryptedKeysWhenOneProviderSucceeds()
throws Exception {
Configuration conf = new Configuration();
KMSClientProvider p1 = mock(KMSClientProvider.class);
String keyName = "key1";
Mockito.doThrow(new IOException(new AuthorizationException("p1"))).when(p1)
.warm... |
@Override
public String toString() {
return "Result{" + "errorCode=" + code + ", message='" + message + '\'' + ", data=" + data + '}';
} | @Test
void testToString() {
Result<String> result = Result.success("test");
assertEquals("Result{errorCode=0, message='success', data=test}", result.toString());
} |
@Override
public synchronized void close() throws IOException {
mCloser.close();
} | @Test
public void writeWithNullUfsStream() {
Assert.assertThrows(NullPointerException.class,
() -> new UfsFileOutStream(null).close());
} |
@Override
public ScheduledExecutor getScheduledExecutor() {
return internalScheduledExecutor;
} | @Test
void testScheduledExecutorServiceCancelWithFixedDelay() throws InterruptedException {
ScheduledExecutor scheduledExecutor = pekkoRpcService.getScheduledExecutor();
long delay = 10L;
final OneShotLatch futureTask = new OneShotLatch();
final OneShotLatch latch = new OneShotLatc... |
@JsonProperty("type")
public FSTType getFstType() {
return _fstType;
} | @Test
public void withDisabledNull()
throws JsonProcessingException {
String confStr = "{\"disabled\": null}";
FstIndexConfig config = JsonUtils.stringToObject(confStr, FstIndexConfig.class);
assertFalse(config.isDisabled(), "Unexpected disabled");
assertNull(config.getFstType(), "Unexpected ty... |
public static Future execute(ParseContext context, Runnable runnable) {
Future future = null;
ExecutorService executorService = context.get(ExecutorService.class);
if (executorService == null) {
FutureTask task = new FutureTask<>(runnable, null);
Thread thread = new Thre... | @Test
public void testExecuteExecutor() throws Exception {
TikaConfig config = TikaConfig.getDefaultConfig();
ParseContext context = new ParseContext();
context.set(ExecutorService.class, config.getExecutorService());
Future result = ConcurrentUtils.execute(context, () ->
{
... |
static String[] getClassPathElements() {
return System.getProperty("java.class.path", ".").split(System.getProperty("path.separator"));
} | @Test
public void getClassPathElementsTest() {
List<String> classPathElements = Arrays.asList(ResourceHelper.getClassPathElements());
List<String> notJar = classPathElements.stream().filter(elem -> !elem.contains(".jar")).collect(Collectors.toList());
assertThat(notJar.stream().anyMatch(elem... |
public static Expression getExpressionForObject(Object source) {
if (source == null) {
return new NullLiteralExpr();
}
String className = source.getClass().getSimpleName();
switch (className) {
case "String":
return new StringLiteralExpr((String) s... | @Test
void getExpressionForObject() {
String string = "string";
Expression retrieved = CommonCodegenUtils.getExpressionForObject(string);
assertThat(retrieved).isInstanceOf(StringLiteralExpr.class);
assertThat(retrieved.toString()).isEqualTo("\"string\"");
int i = 1;
... |
@Override
public List<DeptDO> getDeptList(Collection<Long> ids) {
if (CollUtil.isEmpty(ids)) {
return Collections.emptyList();
}
return deptMapper.selectBatchIds(ids);
} | @Test
public void testGetDeptList_ids() {
// mock 数据
DeptDO deptDO01 = randomPojo(DeptDO.class);
deptMapper.insert(deptDO01);
DeptDO deptDO02 = randomPojo(DeptDO.class);
deptMapper.insert(deptDO02);
// 准备参数
List<Long> ids = Arrays.asList(deptDO01.getId(), dept... |
@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 testDisableReplOutput() 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",... |
void precheckMaxResultLimitOnLocalPartitions(String mapName) {
// check if feature is enabled
if (!isPreCheckEnabled) {
return;
}
// limit number of local partitions to check to keep runtime constant
PartitionIdSet localPartitions = mapServiceContext.getCachedOwnedPa... | @Test(expected = QueryResultSizeExceededException.class)
public void testLocalPreCheckEnabledWitTwoPartitionsOverLimit() {
int[] partitionsSizes = {1062, 1063};
populatePartitions(partitionsSizes);
initMocksWithConfiguration(200000, 2);
limiter.precheckMaxResultLimitOnLocalPartition... |
public static Gson instance() {
return SingletonHolder.INSTANCE;
} | @Test
void successfullyDeserializesArtifactStoreBecauseGoCipherIsNeverUsed() {
assertDoesNotThrow(() -> {
final ArtifactStore store = Serialization.instance().fromJson("{" +
"\"id\": \"store\"," +
"\"pluginId\": \"plugin\"," +
"\"config... |
public Duration getServerTimeoutOrThrow() {
// readTimeout = DOWNSTREAM_OVERHEAD + serverTimeout
TimeBudget serverBudget = readBudget().withReserved(DOWNSTREAM_OVERHEAD);
if (serverBudget.timeLeft().get().compareTo(MIN_SERVER_TIMEOUT) < 0)
throw new UncheckedTimeoutException("Timed o... | @Test
public void justTooLittleTime() {
clock.advance(originalTimeout.minus(MINIMUM_TIME_LEFT).plus(Duration.ofMillis(1)));
try {
timeouts.getServerTimeoutOrThrow();
fail();
} catch (UncheckedTimeoutException e) {
assertEquals("Timed out after PT3S", e.get... |
public boolean checkOrigin(String origin) {
try {
return CorsUtils.isValidOrigin(origin, zConf);
} catch (UnknownHostException | URISyntaxException e) {
LOG.error(e.toString(), e);
}
return false;
} | @Test
void checkInvalidOrigin() {
assertFalse(notebookServer.checkOrigin("http://evillocalhost:8080"));
} |
@VisibleForTesting
static String generateFile(QualifiedVersion version, String template, List<ChangelogEntry> entries) throws IOException {
final List<String> priorVersions = new ArrayList<>();
if (version.minor() > 0) {
final int major = version.major();
for (int minor = ve... | @Test
public void generateFile_withNoHighlights_rendersCorrectMarkup() throws Exception {
// given:
final String template = getResource("/templates/release-highlights.asciidoc");
final String expectedOutput = getResource(
"/org/elasticsearch/gradle/internal/release/ReleaseHighlig... |
@Override
public void commit(Collection<CommitRequest<FileSinkCommittable>> requests)
throws IOException, InterruptedException {
for (CommitRequest<FileSinkCommittable> request : requests) {
FileSinkCommittable committable = request.getCommittable();
if (committable.hasPe... | @Test
void testCommitMultiple() throws Exception {
StubBucketWriter stubBucketWriter = new StubBucketWriter();
FileCommitter fileCommitter = new FileCommitter(stubBucketWriter);
Collection<CommitRequest<FileSinkCommittable>> committables =
Stream.of(
... |
public void onClusterCheck() {
if ( clusteringCheck != null ) {
boolean dis = !clusteringCheck.isChecked();
if ( clusterParameterTree != null ) {
clusterParameterTree.setDisabled( dis );
}
if ( clusterParameterDescriptionLabel != null ) {
clusterParameterDescriptionLabel.setD... | @Test
public void testOnClusterCheck() throws Exception {
} |
@Override
public Page getOutput()
{
if (finished) {
return null;
}
// process unfinished work if one exists
if (unfinishedWork != null) {
boolean workDone = unfinishedWork.process();
aggregationBuilder.updateMemory();
if (!workDone... | @Test(dataProvider = "dataType")
public void testMemoryReservationYield(Type type)
{
List<Page> input = createPagesWithDistinctHashKeys(type, 6_000, 600);
OperatorFactory operatorFactory = new HashAggregationOperatorFactory(
0,
new PlanNodeId("test"),
... |
public static ParsedCommand parse(
// CHECKSTYLE_RULES.ON: CyclomaticComplexity
final String sql, final Map<String, String> variables) {
validateSupportedStatementType(sql);
final String substituted;
try {
substituted = VariableSubstitutor.substitute(KSQL_PARSER.parse(sql).get(0),... | @Test
public void shouldParseCreateConnectorStatementWithVariables() {
// Given:
final String createConnector = "CREATE SOURCE CONNECTOR ${name} WITH(\n"
+ " \"connector.class\"='io.confluent.connect.jdbc.JdbcSourceConnector',\n"
+ " \"connection.url\"=${url},\n"
+ " \"mode\"=... |
static String removeReplicasFromConfig(String throttleConfig, Set<String> replicas) {
List<String> throttles = new ArrayList<>(Arrays.asList(throttleConfig.split(",")));
throttles.removeIf(replicas::contains);
return String.join(",", throttles);
} | @Test
public void testRemoveReplicasFromConfigTest() {
Set<String> replicas = new LinkedHashSet<>();
replicas.add("foo");
replicas.add("bar");
replicas.add("baz");
String throttleConfig = "foo,bar,qux,qaz,baz";
String result = ReplicationThrottleHelper.removeReplicasFromConfig(throttleConfig, ... |
public static <K, V> AsMap<K, V> asMap() {
return new AsMap<>(false);
} | @Test
@Category({ValidatesRunner.class})
public void testEmptyMapSideInputWithNonDeterministicKeyCoder() throws Exception {
final PCollectionView<Map<String, Integer>> view =
pipeline
.apply(
"CreateEmptyView",
Create.empty(KvCoder.of(new NonDeterministicStri... |
static java.sql.Time parseSqlTime(final String value) {
try {
// JDK format in Time.valueOf is compatible with DATE_FORMAT
return Time.valueOf(value);
} catch (IllegalArgumentException e) {
return throwRuntimeParseException(value, new ParseException(value, 0), SQL_TIM... | @Test
public void testTime() {
long now = System.currentTimeMillis();
Time time1 = new Time(now);
Time time2 = DateHelper.parseSqlTime(time1.toString());
assertSqlTimesEqual(time1, time2);
} |
@SuppressWarnings("unchecked")
@Override
public void configure(Map<String, ?> configs) throws KafkaException {
if (sslEngineFactory != null) {
throw new IllegalStateException("SslFactory was already configured.");
}
this.endpointIdentification = (String) configs.get(SslConfig... | @Test
public void testUsedConfigs() throws IOException, GeneralSecurityException {
Map<String, Object> serverSslConfig = sslConfigsBuilder(ConnectionMode.SERVER)
.createNewTrustStore(TestUtils.tempFile("truststore", ".jks"))
.useClientCert(false)
.build();
... |
@Override
public boolean retryRequest(
HttpRequest request, IOException exception, int execCount, HttpContext context) {
if (execCount > maxRetries) {
// Do not retry if over max retries
return false;
}
if (nonRetriableExceptions.contains(exception.getClass())) {
return false;
... | @Test
public void basicRetry() {
BasicHttpResponse response503 = new BasicHttpResponse(503, "Oopsie");
assertThat(retryStrategy.retryRequest(response503, 3, null)).isTrue();
BasicHttpResponse response429 = new BasicHttpResponse(429, "Oopsie");
assertThat(retryStrategy.retryRequest(response429, 3, nul... |
@Bean
public BulkheadRegistry bulkheadRegistry(
BulkheadConfigurationProperties bulkheadConfigurationProperties,
EventConsumerRegistry<BulkheadEvent> bulkheadEventConsumerRegistry,
RegistryEventConsumer<Bulkhead> bulkheadRegistryEventConsumer,
@Qualifier("compositeBulkheadCustomizer"... | @Test
public void testCreateBulkHeadRegistryWithUnknownConfig() {
BulkheadConfigurationProperties bulkheadConfigurationProperties = new BulkheadConfigurationProperties();
io.github.resilience4j.common.bulkhead.configuration.CommonBulkheadConfigurationProperties.InstanceProperties instanceProperties... |
@Injection( name = "SPECIFY_DATABASE_FIELDS" )
public void metaSetSpecifyDatabaseFields( String value ) {
setSpecifyFields( "Y".equalsIgnoreCase( value ) );
} | @Test
public void metaSetSpecifyDatabaseFields() {
TableOutputMeta tableOutputMeta = new TableOutputMeta();
tableOutputMeta.metaSetSpecifyDatabaseFields( "Y" );
assertTrue( tableOutputMeta.specifyFields() );
tableOutputMeta.metaSetSpecifyDatabaseFields( "N" );
assertFalse( tableOutputMeta.specifyF... |
public PackageRevision getLatestRevision(String pluginId, final com.thoughtworks.go.plugin.api.material.packagerepository.PackageConfiguration packageConfiguration, final RepositoryConfiguration repositoryConfiguration) {
return pluginRequestHelper.submitRequest(pluginId, REQUEST_LATEST_REVISION, new DefaultPlu... | @Test
public void shouldTalkToPluginToGetLatestModification() throws Exception {
String expectedRequestBody = "{\"repository-configuration\":{\"key-one\":{\"value\":\"value-one\"},\"key-two\":{\"value\":\"value-two\"}}," +
"\"package-configuration\":{\"key-three\":{\"value\":\"value-three\"}... |
public static FlinkPod loadPodFromTemplateFile(
FlinkKubeClient kubeClient, File podTemplateFile, String mainContainerName) {
final KubernetesPod pod = kubeClient.loadPodFromTemplateFile(podTemplateFile);
final List<Container> otherContainers = new ArrayList<>();
Container mainContai... | @Test
void testLoadPodFromTemplateAndCheckVolumes() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtil... |
public ShardingSphereDistributionTransactionManager getTransactionManager(final TransactionType transactionType) {
if (TransactionType.LOCAL != transactionType) {
ShardingSpherePreconditions.checkNotNull(distributionTransactionManager, () -> new TransactionManagerNotFoundException(transactionType));... | @Test
void assertGetEngine() {
assertThat(transactionManagerEngine.getTransactionManager(TransactionType.XA), instanceOf(ShardingSphereTransactionManagerFixture.class));
} |
public static String getMtLvESS( int mtLv ) {
// MtLvESS = Method Level External Shift String
//
if ( mtLv < 0 ) return "?";
//
String Result = "";
//
// String LvS = ". ";
String LvS = ".";
//
for ( int K = 1; K <= mtLv; K ++ ) {
//
Result = Result + LvS;
}
//
return Result;
} | @Test
public void testgetMtLvESS() throws Exception {
//
assertEquals( "?", BTools.getMtLvESS( -5 ) );
assertEquals( "", BTools.getMtLvESS( 0 ) );
assertEquals( "...", BTools.getMtLvESS( 3 ) );
//
} |
static Result coerceUserList(
final Collection<Expression> expressions,
final ExpressionTypeManager typeManager
) {
return coerceUserList(expressions, typeManager, Collections.emptyMap());
} | @Test
public void shouldNotCoerceMapOfIncompatibleValueLiterals() {
// Given:
final ImmutableList<Expression> expressions = ImmutableList.of(
new CreateMapExpression(
ImmutableMap.of(
new IntegerLiteral(10),
new IntegerLiteral(289476)
)
)... |
@Override
public boolean test(final String functionName) {
if (functionName == null
|| functionName.trim().isEmpty()
|| JAVA_RESERVED_WORDS.contains(functionName.toLowerCase())
|| KSQL_RESERVED_WORDS.contains(functionName.toLowerCase())) {
return false;
}
return isValidJavaId... | @Test
public void shouldAllowValidJavaIdentifiers() {
assertTrue(validator.test("foo"));
assertTrue(validator.test("$foo"));
assertTrue(validator.test("f1_b"));
assertTrue(validator.test("__blah"));
} |
@Override
public boolean match(Message msg, StreamRule rule) {
if (msg.getField(rule.getField()) == null)
return rule.getInverted();
try {
final Pattern pattern = patternCache.get(rule.getValue());
final CharSequence charSequence = new InterruptibleCharSequence(m... | @Test
public void testSuccessfulInvertedMatch() {
StreamRule rule = getSampleRule();
rule.setValue("^foo");
rule.setInverted(true);
Message msg = getSampleMessage();
msg.addField("something", "zomg");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(... |
public final Logger getLogger(final Class<?> clazz) {
return getLogger(clazz.getName());
} | @Test
public void testMultiLevel() {
Logger wxyz = lc.getLogger("w.x.y.z");
LoggerTestHelper.assertNameEquals(wxyz, "w.x.y.z");
LoggerTestHelper.assertLevels(null, wxyz, Level.DEBUG);
Logger wx = lc.getLogger("w.x");
wx.setLevel(Level.INFO);
LoggerTestHelper.assertNa... |
@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 shouldFormatDecimal() {
assertThat(DEFAULT.format(DecimalUtil.builder(2, 1).build()), is("DECIMAL(2, 1)"));
assertThat(STRICT.format(DecimalUtil.builder(2, 1).build()), is("DECIMAL(2, 1)"));
} |
@Override
public PMML_MODEL getPMMLModelType() {
return PMML_MODEL_TYPE;
} | @Test
void getPMMLModelType() {
assertThat(PROVIDER.getPMMLModelType()).isEqualTo(PMML_MODEL.TREE_MODEL);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.