focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
static Properties resolveConsumerProperties(Map<String, String> options, Object keySchema, Object valueSchema) {
Properties properties = from(options);
withSerdeConsumerProperties(true, options, keySchema, properties);
withSerdeConsumerProperties(false, options, valueSchema, properties);
... | @Test
public void test_consumerProperties_json() {
// key
assertThat(resolveConsumerProperties(Map.of(OPTION_KEY_FORMAT, JSON_FLAT_FORMAT)))
.containsExactlyEntriesOf(Map.of(KEY_DESERIALIZER, ByteArrayDeserializer.class.getCanonicalName()));
// value
assertThat(resol... |
boolean dropDatabase(@NotNull String dbName) throws TException {
client.drop_database(dbName, true, true);
return true;
} | @Test
public void dropNonExistingDb() {
Throwable exception = Assertions.assertThrows(NoSuchObjectException.class,
() -> client.dropDatabase("WhatIsThisDatabase"));
} |
public void runExtractor(Message msg) {
try(final Timer.Context ignored = completeTimer.time()) {
final String field;
try (final Timer.Context ignored2 = conditionTimer.time()) {
// We can only work on Strings.
if (!(msg.getField(sourceField) instanceof St... | @Test
public void testRunExtractorCheckSourceValueIsString() throws Exception {
final TestExtractor extractor = new TestExtractor.Builder()
.sourceField("a_field")
.build();
// Extractor should not run for source field values that are not strings!
final Messa... |
public static IpPrefix valueOf(int address, int prefixLength) {
return new IpPrefix(IpAddress.valueOf(address), prefixLength);
} | @Test(expected = IllegalArgumentException.class)
public void testInvalidValueOfIntegerNegativePrefixLengthIPv4() {
IpPrefix ipPrefix;
ipPrefix = IpPrefix.valueOf(0x01020304, -1);
} |
@Override
public StringBuffer format(Object obj, StringBuffer result, FieldPosition pos) {
return format.format(toArgs((Attributes) obj), result, pos);
} | @Test
public void testFormat() {
Attributes attrs = new Attributes();
attrs.setString(Tag.ImageType, VR.CS, "ORIGINAL", "PRIMARY", "AXIAL");
attrs.setString(Tag.StudyDate, VR.DA, "20111012");
attrs.setString(Tag.StudyTime, VR.TM, "0930");
attrs.setString(Tag.StudyInstanceUID,... |
@Override
public boolean validate(Path path, ResourceContext context) {
// explicitly call a method not depending on LinkResourceService
return validate(path);
} | @Test
public void testLessThanLatency() {
sut = new LatencyConstraint(Duration.of(10, ChronoUnit.NANOS));
assertThat(sut.validate(path, resourceContext), is(true));
} |
public static Integer size(Object value) {
if (value != null) {
if (value instanceof Collection<?> collection) {
return collection.size();
} else if (value instanceof Map<?, ?> map) {
return map.size();
} else if (value instanceof Object[] arra... | @Test
public void testSize() {
Map<String, Object> map = new HashMap<>();
map.put("foo", 123);
map.put("bar", 456);
assertEquals(2, CollectionHelper.size(map).intValue());
String[] array = new String[] { "Claus", "Willem" };
assertEquals(2, CollectionHelper.size(arr... |
public RequestFuture requestFuture(Request request) throws NacosException {
int retryTimes = 0;
long start = System.currentTimeMillis();
Exception exceptionToThrow = null;
while (retryTimes <= rpcClientConfig.retryTimes() && System.currentTimeMillis() < start + rpcClientConfig
... | @Test
void testRequestFutureWhenClientAlreadyShutDownThenThrowException() throws NacosException {
assertThrows(NacosException.class, () -> {
rpcClient.rpcClientStatus.set(RpcClientStatus.SHUTDOWN);
rpcClient.currentConnection = connection;
rpcClient.requestFuture(null);
... |
public SuperModelConfigProvider getSuperModel() {
return model;
} | @Test
public void test_lb_config_simple() {
LbServicesConfig.Builder lb = new LbServicesConfig.Builder();
handler.getSuperModel().getConfig(lb);
LbServicesConfig lbc = new LbServicesConfig(lb);
assertEquals(1, lbc.tenants().size());
assertEquals(1, lbc.tenants("a").applicatio... |
public Optional<EndpointCertificateMetadata> readEndpointCertificateMetadata(ApplicationId application) {
try {
Optional<byte[]> data = curator.getData(endpointCertificateMetadataPathOf(application));
if (data.isEmpty() || data.get().length == 0) return Optional.empty();
Slim... | @Test
public void reads_object_format() {
curator.set(endpointCertificateMetadataPath,
"{\"keyName\": \"vespa.tlskeys.tenant1--app1-key\", \"certName\":\"vespa.tlskeys.tenant1--app1-cert\", \"version\": 0}"
.getBytes());
// Read from zk and verify cert and ke... |
@Override
public void dropRuleItemConfiguration(final DropRuleItemEvent event, final MaskRuleConfiguration currentRuleConfig) {
currentRuleConfig.getMaskAlgorithms().remove(((DropNamedRuleItemEvent) event).getItemName());
} | @Test
void assertDropRuleItemConfiguration() {
MaskRuleConfiguration currentRuleConfig = new MaskRuleConfiguration(Collections.emptyList(), new HashMap<>(Collections.singletonMap("type: TEST", mock(AlgorithmConfiguration.class))));
new MaskAlgorithmChangedProcessor().dropRuleItemConfiguration(new Dr... |
public void load() {
for (NextWordsContainer container : mStorage.loadStoredNextWords()) {
if (BuildConfig.DEBUG) Log.d(TAG, "Loaded " + container);
mNextWordMap.put(container.word, container);
}
} | @Test
public void testDoesNotLearnIfNotNotifying() throws Exception {
mNextWordDictionaryUnderTest.load();
assertHasNextWordsForWord(false, mNextWordDictionaryUnderTest, "hello");
assertHasNextWordsForWord(false, mNextWordDictionaryUnderTest, "menny");
assertHasNextWordsForWord(false, mNextWordDictio... |
public static void mergeMap(boolean decrypt, Map<String, Object> config) {
merge(decrypt, config);
} | @Test(expected = RuntimeException.class)
public void testMap_key_keyMustBeString() {
Map<String, Object> testMap = new HashMap<>();
testMap.put("${TEST.double: 1.1}", "value");
CentralizedManagement.mergeMap(true, testMap);
} |
public BeamFnApi.InstructionResponse.Builder processBundle(BeamFnApi.InstructionRequest request)
throws Exception {
BeamFnApi.ProcessBundleResponse.Builder response = BeamFnApi.ProcessBundleResponse.newBuilder();
BundleProcessor bundleProcessor =
bundleProcessorCache.get(
request,
... | @Test
public void testTimerRegistrationsFailIfNoTimerApiServiceDescriptorSpecified() throws Exception {
BeamFnApi.ProcessBundleDescriptor processBundleDescriptor =
BeamFnApi.ProcessBundleDescriptor.newBuilder()
.putTransforms(
"2L",
RunnerApi.PTransform.newBuild... |
@Operation(summary = "queryProjectListPaging", description = "QUERY_PROJECT_LIST_PAGING_NOTES")
@Parameters({
@Parameter(name = "searchVal", description = "SEARCH_VAL", schema = @Schema(implementation = String.class)),
@Parameter(name = "pageSize", description = "PAGE_SIZE", required = true,... | @Test
public void testQueryProjectListPaging() {
int pageNo = 1;
int pageSize = 10;
String searchVal = "";
Result result = Result.success(new PageInfo<Project>(1, 10));
Mockito.when(projectService.queryProjectListPaging(user, pageSize, pageNo, searchVal)).thenReturn(result)... |
@Override
public <R> HoodieData<HoodieRecord<R>> tagLocation(
HoodieData<HoodieRecord<R>> records, HoodieEngineContext context,
HoodieTable hoodieTable) {
return HoodieJavaRDD.of(HoodieJavaRDD.getJavaRDD(records)
.mapPartitionsWithIndex(locationTagFunction(hoodieTable.getMetaClient()), true));... | @Test
public void testSmallBatchSize() throws Exception {
final String newCommitTime = "001";
final int numRecords = 10;
List<HoodieRecord> records = dataGen.generateInserts(newCommitTime, numRecords);
JavaRDD<HoodieRecord> writeRecords = jsc().parallelize(records, 1);
// Load to memory
Hoodi... |
ClassicGroup getOrMaybeCreateClassicGroup(
String groupId,
boolean createIfNotExists
) throws GroupIdNotFoundException {
Group group = groups.get(groupId);
if (group == null && !createIfNotExists) {
throw new GroupIdNotFoundException(String.format("Classic group %s not f... | @Test
public void testStaticMemberRejoinWithLeaderIdAndUnexpectedDeadGroup() throws Exception {
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.build();
GroupMetadataManagerTestContext.RebalanceResult rebalanceResult = context.staticMembersJoinAn... |
@Override
public String create() {
return UuidFactoryImpl.INSTANCE.create();
} | @Test
public void create_different_uuids() {
// this test is not enough to ensure that generated strings are unique,
// but it still does a simple and stupid verification
assertThat(underTest.create()).isNotEqualTo(underTest.create());
} |
public Integer put(FileInStream is) {
int id = mCounter.incrementAndGet();
mInStreamCache.put(id, is);
return id;
} | @Test
public void expiration() throws Exception {
StreamCache streamCache = new StreamCache(0);
FileInStream is = mock(FileInStream.class);
FileOutStream os = mock(FileOutStream.class);
streamCache.put(is);
streamCache.put(os);
verify(is).close();
verify(os).close();
} |
public static <T> List<T> emptyOnNull(List<T> list) {
return list == null ? new ArrayList<>() : list;
} | @Test
void emptyOnNull() {
var list = ListUtils.emptyOnNull(null);
assertThat(list, notNullValue());
assertThat(list, empty());
list = ListUtils.emptyOnNull(List.of("1"));
assertThat(list, notNullValue());
assertThat(list.size(), is(1));
} |
public static JsonAsserter with(String json) {
return new JsonAsserterImpl(JsonPath.parse(json).json());
} | @Test
public void ends_with_evalueates() throws Exception {
with(JSON).assertThat("$.store.book[0].category", endsWith("nce"));
} |
static boolean canUpdate(int transactionLogLayer, int transactionLogIndex, int entryInfoLayer, int entryInfoIndex) {
if (transactionLogLayer == entryInfoLayer) {
// Must make sure to not update beyond the current index
if (transactionLogIndex >= entryInfoIndex) {
return t... | @DisplayName("Tests that can update records on the same layer")
@Test
void testCanUpdateSameLayer() {
assertTrue(TransactionLog.canUpdate(0, 10, 0, 1));
assertTrue(TransactionLog.canUpdate(0, 10, 0, 10));
assertFalse(TransactionLog.canUpdate(0, 10, 0, 11));
} |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMap("containsAtLeast", k0, v0, rest));
} | @Test
public void containsAtLeastMissingKey() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1, "feb", 2);
expectFailureWhenTestingThat(actual).containsAtLeast("jan", 1, "march", 3);
assertFailureKeys(
"missing keys",
"for key",
"expected value",
"---",
... |
public static Schema select(Schema schema, Set<Integer> fieldIds) {
Preconditions.checkNotNull(schema, "Schema cannot be null");
Types.StructType result = select(schema.asStruct(), fieldIds);
if (Objects.equals(schema.asStruct(), result)) {
return schema;
} else if (result != null) {
if (sc... | @Test
public void testSelect() {
Schema schema =
new Schema(
Lists.newArrayList(
required(10, "a", Types.IntegerType.get()),
required(11, "A", Types.IntegerType.get()),
required(
12,
"someStruct",
... |
public synchronized static MetricRegistry setDefault(String name) {
final MetricRegistry registry = getOrCreate(name);
return setDefault(name, registry);
} | @Test
public void errorsWhenDefaultAlreadySet() {
SharedMetricRegistries.setDefault("foobah");
exception.expect(IllegalStateException.class);
exception.expectMessage("Default metric registry name is already set.");
SharedMetricRegistries.setDefault("borg");
} |
@Override
public void execute(Exchange exchange) throws SmppException {
SubmitMulti[] submitMulties = createSubmitMulti(exchange);
List<SubmitMultiResult> results = new ArrayList<>(submitMulties.length);
for (SubmitMulti submitMulti : submitMulties) {
SubmitMultiResult result;
... | @Test
public void bodyWithSMPP8bitDataCodingNotModified() throws Exception {
final byte dataCoding = (byte) 0x04; /* SMPP 8-bit */
byte[] body = { (byte) 0xFF, 'A', 'B', (byte) 0x00, (byte) 0xFF, (byte) 0x7F, 'C', (byte) 0xFF };
Exchange exchange = new DefaultExchange(new DefaultCamelContex... |
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 buildWhenCustomGrantAllAttributesProvidedThenAllAttributesAreSet() {
AuthorizationGrantType customGrantType = new AuthorizationGrantType("CUSTOM");
// @formatter:off
ClientRegistration registration = ClientRegistration
.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clien... |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
public GpgInfo get() {
return new GpgInfo(this.gpgGenerator.getGPGContext());
} | @Test
public void testGetGPG() throws JSONException, Exception {
WebResource r = resource();
JSONObject json = r.path("ws").path("v1").path("gpg")
.accept(MediaType.APPLICATION_JSON).get(JSONObject.class);
assertNotNull(json);
} |
public static boolean isIPv4Address(final String input) {
return IPV4_PATTERN.matcher(input).matches();
} | @Test
public void isIPv4Address() {
assertThat(NetAddressValidatorUtil.isIPv4Address("192.168.1.2")).isTrue();
assertThat(NetAddressValidatorUtil.isIPv4Address("127.0.0.1")).isTrue();
assertThat(NetAddressValidatorUtil.isIPv4Address("999.999.999.999")).isFalse();
} |
public Pattern toRegex() {
String prefix = (this.pattern.startsWith("*") ? ".*" : "");
String suffix = (this.pattern.endsWith("*") ? ".*" : "");
String regex = Arrays.stream(this.pattern.split("\\*"))
.filter(s -> !s.isEmpty())
.map(Pattern::quote)
... | @Test
public void testToRegex() {
ResourcePatternDescriber describer = new ResourcePatternDescriber(
"META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector", null);
Assertions.assertEquals(
"\\QMETA-INF/dubbo/internal/org.apache.dubbo.common.exte... |
public void clear() {
channelCache.invalidateAll();
} | @Test
public void testClear() throws InterruptedException {
String channelName = "existingChannel";
CountDownLatch notifyWhenChannelClosed = new CountDownLatch(1);
cache =
ChannelCache.forTesting(
ignored -> newChannel(channelName), notifyWhenChannelClosed::countDown);
WindmillServ... |
@Override
public boolean hasSameDbVendor() {
Optional<String> registeredDbVendor = metadataIndex.getDbVendor();
return registeredDbVendor.isPresent() && registeredDbVendor.get().equals(getDbVendor());
} | @Test
public void hasSameDbVendor_is_false_if_values_dont_match() {
prepareDb("mssql");
prepareEs("postgres");
assertThat(underTest.hasSameDbVendor()).isFalse();
} |
protected boolean canSkipBadReplayedJournal(Throwable t) {
if (Config.metadata_enable_recovery_mode) {
LOG.warn("skip journal load failure because cluster is in recovery mode");
return true;
}
try {
for (String idStr : Config.metadata_journal_skip_bad_journal... | @Test
public void testCanSkipBadReplayedJournal() {
boolean originVal = Config.metadata_journal_ignore_replay_failure;
Config.metadata_journal_ignore_replay_failure = false;
// when recover_on_load_journal_failed is false, the failure of every operation type can not be skipped.
Asse... |
public static String toJson(SnapshotRef ref) {
return toJson(ref, false);
} | @Test
public void testTagToJsonDefault() {
String json = "{\"snapshot-id\":1,\"type\":\"tag\"}";
SnapshotRef ref = SnapshotRef.tagBuilder(1L).build();
assertThat(SnapshotRefParser.toJson(ref))
.as("Should be able to serialize default tag")
.isEqualTo(json);
} |
@Override
public boolean accept(ProcessingEnvironment processingEnv, DeclaredType type) {
Elements elements = processingEnv.getElementUtils();
TypeElement mapTypeElement = elements.getTypeElement(Map.class.getTypeName());
TypeMirror mapType = mapTypeElement.asType();
Types types = pr... | @Test
void testAccept() {
assertTrue(builder.accept(processingEnv, stringsField.asType()));
assertTrue(builder.accept(processingEnv, colorsField.asType()));
assertTrue(builder.accept(processingEnv, primitiveTypeModelsField.asType()));
assertTrue(builder.accept(processingEnv, modelsFi... |
private ConsumerToken generateConsumerToken(Consumer consumer, Date expires) {
long consumerId = consumer.getId();
String createdBy = userInfoHolder.getUser().getUserId();
Date createdTime = new Date();
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(consumerId);
... | @Test
public void testGenerateConsumerToken() throws Exception {
String someConsumerAppId = "100003171";
Date generationTime = new GregorianCalendar(2016, Calendar.AUGUST, 9, 12, 10, 50).getTime();
String tokenSalt = "apollo";
String expectedToken = "151067a53d08d70de161fa06b455623741877ce2f019f6e3018... |
public static TransformExecutorService parallel(ExecutorService executor) {
return new ParallelTransformExecutor(executor);
} | @Test
public void parallelRejectedShutdownSucceeds() {
@SuppressWarnings("unchecked")
DirectTransformExecutor<Object> first = mock(DirectTransformExecutor.class);
TransformExecutorService parallel = TransformExecutorServices.parallel(executorService);
executorService.shutdown();
parallel.shutdown... |
public static Builder newBuilder() {
return new Builder();
} | @Test
public void decreaseSmoothing() {
VegasLimit limit = VegasLimit.newBuilder()
.decrease(current -> current / 2)
.smoothing(0.5)
.initialLimit(100)
.maxConcurrency(200)
.build();
// Pick up first min-rtt
limit.onSample(... |
public static <NodeT, EdgeT> Set<NodeT> reachableNodes(
Network<NodeT, EdgeT> network, Set<NodeT> startNodes, Set<NodeT> endNodes) {
Set<NodeT> visitedNodes = new HashSet<>();
Queue<NodeT> queuedNodes = new ArrayDeque<>();
queuedNodes.addAll(startNodes);
// Perform a breadth-first traversal rooted... | @Test
public void testReachableNodesWithEmptyNetwork() {
assertThat(
Networks.reachableNodes(
createEmptyNetwork(), Collections.emptySet(), Collections.emptySet()),
empty());
} |
@Override
protected boolean isStepCompleted(@NonNull Context context) {
return isContactsPermComplete(context) && isNotificationPermComplete(context);
} | @Test
public void testKeyboardEnabledAndDefaultButDictionaryDisabled() {
final String flatASKComponent =
new ComponentName(BuildConfig.APPLICATION_ID, SoftKeyboard.class.getName())
.flattenToString();
Settings.Secure.putString(
getApplicationContext().getContentResolver(),
... |
static ColumnExtractor create(final Column column) {
final int index = column.index();
Preconditions.checkArgument(index >= 0, "negative index: " + index);
return column.namespace() == Namespace.KEY
? new KeyColumnExtractor(index)
: new ValueColumnExtractor(index);
} | @Test
public void shouldExtractWindowedKeyColumn() {
// Given:
when(column.namespace()).thenReturn(Namespace.KEY);
when(column.index()).thenReturn(0);
when(key.get(0)).thenReturn("some value");
final ColumnExtractor extractor = TimestampColumnExtractors.create(column);
// When:
final Ob... |
public Result parse(final String string) throws DateNotParsableException {
return this.parse(string, new Date());
} | @Test
public void testUTCTZ() throws Exception {
NaturalDateParser.Result today = naturalDateParserUtc.parse("today");
assertThat(today.getFrom()).as("From should not be null").isNotNull();
assertThat(today.getTo()).as("To should not be null").isNotNull();
assertThat(today.getDateTim... |
public ResourceMethodDescriptor process(final ServerResourceContext context)
{
String path = context.getRequestURI().getRawPath();
if (path.length() < 2)
{
throw new RoutingException(HttpStatus.S_404_NOT_FOUND.getCode());
}
if (path.charAt(0) == '/')
{
path = path.substring(1);
... | @Test
public void failsOnRootResourceNotFound() throws URISyntaxException
{
final TestSetup setup = new TestSetup();
final RestLiRouter router = setup._router;
final ServerResourceContext context = setup._context;
doReturn(new URI("/root")).when(context).getRequestURI();
final RoutingException... |
@Override
public void execute() {
DescribeTableResponse result
= ddbClient.describeTable(DescribeTableRequest.builder().tableName(determineTableName()).build());
Message msg = getMessageForResponse(exchange);
msg.setHeader(Ddb2Constants.TABLE_NAME, result.table().tableName()... | @Test
public void testExecute() {
command.execute();
List<KeySchemaElement> keySchema = new ArrayList<>();
keySchema.add(KeySchemaElement.builder().attributeName("name").build());
assertEquals("FULL_DESCRIBE_TABLE", ddbClient.describeTableRequest.tableName());
assertEquals("F... |
public static CsvReader getReader(CsvReadConfig config) {
return new CsvReader(config);
} | @Test
public void readTest2() {
CsvReader reader = CsvUtil.getReader();
reader.read(FileUtil.getUtf8Reader("test.csv"), (csvRow)-> {
// 只有一行,所以直接判断
assertEquals("sss,sss", csvRow.get(0));
assertEquals("姓名", csvRow.get(1));
assertEquals("性别", csvRow.get(2));
assertEquals("关注\"对象\"", csvRow.get(3));
... |
public ScheduledExecutorService build() {
final InstrumentedThreadFactory instrumentedThreadFactory = new InstrumentedThreadFactory(threadFactory,
environment.getMetricRegistry(), nameFormat);
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolSize, instrumente... | @Test
void testBasicInvocation() {
final String poolName = this.getClass().getSimpleName();
final ScheduledExecutorServiceBuilder test = new ScheduledExecutorServiceBuilder(this.le,
poolName,
false);
this.execTracker = test.build();
assertThat(this.execTrac... |
public static <T> AsList<T> asList() {
return new AsList<>(null, false);
} | @Test
@Category(ValidatesRunner.class)
public void testWindowedListSideInput() {
final PCollectionView<List<Integer>> view =
pipeline
.apply(
"CreateSideInput",
Create.timestamped(
TimestampedValue.of(11, new Instant(1)),
... |
public double getCenterY() {
return (this.top + this.bottom) / 2;
} | @Test
public void getCenterYTest() {
Rectangle rectangle = create(1, 2, 3, 4);
Assert.assertEquals(3, rectangle.getCenterY(), 0);
} |
@Entrance
public final void combine(@SourceFrom int value, @Arg String name, @Arg boolean status) {
int t = DICT.lookup(name).intValue();
int t4 = t * 4;
totalNum++;
if (!status || value > t4) {
return;
}
if (value > t) {
tNum++;
} else... | @Test
public void testCombine() {
ApdexMetrics apdex1 = new ApdexMetricsImpl();
apdex1.combine(200, "foo", true);
apdex1.combine(300, "bar", true);
apdex1.combine(200, "foo", true);
apdex1.combine(1500, "bar", true);
ApdexMetrics apdex2 = new ApdexMetricsImpl();
... |
@Override
public boolean match(Message msg, StreamRule rule) {
Object rawField = msg.getField(rule.getField());
if (rawField == null) {
return rule.getInverted();
}
if (rawField instanceof String) {
String field = (String) rawField;
Boolean resul... | @Test
public void testBasicNonMatch() throws Exception {
StreamRule rule = getSampleRule();
rule.setField("nonexistentField");
rule.setType(StreamRuleType.PRESENCE);
rule.setInverted(false);
Message message = getSampleMessage();
StreamRuleMatcher matcher = getMatche... |
public static ILogger getLogger(@Nonnull Class<?> clazz) {
checkNotNull(clazz, "class must not be null");
return getLoggerInternal(clazz.getName());
} | @Test
public void getLogger_whenJdk_thenReturnStandardLogger() {
isolatedLoggingRule.setLoggingType(LOGGING_TYPE_JDK);
assertInstanceOf(StandardLoggerFactory.StandardLogger.class, Logger.getLogger(getClass()));
} |
synchronized void ensureTokenInitialized() throws IOException {
// we haven't inited yet, or we used to have a token but it expired
if (!hasInitedToken || (action != null && !action.isValid())) {
//since we don't already have a token, go get one
Token<?> token = fs.getDelegationToken(null);
//... | @Test
public void testInitWithNoTokens() throws IOException, URISyntaxException {
Configuration conf = new Configuration();
DummyFs fs = spy(new DummyFs());
doReturn(null).when(fs).getDelegationToken(anyString());
fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);
fs.tokenAspect.ensureToke... |
public File dumpHeap()
throws MalformedObjectNameException, InstanceNotFoundException, ReflectionException,
MBeanException, IOException {
return dumpHeap(localDumpFolder);
} | @Test
public void heapDumpTwice() throws Exception {
File folder = tempFolder.newFolder();
File dump1 = MemoryMonitor.dumpHeap(folder);
assertNotNull(dump1);
assertTrue(dump1.exists());
assertThat(dump1.getParentFile(), Matchers.equalTo(folder));
File dump2 = MemoryMonitor.dumpHeap(folder);
... |
@Nonnull
public static String getAfter(@Nonnull String text, @Nonnull String after) {
int i = text.lastIndexOf(after);
if (i < 0) return text;
return text.substring(i + after.length());
} | @Test
void testGetAfter() {
assertEquals("", StringUtil.getAfter("", ""));
assertEquals("d", StringUtil.getAfter("a b c d", "c "));
assertEquals("a b c d", StringUtil.getAfter("a b c d", "z"));
} |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREF... | @Test
public void testFinalDestinationMagic1() {
assertEquals(l("first", "2"),
finalDestination(l("first", MAGIC_PATH_PREFIX, "2")));
} |
static IndexComponentFilter findBestComponentFilter(
IndexType type,
List<IndexComponentCandidate> candidates,
QueryDataType converterType
) {
// First look for equality filters, assuming that they are more selective than ranges
IndexComponentFilter equalityCompon... | @Test
public void when_upperBoundRangeFilterPresentAndNoBetterChoiceAndSortedIndex_then_itIsUsed() {
IndexComponentFilter bestFilter = IndexComponentFilterResolver.findBestComponentFilter(
indexType, WITH_UPPER_BOUND_RANGE_AS_BEST_CANDIDATES, QUERY_DATA_TYPE
);
if (indexType... |
@Override
protected void processOptions(LinkedList<String> args) throws IOException {
CommandFormat cf =
new CommandFormat(1, Integer.MAX_VALUE, OPTION_FOLLOW_LINK,
OPTION_FOLLOW_ARG_LINK, null);
cf.parse(args);
if (cf.getOpt(OPTION_FOLLOW_LINK)) {
getOptions().setFollowLink(tru... | @Test
public void processOptionsExpression() throws IOException {
Find find = new Find();
find.setConf(conf);
String paths = "path1 path2 path3";
String args = "-L -H " + paths + " -print -name test";
LinkedList<String> argsList = getArgs(args);
find.processOptions(argsList);
LinkedList<S... |
@HighFrequencyInvocation
public boolean isEncryptColumn(final String logicColumnName) {
return columns.containsKey(logicColumnName);
} | @Test
void assertIsEncryptColumn() {
assertTrue(encryptTable.isEncryptColumn("logicColumn"));
} |
public boolean parse(final String s) {
if (StringUtils.isEmpty(s) || StringUtils.isBlank(s)) {
return false;
}
final String[] tmps = Utils.parsePeerId(s);
if (tmps.length < 2 || tmps.length > 4) {
return false;
}
try {
final int port =... | @Test
public void testToStringParseFailed() {
final PeerId pp = new PeerId();
final String str1 = "";
final String str2 = "192.168.1.1";
final String str3 = "92.168.1.1:8081::1:2";
assertFalse(pp.parse(str1));
assertFalse(pp.parse(str2));
} |
public int asInteger() {
checkState(type == Type.INTEGER, "Value is not an integer");
return Integer.parseInt(value);
} | @Test
public void asInteger() {
ConfigProperty p = defineProperty("foo", INTEGER, "123", "Foo Prop");
validate(p, "foo", INTEGER, "123", "123");
assertEquals("incorrect value", 123, p.asInteger());
assertEquals("incorrect value", 123L, p.asLong());
} |
@Override
public Mono<Void> removeProductFromFavourites(int productId, String userId) {
return this.favouriteProductRepository.deleteByProductIdAndUserId(productId, userId);
} | @Test
void removeProductFromFavourites_ReturnsEmptyMono() {
// given
doReturn(Mono.empty()).when(this.favouriteProductRepository)
.deleteByProductIdAndUserId(1, "5f1d5cf8-cbd6-11ee-9579-cf24d050b47c");
// when
StepVerifier.create(this.service.removeProductFromFavouri... |
public static String calculateMemoryWithDefaultOverhead(String memory) {
long memoryMB = convertToBytes(memory) / M;
long memoryOverheadMB = Math.max((long) (memoryMB * 0.1f), MINIMUM_OVERHEAD);
return (memoryMB + memoryOverheadMB) + "Mi";
} | @Test
void testExceptionNoValidNumber() {
assertThrows(NumberFormatException.class, () -> {
K8sUtils.calculateMemoryWithDefaultOverhead("NoValidNumber10000000Tb");
});
} |
public static TypeInformation<?> readTypeInfo(String typeString) {
final List<Token> tokens = tokenize(typeString);
final TokenConverter converter = new TokenConverter(typeString, tokens);
return converter.convert();
} | @Test
void testSyntaxError1() {
assertThatThrownBy(() -> TypeStringUtils.readTypeInfo("ROW<<f0 DECIMAL, f1 TINYINT>"))
.isInstanceOf(ValidationException.class); // additional <
} |
public static Set<String> findReferencedColumn(String columnName, ResolvedSchema schema) {
Column column =
schema.getColumn(columnName)
.orElseThrow(
() ->
new ValidationException(
... | @Test
void testFindReferencedColumn() {
assertThat(ColumnReferenceFinder.findReferencedColumn("b", resolvedSchema))
.isEqualTo(Collections.emptySet());
assertThat(ColumnReferenceFinder.findReferencedColumn("a", resolvedSchema))
.containsExactlyInAnyOrder("b");
... |
@Override
public RexNode visit(CallExpression call) {
boolean isBatchMode = unwrapContext(relBuilder).isBatchMode();
for (CallExpressionConvertRule rule : getFunctionConvertChain(isBatchMode)) {
Optional<RexNode> converted = rule.convert(call, newFunctionContext());
if (conve... | @Test
void testDecimalLiteral() {
BigDecimal value = new BigDecimal("12345678.999");
RexNode rex = converter.visit(valueLiteral(value));
assertThat(((RexLiteral) rex).getValueAs(BigDecimal.class)).isEqualTo(value);
assertThat(rex.getType().getSqlTypeName()).isEqualTo(SqlTypeName.DECI... |
static Optional<File> getOptionalFileFromURLFile(URL retrieved) {
File toReturn = new File(retrieved.getFile());
logger.debug(TO_RETURN_TEMPLATE, toReturn);
logger.debug(TO_RETURN_GETABSOLUTEPATH_TEMPLATE, toReturn.getAbsolutePath());
return Optional.of(toReturn);
} | @Test
void getOptionalFileFromURLFile() {
URL resourceUrl = getResourceUrl();
Optional<File> retrieved = MemoryFileUtils.getOptionalFileFromURLFile(resourceUrl);
assertThat(retrieved).isNotNull();
assertThat(retrieved.isPresent()).isTrue();
assertThat(retrieved).get().isInsta... |
@Override
public Publisher<Exchange> to(String uri, Object data) {
String streamName = requestedUriToStream.computeIfAbsent(uri, camelUri -> {
try {
String uuid = context.getUuidGenerator().generateUuid();
context.addRoutes(new RouteBuilder() {
... | @Test
public void testTo() throws Exception {
context.start();
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Flux.just(1, 2, 3)
.flatMap(e -> crs.to("bean:hello", e, String.class))
.d... |
@Override
public void initTransactions() {
verifyNotClosed();
verifyNotFenced();
if (this.transactionInitialized) {
throw new IllegalStateException("MockProducer has already been initialized for transactions.");
}
if (this.initTransactionException != null) {
... | @Test
public void shouldThrowOnAbortTransactionIfNoTransactionGotStarted() {
buildMockProducer(true);
producer.initTransactions();
assertThrows(IllegalStateException.class, producer::abortTransaction);
} |
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = RedisKeyConstants.ROLE, key = "#id")
@LogRecord(type = SYSTEM_ROLE_TYPE, subType = SYSTEM_ROLE_DELETE_SUB_TYPE, bizNo = "{{#id}}",
success = SYSTEM_ROLE_DELETE_SUCCESS)
public void deleteRole(Long id) {
// 1.... | @Test
public void testDeleteRole() {
// mock 数据
RoleDO roleDO = randomPojo(RoleDO.class, o -> o.setType(RoleTypeEnum.CUSTOM.getType()));
roleMapper.insert(roleDO);
// 参数准备
Long id = roleDO.getId();
// 调用
roleService.deleteRole(id);
// 断言
asser... |
public abstract byte[] encode(MutableSpan input); | @Test void errorSpan_JSON_V2() {
assertThat(new String(encoder.encode(errorSpan), UTF_8))
.isEqualTo(
"{\"traceId\":\"dc955a1d4768875d\",\"id\":\"dc955a1d4768875d\",\"kind\":\"CLIENT\",\"localEndpoint\":{\"serviceName\":\"isao01\"},\"tags\":{\"error\":\"\"}}");
} |
@Override
public void pluginLoaded(GoPluginDescriptor descriptor) {
loadTaskConfigIntoPreferenceStore(descriptor);
} | @Test
public void shouldLoadPreferencesOnlyForTaskPlugins() {
final GoPluginDescriptor descriptor = mock(GoPluginDescriptor.class);
String pluginId = "test-plugin-id";
when(descriptor.id()).thenReturn(pluginId);
final Task task = mock(Task.class);
TaskConfig config = new Task... |
public Mono<Object> genericInvoker(final String body, final MetaData metaData, final ServerWebExchange exchange) throws ShenyuException {
String referenceKey = metaData.getPath();
String namespace = "";
if (CollectionUtils.isNotEmpty(exchange.getRequest().getHeaders().get(Constants.NAMESPACE))) ... | @Test
@SuppressWarnings(value = "unchecked")
public void genericInvokerTest() throws IllegalAccessException, NoSuchFieldException {
GenericService genericService = mock(GenericService.class);
when(referenceConfig.get()).thenReturn(genericService);
when(referenceConfig.getInterface()).the... |
public MethodBuilder serviceId(String serviceId) {
this.serviceId = serviceId;
return getThis();
} | @Test
void serviceId() {
MethodBuilder builder = MethodBuilder.newBuilder();
builder.serviceId("serviceId");
Assertions.assertEquals("serviceId", builder.build().getServiceId());
} |
@Override
public boolean removeExistingSetCookie(String cookieName) {
String cookieNamePrefix = cookieName + "=";
boolean dirty = false;
Headers filtered = new Headers();
for (Header hdr : getHeaders().entries()) {
if (HttpHeaderNames.SET_COOKIE.equals(hdr.getName())) {
... | @Test
void testRemoveExistingSetCookie() {
response.getHeaders()
.add(
"Set-Cookie",
"c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com");
response.getHeaders()
.add(
... |
@Override
public int run(InputStream in, PrintStream out, PrintStream err, List<String> args) throws Exception {
OptionParser optParser = new OptionParser();
OptionSpec<String> codecOpt = Util.compressionCodecOptionWithDefault(optParser, DataFileConstants.NULL_CODEC);
OptionSpec<Integer> levelOpt = Util.... | @Test
void recodec() throws Exception {
String metaKey = "myMetaKey";
String metaValue = "myMetaValue";
File inputFile = new File(DIR, "input.avro");
Schema schema = Schema.create(Type.STRING);
DataFileWriter<String> writer = new DataFileWriter<>(new GenericDatumWriter<String>(schema));
writ... |
@Override
public ElasticAgentPluginInfo pluginInfoFor(GoPluginDescriptor descriptor) {
String pluginId = descriptor.id();
PluggableInstanceSettings pluggableInstanceSettings = null;
if (!extension.supportsClusterProfiles(pluginId)) {
pluggableInstanceSettings = getPluginSettings... | @Test
public void shouldBuildPluginInfoWithoutClusterProfileSettingsForPluginsImplementedUsingv4Extension() {
GoPluginDescriptor descriptor = GoPluginDescriptor.builder().id("plugin1").build();
List<PluginConfiguration> elasticAgentProfileConfigurations = List.of(new PluginConfiguration("aws_passwor... |
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("name", (Gauge<String>) runtime::getName);
gauges.put("vendor", (Gauge<String>) () -> String.format(Locale.US,
"%s %s %s (%s)",
runtime.getVmVen... | @Test
public void hasAGaugeForTheJVMVendor() {
final Gauge<String> gauge = (Gauge<String>) gauges.getMetrics().get("vendor");
assertThat(gauge.getValue())
.isEqualTo("Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 23.7-b01 (1.7)");
} |
public LimitKey getKey() {
return key;
} | @Test
public void testLimitKey() {
Assert.assertEquals(limitConfig.getKey(), LimitKey.SERVER);
} |
public static FromMatchesFilter create(Jid address) {
return new FromMatchesFilter(address, address != null ? address.hasNoResource() : false) ;
} | @Test
public void autoCompareMatchingServiceJid() {
FromMatchesFilter filter = FromMatchesFilter.create(SERVICE_JID1);
Stanza packet = StanzaBuilder.buildMessage().build();
packet.setFrom(SERVICE_JID1);
assertTrue(filter.accept(packet));
packet.setFrom(SERVICE_JID2);
... |
@Override
public boolean hasAttribute(String key) {
return channel.hasAttribute(key);
} | @Test
void hasAttributeTest() {
Assertions.assertFalse(header.hasAttribute("test"));
header.setAttribute("test", "test");
Assertions.assertTrue(header.hasAttribute("test"));
} |
public DockerImagesCommand getSingleImageStatus(String imageName) {
Preconditions.checkNotNull(imageName, "imageName");
super.addCommandArguments("image", imageName);
return this;
} | @Test
public void testSingleImage() {
dockerImagesCommand = dockerImagesCommand.getSingleImageStatus(IMAGE_NAME);
assertEquals("images", StringUtils.join(",",
dockerImagesCommand.getDockerCommandWithArguments()
.get("docker-command")));
assertEquals("image name", "foo", StringUtils.joi... |
@Override
/**
* {@inheritDoc} Handles the bundle's completion report. Parses the monitoringInfos in the
* response, then updates the MetricsRegistry.
*/
public void onCompleted(BeamFnApi.ProcessBundleResponse response) {
response.getMonitoringInfosList().stream()
.filter(monitoringInfo -> !moni... | @Test
public void testEmptyPayload() {
byte[] emptyPayload = "".getBytes(Charset.defaultCharset());
MetricsApi.MonitoringInfo emptyMonitoringInfo =
MetricsApi.MonitoringInfo.newBuilder()
.setType(SUM_INT64_TYPE)
.setPayload(ByteString.copyFrom(emptyPayload))
.putL... |
public StreamObserver<BeamFnApi.Elements> getOutboundObserver() {
return outboundObserver;
} | @Test
public void testOutboundObserver() {
Collection<BeamFnApi.Elements> values = new ArrayList<>();
BeamFnDataGrpcMultiplexer multiplexer =
new BeamFnDataGrpcMultiplexer(
DESCRIPTOR,
OutboundObserverFactory.clientDirect(),
inboundObserver -> TestStreams.withOnNext... |
private void handleTokenCallback(OAuthBearerTokenCallback callback) throws IOException {
checkInitialized();
String accessToken = accessTokenRetriever.retrieve();
try {
OAuthBearerToken token = accessTokenValidator.validate(accessToken);
callback.token(token);
} ... | @Test
public void testHandleTokenCallback() throws Exception {
Map<String, ?> configs = getSaslConfigs();
AccessTokenBuilder builder = new AccessTokenBuilder()
.jwk(createRsaJwk())
.alg(AlgorithmIdentifiers.RSA_USING_SHA256);
String accessToken = builder.build();
... |
public static String formatExpression(final Expression expression) {
return formatExpression(expression, FormatOptions.of(s -> false));
} | @Test
public void shouldFormatWhen() {
assertThat(ExpressionFormatter.formatExpression(new WhenClause(new LongLiteral(1), new LongLiteral(2))), equalTo("WHEN 1 THEN 2"));
} |
@Timed
@Path("/{destination}")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
@Operation(
summary = "Send a message",
description = """
Deliver a message to a single recipient. May be authenticated or unauthenticated; if unauthenticated... | @Test
void testSingleDeviceCurrentUnidentified() throws Exception {
try (final Response response =
resources.getJerseyTest()
.target(String.format("/v1/messages/%s", SINGLE_DEVICE_UUID))
.request()
.header(HeaderUtils.UNIDENTIFIED_ACCESS_KEY, Base64.getEncoder().encodeT... |
public Collection<ServerAbilityInitializer> getInitializers() {
return initializers;
} | @Test
void testGetInitializers() {
assertEquals(1, ServerAbilityInitializerHolder.getInstance().getInitializers().size());
} |
public int getClusterID() {
return clusterID;
} | @Test
public void testConstruct() {
Storage storage1 = new Storage(1, "token", "test");
Assert.assertEquals(1, storage1.getClusterID());
} |
public static DatabaseType getProtocolType(final DatabaseConfiguration databaseConfig, final ConfigurationProperties props) {
Optional<DatabaseType> configuredDatabaseType = findConfiguredDatabaseType(props);
if (configuredDatabaseType.isPresent()) {
return configuredDatabaseType.get();
... | @Test
void assertGetProtocolTypeFromConfiguredProperties() {
Properties props = PropertiesBuilder.build(new Property(ConfigurationPropertyKey.PROXY_FRONTEND_DATABASE_PROTOCOL_TYPE.getKey(), "MySQL"));
DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.empt... |
public void applyPluginsForContainer( final String category, final XulDomContainer container ) throws XulException {
List<SpoonPluginInterface> plugins = pluginCategoryMap.get( category );
if ( plugins != null ) {
for ( SpoonPluginInterface sp : plugins ) {
sp.applyToContainer( category, container... | @Test
public void testApplyPluginsForContainer() throws Exception {
spoonPluginManager.pluginAdded( plugin1 );
spoonPluginManager.pluginAdded( plugin2 );
spoonPluginManager.applyPluginsForContainer( "trans-graph", xulDomContainer );
assertEquals( 2, applies.size() );
assertEquals( 1, (int) applie... |
public static InstanceMetaData create(final String instanceId, final InstanceType instanceType, final String attributes, final String version) {
return InstanceType.JDBC == instanceType ? new JDBCInstanceMetaData(instanceId, attributes, version) : new ProxyInstanceMetaData(instanceId, attributes, version);
... | @Test
void assertCreateJDBCInstanceMetaDataWithInstanceId() {
InstanceMetaData actual = InstanceMetaDataFactory.create("foo_id", InstanceType.JDBC, "127.0.0.1", "foo_version");
assertThat(actual.getId(), is("foo_id"));
assertNotNull(actual.getIp());
assertThat(actual.getAttributes(),... |
public int get(final int key)
{
final int missingValue = this.missingValue;
final int[] entries = this.entries;
@DoNotSub final int mask = entries.length - 1;
@DoNotSub int index = Hashing.evenHash(key, mask);
int value;
while (missingValue != (value = entries[index ... | @Test
void boxedGetShouldReturnNull()
{
assertNull(map.get((Integer)1));
} |
@Override
public byte[] evaluateResponse( @Nonnull final byte[] response ) throws SaslException
{
if ( isComplete() )
{
throw new IllegalStateException( "Authentication exchange already completed." );
}
// The value as sent to us in the 'from' attribute of the stream... | @Test(expected = SaslFailureException.class)
public void testInitialResponseDifferentFromStreamID() throws Exception
{
// Setup test fixture.
final String authzID = "foo.example.org";
final String certID = "bar.example.com";
when(session.getDefaultIdentity()).thenReturn(authzID)... |
public static <T> NullableCoder<T> of(Coder<T> valueCoder) {
if (valueCoder instanceof NullableCoder) {
return (NullableCoder<T>) valueCoder;
}
return new NullableCoder<>(valueCoder);
} | @Test
public void testSubcoderRecievesEntireStream() throws Exception {
NullableCoder<String> coder = NullableCoder.of(new EntireStreamExpectingCoder());
CoderProperties.coderDecodeEncodeEqualInContext(coder, Context.OUTER, null);
CoderProperties.coderDecodeEncodeEqualInContext(coder, Context.OUTER, "foo... |
@Override
public void invoke(IN value, Context context) throws Exception {
bufferLock.lock();
try {
// TODO this implementation is not very effective,
// optimize this with MemorySegment if needed
ByteArrayOutputStream baos = new ByteArrayOutputStream();
... | @Test
void testAccumulatorResultWithCheckpoint() throws Exception {
functionWrapper.openFunctionWithState();
for (int i = 0; i < 6; i++) {
functionWrapper.invoke(i);
}
String version = initializeVersion();
functionWrapper.sendRequestAndGetResponse(version, 3);
... |
public void isNull() {
standardIsEqualTo(null);
} | @Test
public void isNullWhenSubjectForbidsIsEqualToFail() {
expectFailure.whenTesting().about(objectsForbiddingEqualityCheck()).that(new Object()).isNull();
} |
@Override
public ExtensionFactory getExtensionFactory() {
return original.getExtensionFactory();
} | @Test
public void getExtensionFactory() {
pluginManager.loadPlugins();
assertEquals(pluginManager.getExtensionFactory(), wrappedPluginManager.getExtensionFactory());
} |
private Mute() {
} | @Test
void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
assertDoesNotThrow(() -> Mute.mute(this::methodNotThrowingAnyException));
} |
@Override
public synchronized void destroy() {
if (id < 0) {
throw new IllegalStateException("Negative segment ID indicates a reserved segment, "
+ "which should not be destroyed. Reserved segments are cleaned up only when "
+ "an entire store is closed, via the c... | @Test
public void shouldNotDestroySegmentWithNegativeId() {
// reserved segments should not be destroyed. they are cleaned up only when
// an entire store is closed, via the close() method rather than destroy()
assertThrows(IllegalStateException.class, () -> negativeIdSegment.destroy());
... |
@Override
public DirectoryTimestamp getDirectoryTimestamp() {
return DirectoryTimestamp.explicit;
} | @Test
public void testFeatures() {
assertEquals(Protocol.Case.sensitive, new CteraProtocol().getCaseSensitivity());
assertEquals(Protocol.DirectoryTimestamp.explicit, new CteraProtocol().getDirectoryTimestamp());
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.