focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public int diff(String... names) {
return get(diffAsync(names));
} | @Test
public void testDiff() throws InterruptedException {
redisson.getKeys().flushall();
RSetCache<Integer> cache1 = redisson.getSetCache("cache1", IntegerCodec.INSTANCE);
cache1.add(1);
cache1.add(2, 1, TimeUnit.SECONDS);
cache1.add(5, 1, TimeUnit.SECONDS);
cache1.a... |
@Override
public CompletableFuture<T> toCompletableFuture()
{
return _task.toCompletionStage().toCompletableFuture();
} | @Test
public void testCreateStageFromSupplierAsync() throws Exception
{
String testResult = "testCreateStageFromCompletableFuture";
ParSeqBasedCompletionStage<String> stageFromCompletionStage =
_parSeqBasedCompletionStageFactory.buildStageFromSupplierAsync(() -> testResult);
Assert.assertEquals(... |
public static Read<String> readStrings() {
return Read.newBuilder(
(PubsubMessage message) -> new String(message.getPayload(), StandardCharsets.UTF_8))
.setCoder(StringUtf8Coder.of())
.build();
} | @Test
public void testNullSubscription() {
String topic = "projects/project/topics/topic";
PubsubIO.Read<String> read = PubsubIO.readStrings().fromTopic(StaticValueProvider.of(topic));
assertNotNull(read.getTopicProvider());
assertNull(read.getSubscriptionProvider());
assertNotNull(DisplayData.fro... |
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword)
throws IOException, GeneralSecurityException
{
PrivateKey key;
try {
key = createPrivateKey(privateKeyFile, keyPassword);
} catch (OperatorCreationException | IOExcepti... | @Test
void testParsingPKCS1WithoutPassword() throws IOException, GeneralSecurityException {
KeyStore keystore = PEMImporter.loadKeyStore(pemCert, privkeyWithoutPasswordPKCS1, "");
assertEquals(1, keystore.size());
assertTrue(keystore.containsAlias("key"));
assertEquals(1, keystore.getCertificateChain(... |
public void start() {
taskExecutor = Executors.newSingleThreadScheduledExecutor(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Eureka-PeerNodesUpdater");
... | @Test
public void testReloadWithNoPeerChange() throws Exception {
// Start
peerEurekaNodes.withPeerUrls(PEER_EUREKA_URL_A);
peerEurekaNodes.start();
PeerEurekaNode peerNode = getPeerNode(PEER_EUREKA_URL_A);
assertThat(peerEurekaNodes.awaitNextReload(60, TimeUnit.SECONDS), is... |
@Override
public String toString() {
return translations.toString();
} | @Test
public void testToString() {
Translation enMap = SINGLETON.getWithFallBack(Locale.UK);
assertEquals("continue onto blp street", enMap.tr("continue_onto", "blp street"));
Translation trMap = SINGLETON.getWithFallBack(Locale.GERMANY);
assertEquals("Zu Fuß", trMap.tr("web.FOOT"))... |
@Override
public List<URI> get() {
return resultsCachingSupplier.get();
} | @Test
void testSkippedConfigWithDefaultIndexer() {
final IndexerDiscoveryProvider provider = new IndexerDiscoveryProvider(
Collections.emptyList(),
1,
Duration.seconds(1),
preflightConfig(PreflightConfigResult.SKIPPED),
nodes(),... |
@Override
public CharSequence get(CharSequence name) {
return get0(name);
} | @Test
public void testGet() {
Http2Headers headers = newClientHeaders();
assertTrue(AsciiString.contentEqualsIgnoreCase("value1", headers.get("Name1")));
assertTrue(AsciiString.contentEqualsIgnoreCase("/foo",
headers.get(Http2Headers.PseudoHeaderName.PATH.value())));
... |
public static InetSocketAddress toInetSocketAddress(String address) {
String[] ipPortStr = splitIPPortStr(address);
String host;
int port;
if (null != ipPortStr) {
host = ipPortStr[0];
port = Integer.parseInt(ipPortStr[1]);
} else {
host = addr... | @Test
public void testToInetSocketAddress() {
try {
NetUtil.toInetSocketAddress("23939:ks");
} catch (Exception e) {
assertThat(e).isInstanceOf(NumberFormatException.class);
}
} |
@Override
public Num calculate(BarSeries series, Position position) {
return series.one();
} | @Test
public void calculateWithNoPositions() {
MockBarSeries series = new MockBarSeries(numFunction, 100, 105, 110, 100, 95, 105);
AnalysisCriterion buyAndHold = getCriterion();
assertNumEquals(0, buyAndHold.calculate(series, new BaseTradingRecord()));
} |
@Override
public boolean isSatisfied(int index, TradingRecord tradingRecord) {
if (tradingRecord.getCurrentPosition().isOpened()) {
final int entryIndex = tradingRecord.getLastEntry().getIndex();
final int currentBarCount = index - entryIndex;
return currentBarCount >= ba... | @Test
public void testAtLeastOneBarRuleForOpenedTrade() {
final OpenedPositionMinimumBarCountRule rule = new OpenedPositionMinimumBarCountRule(1);
final BarSeries series = new MockBarSeries(DecimalNum::valueOf, 1, 2, 3, 4);
final TradingRecord tradingRecord = new BaseTradingRecord(Trade.bu... |
public String getConstraintsAsString() {
return constraintsString;
} | @Test
void getConstraintsAsString() {
KiePMMLFieldOperatorValue kiePMMLFieldOperatorValue = getKiePMMLFieldOperatorValueWithName();
String expected = "value < 35 surrogate value > 85";
String retrieved = kiePMMLFieldOperatorValue.getConstraintsAsString();
assertThat(retrieved).isEqua... |
protected String resolveOffchain(
String lookupData, OffchainResolverContract resolver, int lookupCounter)
throws Exception {
if (EnsUtils.isEIP3668(lookupData)) {
OffchainLookup offchainLookup =
OffchainLookup.build(Numeric.hexStringToByteArray(lookupDat... | @Test
void resolveOffchainNotEIP() throws Exception {
String lookupData = "some data";
String resolveResponse = ensResolver.resolveOffchain(lookupData, null, 4);
assertEquals(lookupData, resolveResponse);
} |
@Override
public void initialize(ServiceConfiguration config) throws IOException {
this.allowedAudiences = validateAllowedAudiences(getConfigValueAsSet(config, ALLOWED_AUDIENCES));
this.roleClaim = getConfigValueAsString(config, ROLE_CLAIM, ROLE_CLAIM_DEFAULT);
this.isRoleClaimNotSubject = !... | @Test
public void ensureInsecureIssuerFailsInitialization() throws IOException {
@Cleanup
AuthenticationProviderOpenID provider = new AuthenticationProviderOpenID();
Properties props = new Properties();
props.setProperty(AuthenticationProviderOpenID.ALLOWED_TOKEN_ISSUERS, "https://my... |
public SerializableFunction<Row, T> getFromRowFunction() {
return fromRowFunction;
} | @Test
public void testMapRowToProto() {
ProtoDynamicMessageSchema schemaProvider = schemaFromDescriptor(MapPrimitive.getDescriptor());
SerializableFunction<Row, DynamicMessage> fromRow = schemaProvider.getFromRowFunction();
MapPrimitive proto =
parseFrom(fromRow.apply(MAP_PRIMITIVE_ROW).toString()... |
public static Map<String, String> parseParams(HttpRequest request) {
if (request instanceof HttpGet) {
return parseParamsForGet(request);
}
if (request instanceof HttpEntityEnclosingRequestBase) {
return parseParamsForRequestWithEntity((HttpEntityEnclosingRequestBase) request);
}
return ... | @Test
public void parseParams_returnsNullForUnsupportedOperations() throws Exception {
HttpDelete httpDelete = new HttpDelete("http://example.com/deleteme");
assertThat(ParamsParser.parseParams(httpDelete)).isEmpty();
} |
public static int getMaxTileNumber(byte zoomLevel) {
if (zoomLevel < 0) {
throw new IllegalArgumentException("zoomLevel must not be negative: " + zoomLevel);
} else if (zoomLevel == 0) {
return 0;
}
return (2 << zoomLevel - 1) - 1;
} | @Test
public void getMaxTileNumberTest() {
Assert.assertEquals(0, Tile.getMaxTileNumber((byte) 0));
Assert.assertEquals(1, Tile.getMaxTileNumber((byte) 1));
Assert.assertEquals(3, Tile.getMaxTileNumber((byte) 2));
Assert.assertEquals(7, Tile.getMaxTileNumber((byte) 3));
Asser... |
List<String> decorateTextWithHtml(String text, DecorationDataHolder decorationDataHolder) {
return decorateTextWithHtml(text, decorationDataHolder, null, null);
} | @Test
public void should_escape_ampersand_char() {
String javadocWithAmpersandChar =
"/**\n" +
" * Definition of a dashboard.\n" +
" * <p/>\n" +
" * Its name and description can be retrieved using the i18n mechanism, using the keys \"dashboard.<id>.name\" and\n" +
" * ... |
@Override
public Map<String, List<TopicPartition>> assignPartitions(Map<String, List<PartitionInfo>> partitionsPerTopic,
Map<String, Subscription> subscriptions) {
Map<String, List<TopicPartition>> consumerToOwnedPartitions = new HashMap<>();
... | @Test
public void testSubscriptionNotEqualAndAssignSamePartitionWith3Generation() {
Map<String, List<PartitionInfo>> partitionsPerTopic = new HashMap<>();
partitionsPerTopic.put(topic, partitionInfos(topic, 6));
partitionsPerTopic.put(topic1, partitionInfos(topic1, 1));
int[][] seque... |
public EndpointResponse checkHealth() {
return EndpointResponse.ok(getResponse());
} | @Test
public void shouldRecheckHealthIfCachedResponseExpired() throws Exception {
// Given:
healthCheckResource = new HealthCheckResource(healthCheckAgent, Duration.ofMillis(10));
healthCheckResource.checkHealth();
// When / Then:
assertThatEventually(
"Should receive response2 once respo... |
public static <T> T toObj(byte[] json, Class<T> cls) {
try {
return mapper.readValue(json, cls);
} catch (Exception e) {
throw new NacosDeserializationException(cls, e);
}
} | @Test
void testToObject11() {
assertEquals(Collections.singletonMap("key", "value"),
JacksonUtils.toObj(new ByteArrayInputStream("{\"key\":\"value\"}".getBytes()),
TypeUtils.parameterize(Map.class, String.class, String.class)));
assertEquals(Collections.single... |
public synchronized void rewind() {
this.readPosition = 0;
this.curReadBufferIndex = 0;
this.readPosInCurBuffer = 0;
if (CollectionUtils.isNotEmpty(bufferList)) {
this.curBuffer = bufferList.get(0);
for (ByteBuffer buffer : bufferList) {
buffer.rew... | @Test
public void testCommitLogTypeInputStream() {
List<ByteBuffer> uploadBufferList = new ArrayList<>();
int bufferSize = 0;
for (int i = 0; i < MSG_NUM; i++) {
ByteBuffer byteBuffer = MessageFormatUtilTest.buildMockedMessageBuffer();
uploadBufferList.add(byteBuffer)... |
@Override
public void open() throws Exception {
super.open();
inputActivityClock = new PausableRelativeClock(getProcessingTimeService().getClock());
getContainingTask()
.getEnvironment()
.getMetricGroup()
.getIOMetricGroup()
.re... | @Test
public void testIdleTimeoutUnderBackpressure() throws Exception {
long idleTimeout = 100;
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(0, WATERMARK_GENERATOR, idleTimeout);
testHarness.getExecutionConfig().setAutoWatermarkInterval... |
public Set<FactIdentifier> getFactIdentifiers() {
return factMappings.stream().map(FactMapping::getFactIdentifier).collect(Collectors.toSet());
} | @Test
public void getFactIdentifiers() {
modelDescriptor.addFactMapping(factIdentifier, expressionIdentifier);
assertThat(modelDescriptor.getFactIdentifiers()).isNotNull().hasSize(1).containsExactly(factIdentifier);
} |
int lookupResourceValue(Ref<Res_value> value) {
byte resolvedType = DataType.REFERENCE.code();
Res_value inValue = value.get();
DataType dataType;
try {
dataType = DataType.fromCode(inValue.dataType);
} catch (IllegalArgumentException e) {
return BAD_TYPE;
}
switch (dataType) {... | @Test
public void lookupResourceValue_returnsBadTypeIfTypeOutOfEnumRange() {
DynamicRefTable pseudoRefTable =
new DynamicRefTable(/* packageId= */ (byte) 0, /* appAsLib= */ true);
assertThat(pseudoRefTable.lookupResourceValue(RES_VALUE_OF_BAD_TYPE)).isEqualTo(BAD_TYPE);
} |
@Operation(summary = "Resolve SAML artifact")
@PostMapping(value = {"/backchannel/saml/v4/entrance/resolve_artifact", "/backchannel/saml/v4/idp/resolve_artifact"})
public ResponseEntity resolveArtifact(HttpServletRequest request, HttpServletResponse response) throws SamlParseException {
try {
... | @Test
void failedResolveArtifactTest() throws SamlParseException {
when(artifactResolveServiceMock.startArtifactResolveProcess(any(HttpServletRequest.class))).thenThrow(ClassCastException.class);
ResponseEntity response = artifactController.resolveArtifact(httpServletRequestMock, httpServletRespons... |
public Optional<UfsStatus[]> listFromUfs(String path, boolean isRecursive)
throws IOException {
ListOptions ufsListOptions = ListOptions.defaults().setRecursive(isRecursive);
UnderFileSystem ufs = getUfsInstance(path);
try {
UfsStatus[] listResults = ufs.listStatus(path, ufsListOptions);
i... | @Test
public void listFromUfsWhenGetFail() throws IOException {
UnderFileSystem system = mock(UnderFileSystem.class);
when(system.listStatus(anyString())).thenReturn(null);
when(system.getStatus(anyString())).thenThrow(new FileNotFoundException());
doReturn(system).when(mDoraUfsManager).getOrAdd(any()... |
public int get(final K key)
{
final int initialValue = this.initialValue;
final K[] keys = this.keys;
final int[] values = this.values;
@DoNotSub final int mask = values.length - 1;
@DoNotSub int index = Hashing.hash(key, mask);
int value;
while (initialValue... | @Test
void getShouldReturnInitialValueWhenEmpty()
{
assertEquals(INITIAL_VALUE, map.get(1));
} |
static Object parseValue( String key, String value, Class<?> valueType )
throws IllegalArgumentException
{
return parseValue( key, value, valueType, null, v -> v, Collections.emptyList() );
} | @Test
void parseValueWithJavaType() {
assertEquals( null, UIDefaultsLoader.parseValue( "dummy", "null", String.class ) );
assertEquals( false, UIDefaultsLoader.parseValue( "dummy", "false", boolean.class ) );
assertEquals( true, UIDefaultsLoader.parseValue( "dummy", "true", Boolean.class ) );
assertEquals( "h... |
@Override
public XAConnection wrap(final XADataSource xaDataSource, final Connection connection) throws SQLException {
return createXAConnection(connection.unwrap(jdbcConnectionClass));
} | @Test
void assertWrap() throws SQLException {
XAConnection actual = DatabaseTypedSPILoader.getService(XAConnectionWrapper.class, databaseType).wrap(createXADataSource(), mockConnection());
assertThat(actual.getXAResource(), instanceOf(PGXAConnection.class));
} |
private KafkaRebalanceStatus updateStatus(KafkaRebalance kafkaRebalance,
KafkaRebalanceStatus desiredStatus,
Throwable e) {
// Leave the current status when the desired state is null
if (desiredStatus != null) {
... | @Test
public void testCruiseControlDisabledToEnabledBehaviour(VertxTestContext context) {
// build a Kafka cluster without the cruiseControl definition
Kafka kafka = new KafkaBuilder(KAFKA)
.editSpec()
.withCruiseControl(null)
.endSpec()
... |
public static <T extends RecordTemplate> PatchRequest<T> applyProjection(PatchRequest<T> patch, MaskTree projection)
{
try
{
/**
* Implementation consists of 3 steps:
* 1) move data conveyed by patch out of meta-commands (expose method)
* 2) apply projection on it
* 2) trim o... | @Test(dataProvider = "data")
public void testProjectionOnPatch(String[] patchAndProjection, String expectedResult) throws IOException
{
DataMap patch = dataMapFromString(patchAndProjection[0].replace('\'', '"'));
DataMap projection = dataMapFromString(patchAndProjection[1].replace('\'', '"'));
DataMap e... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
return this.list(directory, listener, new HostPreferences(session.getHost()).getInteger("eue.listing.chunksize"));
} | @Test
public void testListForSharedFile() throws Exception {
final EueResourceIdProvider fileid = new EueResourceIdProvider(session);
final Path sourceFolder = new EueDirectoryFeature(session, fileid).mkdir(new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory)), ne... |
@Override
public final Optional<IdentifierValue> getAlias() {
return Optional.ofNullable(alias);
} | @Test
void assertGetAlias() {
Projection projection = new AggregationProjection(AggregationType.COUNT, "COUNT( A.\"DIRECTION\" )", new IdentifierValue("AVG_DERIVED_COUNT_0"), mock(DatabaseType.class));
Optional<IdentifierValue> actual = projection.getAlias();
assertTrue(actual.isPresent());
... |
@Override
public Schema getSourceSchema() {
if (schema == null) {
try {
Schema.Parser parser = new Schema.Parser();
schema = parser.parse(schemaString);
} catch (Exception e) {
throw new HoodieSchemaException("Failed to parse schema: " + schemaString, e);
}
}
ret... | @Test
public void validateRecursiveSchemaGeneration_depth2() throws IOException {
TypedProperties properties = new TypedProperties();
properties.setProperty(ProtoClassBasedSchemaProviderConfig.PROTO_SCHEMA_CLASS_NAME.key(), Parent.class.getName());
properties.setProperty(ProtoClassBasedSchemaProviderConfi... |
public static byte[] generateFor(byte[] unidentifiedAccessKey) {
try {
if (unidentifiedAccessKey.length != UnidentifiedAccessUtil.UNIDENTIFIED_ACCESS_KEY_LENGTH) {
throw new IllegalArgumentException("Invalid UAK length: " + unidentifiedAccessKey.length);
}
Mac mac = Mac.getInstance("HmacS... | @Test
public void generateForIllegalArgument() {
final byte[] invalidLengthUnidentifiedAccessKey = new byte[15];
new SecureRandom().nextBytes(invalidLengthUnidentifiedAccessKey);
assertThrows(IllegalArgumentException.class, () -> UnidentifiedAccessChecksum.generateFor(invalidLengthUnidentifiedAccessKey))... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testFunctionWithNoGenericSuperclass() {
RichMapFunction<?, ?> function = new Mapper2();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(function, (TypeInformation) Types.STRING);
assertThat(ti.isBasicType()... |
@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 testBandwidthConstrainedIntentAllocation() {
final double bpsTotal = 1000.0;
String[] hops = {S1, S2, S3};
final ResourceService resourceService =
MockResourceService.makeCustomBandwidthResourceService(bpsTotal);
final List<Constraint> constraints ... |
List<Token> tokenize() throws ScanException {
List<Token> tokenList = new ArrayList<Token>();
StringBuilder buf = new StringBuilder();
while (pointer < patternLength) {
char c = pattern.charAt(pointer);
pointer++;
switch (state) {
case LITERAL_ST... | @Test
public void LOGBACK_1101() throws ScanException {
String input = "a:{y}";
Tokenizer tokenizer = new Tokenizer(input);
List<Token> tokenList = tokenizer.tokenize();
witnessList.add(new Token(Token.Type.LITERAL, "a"));
witnessList.add(new Token(Token.Type.LITERAL, ":"));... |
UuidGenerator loadUuidGenerator() {
Class<? extends UuidGenerator> objectFactoryClass = options.getUuidGeneratorClass();
ClassLoader classLoader = classLoaderSupplier.get();
ServiceLoader<UuidGenerator> loader = ServiceLoader.load(UuidGenerator.class, classLoader);
if (objectFactoryClass... | @Test
void test_case_2() {
Options options = () -> null;
UuidGeneratorServiceLoader loader = new UuidGeneratorServiceLoader(
UuidGeneratorServiceLoaderTest.class::getClassLoader,
options);
assertThat(loader.loadUuidGenerator(), instanceOf(RandomUuidGenerator.class));
... |
public final void sort(long startIndex, long length) {
quickSort(startIndex, length - 1);
} | @Test
public void testQuickSortInt() {
final int[] array = intArrayWithRandomElements();
final long baseAddr = memMgr.getAllocator().allocate(ARRAY_LENGTH * INT_SIZE_IN_BYTES);
final MemoryAccessor mem = memMgr.getAccessor();
for (int i = 0; i < ARRAY_LENGTH; i++) {
mem.p... |
@Override
public void processWatermark(org.apache.flink.streaming.api.watermark.Watermark mark)
throws Exception {
// if we receive a Long.MAX_VALUE watermark we forward it since it is used
// to signal the end of input and to not block watermark progress downstream
if (mark.getT... | @Test
void longMaxInputWatermarkIsForwarded() throws Exception {
OneInputStreamOperatorTestHarness<Long, Long> testHarness =
createTestHarness(
WatermarkStrategy.forGenerator((ctx) -> new PeriodicWatermarkGenerator())
.withTimestampAssi... |
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
final HttpServletResponse resp = (HttpServletResponse) respo... | @Test
void passesThroughNonHttpRequests() throws Exception {
final ServletRequest req = mock(ServletRequest.class);
final ServletResponse res = mock(ServletResponse.class);
filter.doFilter(req, res, chain);
verify(chain).doFilter(req, res);
verifyNoInteractions(res);
} |
static TimelineFilterList parseKVFilters(String expr, boolean valueAsString)
throws TimelineParseException {
return parseFilters(new TimelineParserForKVFilters(expr, valueAsString));
} | @Test
void testConfigFiltersParsing() throws Exception {
String expr = "(((key11 ne 234 AND key12 eq val12) AND " +
"(key13 ene val13 OR key14 eq 567)) OR (key21 eq val_21 OR key22 eq " +
"val.22))";
TimelineFilterList expectedList = new TimelineFilterList(
Operator.OR,
new Tim... |
@Override
public boolean isFetchSizeSupported() {
return false;
} | @Test
public void testIsFetchSizeSupported() throws Exception {
assertFalse( dbMeta.isFetchSizeSupported() );
} |
public static Node build(final List<JoinInfo> joins) {
Node root = null;
for (final JoinInfo join : joins) {
if (root == null) {
root = new Leaf(join.getLeftSource());
}
if (root.containsSource(join.getRightSource()) && root.containsSource(join.getLeftSource())) {
throw new K... | @Test
public void handlesLeftThreeWayJoin() {
// Given:
when(j1.getLeftSource()).thenReturn(a);
when(j1.getRightSource()).thenReturn(b);
when(j2.getLeftSource()).thenReturn(a);
when(j2.getRightSource()).thenReturn(c);
final List<JoinInfo> joins = ImmutableList.of(j1, j2);
// When:
fin... |
public static NameStep newBuilder() {
return new CharacterSteps();
} | @Test
void testBuildWizard() {
final var character = CharacterStepBuilder.newBuilder()
.name("Merlin")
.wizardClass("alchemist")
.withSpell("poison")
.withAbility("invisibility")
.withAbility("wisdom")
.noMoreAbilities()
.build();
assertEquals("Merlin",... |
public static String escapeHtml4(CharSequence html) {
Html4Escape escape = new Html4Escape();
return escape.replace(html).toString();
} | @Test
public void escapeSingleQuotesTest(){
// 单引号不做转义
String str = "'some text with single quotes'";
final String s = EscapeUtil.escapeHtml4(str);
assertEquals("'some text with single quotes'", s);
} |
public static int[] colMin(int[][] matrix) {
int[] x = new int[matrix[0].length];
Arrays.fill(x, Integer.MAX_VALUE);
for (int[] row : matrix) {
for (int j = 0; j < x.length; j++) {
if (x[j] > row[j]) {
x[j] = row[j];
}
... | @Test
public void testColMin() {
System.out.println("colMin");
double[][] A = {
{0.7220180, 0.07121225, 0.6881997},
{-0.2648886, -0.89044952, 0.3700456},
{-0.6391588, 0.44947578, 0.6240573}
};
double[] r = {-0.6391588, -0.89044952, 0.3700456};
... |
public static JavaBeanDescriptor serialize(Object obj) {
return serialize(obj, JavaBeanAccessor.FIELD);
} | @Test
void test_Circular_Reference() {
Parent parent = new Parent();
parent.setAge(Integer.MAX_VALUE);
parent.setEmail("a@b");
parent.setName("zhangsan");
Child child = new Child();
child.setAge(100);
child.setName("lisi");
child.setParent(parent);
... |
public static GenericRecord rewriteRecord(GenericRecord oldRecord, Schema newSchema) {
GenericRecord newRecord = new GenericData.Record(newSchema);
boolean isSpecificRecord = oldRecord instanceof SpecificRecordBase;
for (Schema.Field f : newSchema.getFields()) {
if (!(isSpecificRecord && isMetadataFie... | @Test
public void testJsonNodeNullWithDefaultValues() {
List<Schema.Field> fields = new ArrayList<>();
Schema initialSchema = Schema.createRecord("test_record", "test record", "org.test.namespace", false);
Schema.Field field1 = new Schema.Field("key", HoodieAvroUtils.METADATA_FIELD_SCHEMA, "", JsonPropert... |
public static <KLeftT, KRightT> KTableHolder<KLeftT> build(
final KTableHolder<KLeftT> left,
final KTableHolder<KRightT> right,
final ForeignKeyTableTableJoin<KLeftT, KRightT> join,
final RuntimeBuildContext buildContext
) {
final LogicalSchema leftSchema = left.getSchema();
final Logi... | @Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void shouldDoLeftJoinOnSubKey() {
// Given:
givenLeftJoin(leftMultiKey, L_KEY_2);
// When:
final KTableHolder<Struct> result = join.build(planBuilder, planInfo);
// Then:
final ArgumentCaptor<KsqlKeyExtractor> ksqlKeyExtractor
... |
public Pet status(StatusEnum status) {
this.status = status;
return this;
} | @Test
public void statusTest() {
// TODO: test status
} |
public List<CompactionTask> produce() {
// get all CF files sorted by key range start (L1+)
List<SstFileMetaData> sstSortedByCfAndStartingKeys =
metadataSupplier.get().stream()
.filter(l -> l.level() > 0) // let RocksDB deal with L0
.sorte... | @Test
void testSkipBeingCompacted() {
assertThat(produce(configBuilder().build(), sstBuilder().setBeingCompacted(true).build()))
.isEmpty();
} |
public static String[] getCheckProcessIsAliveCommand(String pid) {
return getSignalKillCommand(0, pid);
} | @Test
public void testGetCheckProcessIsAliveCommand() throws Exception {
String anyPid = "9999";
String[] checkProcessAliveCommand = getCheckProcessIsAliveCommand(
anyPid);
String[] expectedCommand;
if (Shell.WINDOWS) {
expectedCommand =
new String[]{getWinUtilsPath(), "task"... |
public SortedSet<Long> validWindows(Cluster cluster, double minMonitoredPartitionsPercentage) {
AggregationOptions<String, PartitionEntity> options = new AggregationOptions<>(minMonitoredPartitionsPercentage,
0.0,
... | @Test
public void testValidWindows() {
TestContext ctx = setupScenario1();
KafkaPartitionMetricSampleAggregator aggregator = ctx.aggregator();
MetadataClient.ClusterAndGeneration clusterAndGeneration = ctx.clusterAndGeneration(0);
SortedSet<Long> validWindows = aggregator.validWindows(clusterAndGenera... |
public static Optional<Expression> convert(
org.apache.flink.table.expressions.Expression flinkExpression) {
if (!(flinkExpression instanceof CallExpression)) {
return Optional.empty();
}
CallExpression call = (CallExpression) flinkExpression;
Operation op = FILTERS.get(call.getFunctionDefi... | @Test
public void testLike() {
UnboundPredicate<?> expected =
org.apache.iceberg.expressions.Expressions.startsWith("field5", "abc");
Expression expr =
resolve(
ApiExpressionUtils.unresolvedCall(
BuiltInFunctionDefinitions.LIKE, Expressions.$("field5"), Expressions.... |
@Override
@CheckForNull
public String revisionId(Path path) {
RepositoryBuilder builder = getVerifiedRepositoryBuilder(path);
try {
return Optional.ofNullable(getHead(builder.build()))
.map(Ref::getObjectId)
.map(ObjectId::getName)
.orElse(null);
} catch (IOException e) {
... | @Test
public void revisionId_should_return_different_sha1_after_commit() throws IOException, GitAPIException {
Path projectDir = worktree.resolve("project");
Files.createDirectory(projectDir);
GitScmProvider provider = newGitScmProvider();
String sha1before = provider.revisionId(projectDir);
ass... |
private StorageVolume getStorageVolumeOfTable(String svName, long dbId) throws DdlException {
StorageVolume sv = null;
if (svName.isEmpty()) {
String dbStorageVolumeId = getStorageVolumeIdOfDb(dbId);
if (dbStorageVolumeId != null) {
return getStorageVolume(dbStora... | @Test
public void testGetStorageVolumeOfTable()
throws DdlException, AlreadyExistsException {
new Expectations() {
{
editLog.logSetDefaultStorageVolume((SetDefaultStorageVolumeLog) any);
}
};
SharedDataStorageVolumeMgr sdsvm = new SharedDa... |
public final <KIn, VIn, KOut, VOut> void addProcessor(final String name,
final ProcessorSupplier<KIn, VIn, KOut, VOut> supplier,
final String... predecessorNames) {
Objects.requireNonNull(name, "n... | @Test
public void testAddProcessorWithNullParents() {
assertThrows(NullPointerException.class, () -> builder.addProcessor("processor",
new MockApiProcessorSupplier<>(), (String) null));
} |
static int getNext(final CronEntry entry, final int current, final Calendar working) throws MessageFormatException {
int result = 0;
if (entry.currentWhen == null) {
entry.currentWhen = calculateValues(entry);
}
List<Integer> list = entry.currentWhen;
int next = -1;... | @Test
public void testGetNextExact() throws MessageFormatException {
String token = "3";
int next = CronParser.getNext(createEntry(token, 0, 10), 2, null);
assertEquals(1, next);
next = CronParser.getNext(createEntry(token, 0, 10), 3, null);
assertEquals(10, next);
ne... |
@Override
public Object lock() {
return controller;
} | @Test
public void testLock() {
final AbstractController c = new AbstractController() {
@Override
public void invoke(final MainAction runnable, final boolean wait) {
//
}
};
assertEquals(c, new ControllerMainAction(c) {
@Overrid... |
public static PodTemplateSpec createPodTemplateSpec(
String workloadName,
Labels labels,
PodTemplate template,
Map<String, String> defaultPodLabels,
Map<String, String> podAnnotations,
Affinity affinity,
List<Container> initContainers,
... | @Test
public void testCreatePodTemplateSpecWithNullTemplate() {
PodTemplateSpec pod = WorkloadUtils.createPodTemplateSpec(
NAME,
LABELS,
null,
Map.of("default-label", "default-value"),
Map.of("extra", "annotations"),
... |
public abstract String encrypt(String plaintext) throws GeneralSecurityException; | @Test
void encrypt() throws GeneralSecurityException {
// given
RunContext runContext = runContextFactory.of();
String plainText = "toto";
String encrypted = runContext.encrypt(plainText);
String decrypted = EncryptionService.decrypt(secretKey, encrypted);
assertTha... |
@Override
public boolean equals(Object obj) {
if (!(obj instanceof JobParameters rhs)) {
return false;
}
if (obj == this) {
return true;
}
return this.parameters.equals(rhs.parameters);
} | @Test
void testEquals() {
jobParameter = new JobParameter("test", String.class, true);
JobParameter testParameter = new JobParameter("test", String.class, true);
assertEquals(jobParameter, testParameter);
} |
@Override
public double calcEdgeWeight(EdgeIteratorState edgeState, boolean reverse) {
double priority = edgeToPriorityMapping.get(edgeState, reverse);
if (priority == 0) return Double.POSITIVE_INFINITY;
final double distance = edgeState.getDistance();
double seconds = calcSeconds(d... | @Test
public void testArea() throws Exception {
EdgeIteratorState edge1 = graph.edge(0, 1).setDistance(10).
set(roadClassEnc, PRIMARY).set(avSpeedEnc, 80);
EdgeIteratorState edge2 = graph.edge(2, 3).setDistance(10).
set(roadClassEnc, PRIMARY).set(avSpeedEnc, 80);
... |
private static Schema optional(Schema original) {
// null is first in the union because Parquet's default is always null
return Schema.createUnion(Arrays.asList(Schema.create(Schema.Type.NULL), original));
} | @Test
public void testOptionalArrayElement() throws Exception {
Schema schema = Schema.createRecord("record1", null, null, false);
Schema optionalIntArray = Schema.createArray(optional(Schema.create(INT)));
schema.setFields(Arrays.asList(new Schema.Field("myintarray", optionalIntArray, null, null)));
... |
@Nullable
public static String getRelativeDisplayNameFrom(@CheckForNull Item p, @CheckForNull ItemGroup g) {
return getRelativeNameFrom(p, g, true);
} | @Test
public void testGetRelativeDisplayNameInsideItemGroup() {
Item i = mock(Item.class);
when(i.getName()).thenReturn("jobName");
when(i.getDisplayName()).thenReturn("displayName");
TopLevelItemAndItemGroup ig = mock(TopLevelItemAndItemGroup.class);
ItemGroup j = mock(Jenki... |
public static Finder specializedFinder(String... queries) {
var finder = identMult();
for (String query : queries) {
finder = finder.and(Finder.contains(query));
}
return finder;
} | @Test
void specializedFinderTest() {
var res = specializedFinder("love", "heaven").find(text());
assertEquals(1, res.size());
assertEquals("With a love that the winged seraphs of heaven", res.get(0));
} |
@Override
@SuppressWarnings("rawtypes")
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String,... | @Test
public void reportsByteGaugeValues() throws Exception {
reporter.report(map("gauge", gauge((byte) 1)),
map(),
map(),
map(),
map());
final InOrder inOrder = inOrder(graphite);
inOrder.verify(graphite).connect();
inOrder.verify(gra... |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} else if (!(obj instanceof MapPosition)) {
return false;
}
MapPosition other = (MapPosition) obj;
if (!this.latLong.equals(other.latLong)) {
return false;
... | @Test
public void equalsTest() {
MapPosition mapPosition1 = new MapPosition(new LatLong(1.0, 2.0), (byte) 3);
MapPosition mapPosition2 = new MapPosition(new LatLong(1.0, 2.0), (byte) 3);
MapPosition mapPosition3 = new MapPosition(new LatLong(1.0, 2.0), (byte) 0);
MapPosition mapPosit... |
public ForComputation forComputation(String computation) {
return new ForComputation(computation);
} | @Test
public void testMultipleFamilies() throws Exception {
TestStateTag tag = new TestStateTag("tag1");
WindmillStateCache.ForKey keyCache =
cache.forComputation("comp1").forKey(computationKey("comp1", "key1", SHARDING_KEY), 0L, 0L);
WindmillStateCache.ForKeyAndFamily family1 = keyCache.forFamil... |
public String getStyle()
{
return getCOSObject().getNameAsString(COSName.S, PDTransitionStyle.R.name());
} | @Test
void getStyle()
{
PDTransition transition = new PDTransition(PDTransitionStyle.Fade);
assertEquals(COSName.TRANS, transition.getCOSObject().getCOSName(COSName.TYPE));
assertEquals(PDTransitionStyle.Fade.name(), transition.getStyle());
} |
@Override
public Collection<String> getLogicTableNames() {
return logicTableMapper;
} | @Test
void assertGetLogicTableMapper() {
assertThat(new LinkedList<>(ruleAttribute.getLogicTableNames()), is(Collections.singletonList("foo_tbl")));
} |
public static RestartBackoffTimeStrategy.Factory createRestartBackoffTimeStrategyFactory(
final RestartStrategies.RestartStrategyConfiguration jobRestartStrategyConfiguration,
final Configuration jobConfiguration,
final Configuration clusterConfiguration,
final boolean is... | @Test
void testNoRestartStrategySpecifiedInExecutionConfig() {
final Configuration conf = new Configuration();
conf.set(RestartStrategyOptions.RESTART_STRATEGY, FAILURE_RATE.getMainValue());
final RestartBackoffTimeStrategy.Factory factory =
RestartBackoffTimeStrategyFactory... |
@Nullable String getCollectionName(BsonDocument command, String commandName) {
if (COMMANDS_WITH_COLLECTION_NAME.contains(commandName)) {
String collectionName = getNonEmptyBsonString(command.get(commandName));
if (collectionName != null) {
return collectionName;
}
}
// Some other ... | @Test void getCollectionName_notAllowListedCommandAndCollectionField() {
BsonDocument command = new BsonDocument(Arrays.asList(
new BsonElement("collection", new BsonString("coll")),
new BsonElement("cmd", new BsonString("bar"))
));
assertThat(listener.getCollectionName(command, "cmd")).isEqualT... |
@Override
public Mono<SinglePage> get(String name) {
return client.fetch(SinglePage.class, name);
} | @Test
void get() {
when(client.fetch(eq(SinglePage.class), any()))
.thenReturn(Mono.empty());
SinglePage singlePage = new SinglePage();
singlePage.setMetadata(new Metadata());
singlePage.getMetadata().setName("fake-single-page");
when(client.fetch(eq(SinglePage.... |
@Override
public boolean match(Message msg, StreamRule rule) {
Double msgVal = getDouble(msg.getField(rule.getField()));
if (msgVal == null) {
return false;
}
Double ruleVal = getDouble(rule.getValue());
if (ruleVal == null) {
return false;
}
... | @Test
public void testSuccessfulDoubleMatch() {
StreamRule rule = getSampleRule();
rule.setValue("1.0");
Message msg = getSampleMessage();
msg.addField("something", "1.1");
StreamRuleMatcher matcher = getMatcher(rule);
assertTrue(matcher.match(msg, rule));
} |
public IsJson(Matcher<? super ReadContext> jsonMatcher) {
this.jsonMatcher = jsonMatcher;
} | @Test
public void shouldDescribeMismatchOfValidJson() {
Matcher<Object> matcher = isJson(withPathEvaluatedTo(true));
Description description = new StringDescription();
matcher.describeMismatch(BOOKS_JSON_STRING, description);
assertThat(description.toString(), containsString(TestingM... |
@Override
public <T> T convert(DataTable dataTable, Type type) {
return convert(dataTable, type, false);
} | @Test
void convert_to_list_of_unknown_type__throws_exception__register_transformer() {
DataTable table = parse("",
" | firstName | lastName | birthDate |",
" | Annie M. G. | Schmidt | 1911-03-20 |",
" | Roald | Dahl | 1916-09-13 |",
" | Astrid ... |
@Override
public void createPod(Pod pod) {
checkNotNull(pod, ERR_NULL_POD);
checkArgument(!Strings.isNullOrEmpty(pod.getMetadata().getUid()),
ERR_NULL_POD_UID);
k8sPodStore.createPod(pod);
log.info(String.format(MSG_POD, pod.getMetadata().getName(), MSG_CREATED));
... | @Test(expected = NullPointerException.class)
public void testCreateNullPod() {
target.createPod(null);
} |
public List<String> getGlobalWhiteAddrs() {
return globalWhiteAddrs;
} | @Test
public void testGetGlobalWhiteAddrs() {
AclConfig aclConfig = new AclConfig();
List<String> expected = Arrays.asList("192.168.1.1", "192.168.1.2");
aclConfig.setGlobalWhiteAddrs(expected);
assertEquals("Global white addresses should match", expected, aclConfig.getGlobalWhiteAdd... |
public static StatementExecutorResponse execute(
final ConfiguredStatement<AssertSchema> statement,
final SessionProperties sessionProperties,
final KsqlExecutionContext executionContext,
final ServiceContext serviceContext
) {
return AssertExecutor.execute(
statement.getMaskedStat... | @Test
public void shouldFailToAssertSchemaBySubject() {
// Given
final AssertSchema assertSchema = new AssertSchema(Optional.empty(), Optional.of("abc"), Optional.empty(), Optional.empty(), true);
final ConfiguredStatement<AssertSchema> statement = ConfiguredStatement
.of(KsqlParser.PreparedStatem... |
@CheckReturnValue
protected final boolean tryEmit(int ordinal, @Nonnull Object item) {
return outbox.offer(ordinal, item);
} | @Test
public void when_tryEmitToAll_then_emittedToAll() {
// When
boolean emitted = p.tryEmit(MOCK_ITEM);
// Then
assertTrue(emitted);
validateReceptionAtOrdinals(MOCK_ITEM, ALL_ORDINALS);
} |
@Override
public Metric root() {
return new RootMetricImpl(this.threadContext, this.metrics.root(this.threadContext));
} | @Test
public void testRoot() {
final NamespacedMetric metrics = this.getInstance().namespace("test");
final Metric root = metrics.root();
final NamespacedMetric namespaced = root.namespace("someothernamespace");
assertThat(namespaced.namespaceName()).containsExactly("someothernamespa... |
@Override
public synchronized int read() throws IOException {
checkNotClosed();
if (finished) {
return -1;
}
file.readLock().lock();
try {
int b = file.read(pos++); // it's ok for pos to go beyond size()
if (b == -1) {
finished = true;
} else {
file.setLas... | @Test
public void testRead_wholeArray() throws IOException {
JimfsInputStream in = newInputStream(1, 2, 3, 4, 5, 6, 7, 8);
byte[] bytes = new byte[8];
assertThat(in.read(bytes)).isEqualTo(8);
assertArrayEquals(bytes(1, 2, 3, 4, 5, 6, 7, 8), bytes);
assertEmpty(in);
} |
public Object unmarshal(Exchange exchange, Document document) throws Exception {
InputStream is = exchange.getIn().getMandatoryBody(InputStream.class);
return unmarshal(exchange, is);
} | @Test
public void testXMLElementDecryptionWithoutEncryptedKey() throws Exception {
if (!TestHelper.HAS_3DES) {
return;
}
String passPhrase = "this is a test passphrase";
byte[] bytes = passPhrase.getBytes();
final byte[] keyBytes = Arrays.copyOf(bytes, 24);
... |
@POST
@Path("/generate_regex")
@Timed
@ApiOperation(value = "Generates a regex that can be used as a value for a whitelist entry.")
@NoAuditEvent("Utility function only.")
@Consumes(MediaType.APPLICATION_JSON)
public WhitelistRegexGenerationResponse generateRegex(@ApiParam(name = "JSON body", re... | @Test
public void generateRegexForUrl() {
final WhitelistRegexGenerationRequest request =
WhitelistRegexGenerationRequest.create("https://example.com/api/lookup", null);
final WhitelistRegexGenerationResponse response = urlWhitelistResource.generateRegex(request);
assertThat(... |
public static int calculateDefaultNumSlots(
ResourceProfile totalResourceProfile, ResourceProfile defaultSlotResourceProfile) {
// For ResourceProfile.ANY in test case, return the maximum integer
if (totalResourceProfile.equals(ResourceProfile.ANY)) {
return Integer.MAX_VALUE;
... | @Test
void testCalculateDefaultNumSlots() {
final ResourceProfile defaultSlotResource =
ResourceProfile.newBuilder()
.setCpuCores(1.0)
.setTaskHeapMemoryMB(1)
.setTaskOffHeapMemoryMB(2)
.setNetwor... |
@Override
public boolean isReadable(Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType) {
return isSupportedMediaType(mediaType) && isSupportedCharset(mediaType) && isSupportedEntity(serializableClass);
} | @Test
public void testNonUtf8CharsetIsNotAccepted() throws Exception {
Map<String, String> params = new HashMap<>();
params.put("charset", "ISO-8859");
MediaType mediaTypeWithNonSupportedCharset = new MediaType("application", "json", params);
assertThat(jerseyProvider.isReadable(Ins... |
public BlobOperationResponse uploadBlockBlob(final Exchange exchange) throws IOException {
ObjectHelper.notNull(exchange, MISSING_EXCHANGE);
final BlobStreamAndLength blobStreamAndLength = BlobStreamAndLength.createBlobStreamAndLengthFromExchangeBody(exchange);
final BlobCommonRequestOptions co... | @Test
void testUploadBlockBlob() throws Exception {
// mocking
final BlockBlobItem blockBlobItem = new BlockBlobItem("testTag", OffsetDateTime.now(), null, false, null);
final HttpHeaders httpHeaders = new HttpHeaders().set("x-test-header", "123");
when(client.uploadBlockBlob(any(),... |
public static boolean inTccBranch() {
return BranchType.TCC == getBranchType();
} | @Test
public void testInTccBranch() {
RootContext.bind(DEFAULT_XID);
assertThat(RootContext.inTccBranch()).isFalse();
RootContext.bindBranchType(BranchType.TCC);
assertThat(RootContext.inTccBranch()).isTrue();
RootContext.unbindBranchType();
assertThat(RootContext.inT... |
public final Sink sink(final Sink sink) {
return new Sink() {
@Override public void write(Buffer source, long byteCount) throws IOException {
boolean throwOnTimeout = false;
enter();
try {
sink.write(source, byteCount);
throwOnTimeout = true;
} catch (IOExce... | @Test public void wrappedThrowsWithoutTimeout() throws Exception {
Sink sink = new ForwardingSink(new Buffer()) {
@Override public void write(Buffer source, long byteCount) throws IOException {
throw new IOException("no timeout occurred");
}
};
AsyncTimeout timeout = new AsyncTimeout();
... |
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
} | @Test
public void added_event_uses_language_key_in_message_if_language_not_found() {
QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date());
qProfileStatusRepository.register(qp.getQpKey(), ADDED);
mockLanguageNotInRepository(LANGUAGE_KEY_1);
mockQualityProfileMeasures(treeRootHolder.getRoot()... |
@Override
public InterpreterResult interpret(final String st, final InterpreterContext context)
throws InterpreterException {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("st:\n{}", st);
}
final FormType form = getFormType();
RemoteInterpreterProcess interpreterProcess = null;
try {
... | @Test
void testEnvironmentAndProperty() throws InterpreterException {
interpreterSetting.getOption().setPerUser(InterpreterOption.SHARED);
interpreterSetting.setProperty("ENV_1", "VALUE_1");
interpreterSetting.setProperty("property_1", "value_1");
final Interpreter interpreter1 = interpreterSetting.g... |
@Override
public ConsumerBuilder<T> priorityLevel(int priorityLevel) {
checkArgument(priorityLevel >= 0, "priorityLevel needs to be >= 0");
conf.setPriorityLevel(priorityLevel);
return this;
} | @Test(expectedExceptions = IllegalArgumentException.class)
public void testConsumerBuilderImplWhenPriorityLevelPropertyIsNegative() {
consumerBuilderImpl.priorityLevel(-1);
} |
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record,
final Callback callback) {
maybeBeginTransaction();
try {
return producer.send(record, callback);
} catch (final KafkaException uncaughtException) {
if (isRecoverable(... | @Test
public void shouldFailOnSendFatal() {
nonEosMockProducer.sendException = new RuntimeException("KABOOM!");
final RuntimeException thrown = assertThrows(
RuntimeException.class,
() -> nonEosStreamsProducer.send(record, null)
);
assertThat(thrown.getMessa... |
public static void refreshSuperUserGroupsConfiguration() {
//load server side configuration;
refreshSuperUserGroupsConfiguration(new Configuration());
} | @Test
public void testWildcardUser() {
Configuration conf = new Configuration();
conf.set(
DefaultImpersonationProvider.getTestProvider().
getProxySuperuserUserConfKey(REAL_USER_NAME),
"*");
conf.set(
DefaultImpersonationProvider.getTestProvider().
getProxySuperuserIp... |
public static Map<String, String> fromEnvironment() {
Map<String, String> p = System.getenv();
return new CucumberPropertiesMap(p);
} | @Test
void looks_up_value_from_environment() {
Map<String, String> properties = CucumberProperties.fromEnvironment();
String path = properties.get("PATH");
if (path == null) {
// on some Windows flavors, the PATH environment variable is named
// "Path"
pat... |
public JmxCollector register() {
return register(PrometheusRegistry.defaultRegistry);
} | @Test
public void testCompositeData() throws Exception {
JmxCollector jc =
new JmxCollector(
"\n---\nrules:\n- pattern: `io.prometheus.jmx.test<name=PerformanceMetricsMBean><PerformanceMetrics>.*`\n attrNameSnakeCase: true"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.