focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
long size() {
return directories.size();
} | @Test
public void testDeletePerfectCache() throws Throwable {
// run a larger scale test. Also use the ordering we'd expect for a sorted
// listing, which we implement by sorting the paths
List<CopyListingFileStatus> statusList = buildStatusList();
// cache is bigger than the status list
tracker =... |
@Override
public T build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = mapper.readTree(createParser(input));
if (node == null) {
th... | @Test
void throwsAnExceptionOnUnexpectedArrayOverride() {
System.setProperty("dw.servers.port", "9000");
assertThatIllegalArgumentException()
.isThrownBy(() -> factory.build(configurationSourceProvider, validFile))
.withMessageContaining("target is an array but no index speci... |
public String getClusterName() {
if (StringUtils.isNotEmpty(contextPath)) {
return contextPath.substring(1);
}
return null;
} | @Test
public void testGetClusterName() {
assertEquals(upstreamInstance.getClusterName(), "henyuContextPath");
upstreamInstance.setContextPath("");
assertNull(upstreamInstance.getClusterName());
} |
boolean isPublicAndStatic() {
int modifiers = mainMethod.getModifiers();
return isPublic(modifiers) && isStatic(modifiers);
} | @Test
public void testPublicAndStaticForMain() throws NoSuchMethodException {
Method method = MainMethodFinderTest.class.getDeclaredMethod("main", String[].class);
MainMethodFinder mainMethodFinder = new MainMethodFinder();
mainMethodFinder.mainMethod = method;
boolean publicAndStat... |
public static boolean isIPv4Host(String host) {
return StringUtils.isNotBlank(host)
&& IPV4_PATTERN.matcher(host).matches();
} | @Test
public void isIPv4Host() throws Exception {
} |
public Searcher searcher() {
return new Searcher();
} | @Test
void require_that_search_for_simple_conjunctions_work() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
feature("a").inSet("1"),
feature("b").inSet("2")));
... |
@Override
public synchronized boolean onReportingPeriodEnd() {
firstEventReceived = false;
return true;
} | @Test
public void testOnReportingPeriodEnd() {
assertTrue(strategy.onActivity(), "First call of onActivity() should return true.");
assertTrue(strategy.onReportingPeriodEnd(), "onReportingPeriodEnd() should always return true.");
assertTrue(strategy.onActivity(), "onActivity() should return ... |
public void addHeader(String name, String value) {
parent.headers().add(name, value);
} | @Test
void testAddHeader() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
response.addH... |
public static DateTime date() {
return new DateTime();
} | @Test
public void calendarTest() {
final Date date = DateUtil.date();
final Calendar c = DateUtil.calendar(date);
assertEquals(DateUtil.date(c), date);
} |
protected String addDatetimeToFilename( String filename, boolean addDate, String datePattern, boolean addTime,
String timePattern, boolean specifyFormat, String datetimeFormat ) {
if ( Utils.isEmpty( filename ) ) {
return null;
}
// Replace possible environm... | @Test
public void testAddDatetimeToFilename_ZipWithDotsInFolderWithDots() {
JobEntryBase jobEntryBase = new JobEntryBase();
String fullFilename;
String filename = "/folder.with.dots/zip.with.dots.in.folder.with.dots";
String regexFilename = regexDotEscape( filename );
// add nothing
fullFilen... |
public HollowHashIndexResult findMatches(Object... query) {
if (hashStateVolatile == null) {
throw new IllegalStateException(this + " wasn't initialized");
}
int hashCode = 0;
for(int i=0;i<query.length;i++) {
if(query[i] == null)
throw new Illega... | @Test
public void testIndexingListTypeField() throws Exception {
mapper.add(new TypeList("A", "B", "C", "D", "A", "B", "C", "D"));
mapper.add(new TypeList("B", "C", "D", "E"));
mapper.add(new TypeList("X", "Y", "Z"));
mapper.add(new TypeList());
roundTripSnapshot();
H... |
public void broadcastEvent(AbstractEvent event) throws IOException {
broadcastEvent(event, false);
} | @TestTemplate
void testBroadcastEventBufferReferenceCounting() throws Exception {
int bufferSize = 32 * 1024;
int numSubpartitions = 2;
ResultPartition partition = createResultPartition(bufferSize, numSubpartitions);
RecordWriter<?> writer = createRecordWriter(partition);
w... |
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
final String prefix = containerService.isContainer(directory) ? StringUtils.EMPTY : containerService.getKey(directory) + Path.DELIMITER;
return this.list(directory, list... | @Test
public void testListDotInKey() throws Exception {
final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
container.attributes().setRegion("IAD");
final Path placeholder = new SwiftDirectoryFeature(session).mkdir(new Path(container, new ... |
public void execute() throws DdlException {
Map<String, UserVariable> clonedUserVars = new ConcurrentHashMap<>();
boolean hasUserVar = stmt.getSetListItems().stream().anyMatch(var -> var instanceof UserVariable);
boolean executeSuccess = true;
if (hasUserVar) {
clonedUserVars... | @Test
public void test1SetSessionAndGlobal() throws Exception {
ConnectContext ctx = starRocksAssert.getCtx();
ctxToRoot();
DDLStmtExecutor.execute(UtFrameUtils.parseStmtWithNewParser(
"grant operate on system to testUser", ctx), ctx);
ctxToTestUser();
String... |
@Nullable
protected String findWebJarResourcePath(String pathStr) {
Path path = Paths.get(pathStr);
if (path.getNameCount() < 2) return null;
String version = swaggerUiConfigProperties.getVersion();
if (version == null) return null;
Path first = path.getName(0);
Path rest = path.subpath(1, path.getNameCoun... | @Test
void returNullWhenPathIsSameAsWebjar() {
String path = "swagger-ui";
String actual = abstractSwaggerResourceResolver.findWebJarResourcePath(path);
assertTrue(Objects.isNull(actual));
} |
private static ByteBuf copiedBufferAscii(CharSequence string) {
boolean release = true;
// Mimic the same behavior as other copiedBuffer implementations.
ByteBuf buffer = ALLOC.heapBuffer(string.length());
try {
ByteBufUtil.writeAscii(buffer, string);
release = fa... | @Test
public void testCopiedBufferAscii() {
testCopiedBufferCharSequence("Some US_ASCII", CharsetUtil.US_ASCII);
} |
public static void saveHandler(Object handler) {
final HttpAsyncContext httpAsyncContext = getOrCreateContext();
httpAsyncContext.setHandler(handler);
} | @Test
public void saveHandler() {
final Object handler = new Object();
HttpAsyncUtils.saveHandler(handler);
Assert.assertEquals(handler, HttpAsyncUtils.getOrCreateContext().getHandler());
} |
protected SerializerFactory getSerializerFactory(boolean multipleClassLoader, boolean generic) {
if (generic) {
return multipleClassLoader ? new GenericMultipleClassLoaderSofaSerializerFactory() :
new GenericSingleClassLoaderSofaSerializerFactory();
} else {
retur... | @Test
public void getSerializerFactory() {
Assert.assertEquals(SingleClassLoaderSofaSerializerFactory.class,
serializer.getSerializerFactory(false, false).getClass());
Assert.assertEquals(MultipleClassLoaderSofaSerializerFactory.class,
serializer.getSerializerFactory(true, fa... |
@Override
public boolean hasOrdinal() {
switch (super.getVersion()) {
case DEFAULT_VERSION:
return true;
default:
return true;
}
} | @Test
public void testHasOrdinal() {
assertTrue(verDefault.hasOrdinal());
assertTrue(verCurrent.hasOrdinal());
} |
@Override
public <V> MultiLabel generateOutput(V label) {
if (label instanceof Collection) {
Collection<?> c = (Collection<?>) label;
List<Pair<String,Boolean>> dimensions = new ArrayList<>();
for (Object o : c) {
dimensions.add(MultiLabel.parseElement(o.t... | @Test
public void testGenerateOutput_null() {
MultiLabelFactory factory = new MultiLabelFactory();
assertThrows(NullPointerException.class, () -> factory.generateOutput(null));
assertThrows(NullPointerException.class, () -> factory.generateOutput(new HashSet<>(Arrays.asList("a", null, "b")))... |
@Override
public EncodedMessage transform(ActiveMQMessage message) throws Exception {
if (message == null) {
return null;
}
long messageFormat = 0;
Header header = null;
Properties properties = null;
Map<Symbol, Object> daMap = null;
Map<Symbol, O... | @Test
public void testConvertCompressedMapMessageToAmqpMessage() throws Exception {
ActiveMQMapMessage outbound = createMapMessage(true);
outbound.setString("property-1", "string");
outbound.setInt("property-2", 1);
outbound.setBoolean("property-3", true);
outbound.onSend();
... |
ProducerIdsBlock nextProducerBlock() {
return nextProducerBlock.get();
} | @Test
public void testGenerateProducerIds() {
for (int i = 0; i < 100; i++) {
generateProducerIds(producerIdControlManager, i % 4, 100);
}
assertEquals(new ProducerIdsBlock(3, 100000, 1000), producerIdControlManager.nextProducerBlock());
} |
@Override
public Path move(final Path file, final Path renamed, final TransferStatus status, final Delete.Callback delete, final ConnectionCallback callback) throws BackgroundException {
try {
final StoregateApiClient client = session.getClient();
final MoveFileRequest move = new Mov... | @Test
public void testMoveWithLock() throws Exception {
final StoregateIdProvider nodeid = new StoregateIdProvider(session);
final Path room = new StoregateDirectoryFeature(session, nodeid).mkdir(
new Path(String.format("/My files/%s", new AlphanumericRandomStringService().random()),
... |
@Override
protected Optional<LocalDate> extractField(String s) {
try {
return Optional.of(LocalDate.parse(s, formatter));
} catch (DateTimeParseException e) {
logger.log(Level.WARNING, e.getParsedString());
logger.log(Level.WARNING, String.format("Unable to parse ... | @Test
public void testValidBehaviour() {
String isoFormat = "uuuu-MM-dd";
DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern(isoFormat, Locale.US);
String isoInput = "1994-01-26";
DateExtractor isoExtractor = new DateExtractor("test-iso", "date-iso", isoFormat);
Loc... |
@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 importTemplatesWithZip() throws IOException {
// create 3 templates, so we have at least 3 of them
client.toBlocking().retrieve(POST("/api/v1/templates", createTemplate()), Template.class);
client.toBlocking().retrieve(POST("/api/v1/templates", createTemplate()), Template.class);
... |
static Optional<DataField> getTargetDataField(final Model model) {
DataType targetDataType = getTargetDataType(model.getMiningFunction(), model.getMathContext());
OpType targetOpType = getTargetOpType(model.getMiningFunction());
if (targetDataType == null || targetOpType == null) {
r... | @Test
void getTargetDataField() throws Exception {
final InputStream inputStream = getFileInputStream(NO_TARGET_FIELD_SAMPLE);
final PMML pmml = org.jpmml.model.PMMLUtil.unmarshal(inputStream);
final Model model = pmml.getModels().get(0);
Optional<DataField> optionalDataField = KiePM... |
public static PCollectionRowTuple empty(Pipeline pipeline) {
return new PCollectionRowTuple(pipeline);
} | @Test
public void testEmpty() {
String tag = "collection1";
assertFalse(PCollectionRowTuple.empty(pipeline).has(tag));
} |
public abstract void verify(String value); | @Test
public void testBooleanAttribute() {
BooleanAttribute booleanAttribute = new BooleanAttribute("bool.key", false, false);
Assert.assertThrows(RuntimeException.class, () -> booleanAttribute.verify(""));
Assert.assertThrows(RuntimeException.class, () -> booleanAttribute.verify("a"));
... |
public static <T> boolean isNotNullOrEmpty(Collection<T> collection) {
return !isNullOrEmpty(collection);
} | @Test
void isNotNullOrEmptyIsFalseForEmptyArray() {
assertThat(isNotNullOrEmpty(new String[]{})).isFalse();
} |
public T send() throws IOException {
return web3jService.send(this, responseType);
} | @Test
public void testEthGetTransactionByBlockHashAndIndex() throws Exception {
web3j.ethGetTransactionByBlockHashAndIndex(
"0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331",
BigInteger.ZERO)
.send();
verifyResult(
... |
@Override
public int hashCode() {
return underlying().hashCode();
} | @Test
public void testHashCode() {
final HashPMap<Object, Object> mock = mock(HashPMap.class);
assertEquals(mock.hashCode(), new PCollectionsImmutableMap<>(mock).hashCode());
final HashPMap<Object, Object> someOtherMock = mock(HashPMap.class);
assertNotEquals(mock.hashCode(), new PCo... |
static int getIndex(CharSequence name) {
HeaderNameIndex entry = getEntry(name);
return entry == null ? NOT_FOUND : entry.index;
} | @Test
public void testExistingHeaderName() {
assertEquals(6, HpackStaticTable.getIndex(":scheme"));
} |
@Override
public String convert(final ReadwriteSplittingRuleConfiguration ruleConfig) {
if (ruleConfig.getDataSourceGroups().isEmpty()) {
return "";
}
StringBuilder result = new StringBuilder(ReadwriteSplittingDistSQLConstants.CREATE_READWRITE_SPLITTING_RULE);
Iterator<Re... | @Test
void assertConvertWithEmptyDataSources() {
ReadwriteSplittingRuleConfiguration readwriteSplittingRuleConfig = mock(ReadwriteSplittingRuleConfiguration.class);
when(readwriteSplittingRuleConfig.getDataSourceGroups()).thenReturn(Collections.emptyList());
ReadwriteSplittingRuleConfigurati... |
@Override
public double p(double x) {
return Math.exp(-np * Math.log(1.0 + x * x / nu) + fac) / Math.sqrt(Math.PI * nu);
} | @Test
public void testP() {
System.out.println("p");
TDistribution instance = new TDistribution(20);
instance.rand();
assertEquals(2.660085e-09, instance.p(-10.0), 1E-16);
assertEquals(0.05808722, instance.p(-2.0), 1E-7);
assertEquals(0.2360456, instance.p(-1.0), 1E-7... |
@Override
public int size() {
if (entries == null) {
return 0;
}
return entries.size();
} | @Test
public void testSize_whenNull() {
ResultSet resultSet = new ResultSet(null, IterationType.KEY);
assertEquals(0, resultSet.size());
} |
public Node parse() throws ScanException {
if (tokenList == null || tokenList.isEmpty())
return null;
return E();
} | @Test
public void withDefault() throws ScanException {
Tokenizer tokenizer = new Tokenizer("${b:-c}");
Parser parser = new Parser(tokenizer.tokenize());
Node node = parser.parse();
Node witness = new Node(Node.Type.VARIABLE, new Node(Node.Type.LITERAL, "b"));
witness.defaultPart = new Node(Node.Ty... |
public String generateInvalidPayloadExceptionMessage(final byte[] hl7Bytes) {
if (hl7Bytes == null) {
return "HL7 payload is null";
}
return generateInvalidPayloadExceptionMessage(hl7Bytes, hl7Bytes.length);
} | @Test
public void testGenerateInvalidPayloadExceptionMessageWithLengthSmallerThanArraySize() {
byte[] payload = TEST_MESSAGE.getBytes();
String message = hl7util.generateInvalidPayloadExceptionMessage(payload, 10);
assertEquals("The HL7 payload terminating byte [0x7c] is incorrect - expecte... |
@Override
public CompletableFuture<T> toCompletableFuture()
{
return _task.toCompletionStage().toCompletableFuture();
} | @Test
public void testCreateStageFromValue() throws Exception
{
String testResult = "testCreateStageFromValue";
ParSeqBasedCompletionStage<String> stageFromValue =
_parSeqBasedCompletionStageFactory.buildStageFromValue(testResult);
Assert.assertEquals(testResult, stageFromValue.toCompletableFutu... |
public boolean isRegisteredUser(@Nonnull final JID user, final boolean checkRemoteDomains) {
if (xmppServer.isLocal(user)) {
try {
getUser(user.getNode());
return true;
}
catch (final UserNotFoundException e) {
return false;
... | @Test
public void isRegisteredUserTrueWillReturnTrueForLocalUsers() {
final boolean result = userManager.isRegisteredUser(new JID(USER_ID, Fixtures.XMPP_DOMAIN, null), true);
assertThat(result, is(true));
} |
public FEELFnResult<String> invoke(@ParameterName("string") String string) {
if ( string == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "string", "cannot be null"));
} else {
return FEELFnResult.ofResult( string.toLowerCase() );
}
} | @Test
void invokeLowercaseString() {
FunctionTestUtil.assertResult(stringLowerCaseFunction.invoke("teststring"), "teststring");
} |
@Override
public KsMaterializedQueryResult<WindowedRow> get(
final GenericKey key,
final int partition,
final Range<Instant> windowStart,
final Range<Instant> windowEnd,
final Optional<Position> position
) {
try {
final ReadOnlySessionStore<GenericKey, GenericRow> store = sta... | @Test
public void shouldReturnValueIfSessionStartsAtLowerBoundIfLowerStartBoundClosed() {
// Given:
final Range<Instant> startBounds = Range.closed(
LOWER_INSTANT,
UPPER_INSTANT
);
final Instant wend = LOWER_INSTANT.plusMillis(1);
givenSingleSession(LOWER_INSTANT, wend);
// W... |
public static SearchTypeError parse(Query query, String searchTypeId, ElasticsearchException ex) {
if (isSearchTypeAbortedError(ex)) {
return new SearchTypeAbortedError(query, searchTypeId, ex);
}
Throwable possibleResultWindowException = ex;
int attempt = 0;
while ... | @Test
void returnsResultWindowLimitError() {
final ElasticsearchException elasticsearchException = new ElasticsearchException("Result window is too large, [from + size] must be less than or equal to: [42]");
final SearchTypeError error = SearchTypeErrorParser.parse(query, "searchTypeId", elasticsear... |
public void addValueProviders(final String segmentName,
final RocksDB db,
final Cache cache,
final Statistics statistics) {
if (storeToValueProviders.isEmpty()) {
logger.debug("Adding metrics record... | @Test
public void shouldNotAddItselfToRecordingTriggerWhenNotEmpty() {
recorder.addValueProviders(SEGMENT_STORE_NAME_1, dbToAdd1, cacheToAdd1, statisticsToAdd1);
verify(recordingTrigger).addMetricsRecorder(recorder);
recorder.addValueProviders(SEGMENT_STORE_NAME_2, dbToAdd2, cacheToAdd2, s... |
@Override
public String getName() {
return name;
} | @Test
public void testGetName() {
assertNull(null, queueConfig.getName());
} |
@CanIgnoreReturnValue
public final Ordered containsAtLeast(
@Nullable Object k0, @Nullable Object v0, @Nullable Object... rest) {
return containsAtLeastEntriesIn(accumulateMultimap(k0, v0, rest));
} | @Test
public void containsAtLeastVarargRespectsDuplicatesFailure() {
ImmutableListMultimap<Integer, String> actual =
ImmutableListMultimap.of(3, "one", 3, "two", 4, "five", 4, "five");
expectFailureWhenTestingThat(actual).containsAtLeast(3, "one", 3, "one", 3, "one", 4, "five");
assertFailureKeys... |
public static SinkConfig validateUpdate(SinkConfig existingConfig, SinkConfig newConfig) {
SinkConfig mergedConfig = clone(existingConfig);
if (!existingConfig.getTenant().equals(newConfig.getTenant())) {
throw new IllegalArgumentException("Tenants differ");
}
if (!existingC... | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Input Topics cannot be altered")
public void testMergeDifferentInputs() {
SinkConfig sinkConfig = createSinkConfig();
SinkConfig newSinkConfig = createUpdatedSinkConfig("topicsPattern", "Different");
... |
public String createRegexForUrlTemplate(String url, String placeholder) {
String transformedUrl = Arrays.stream(StringUtils.splitByWholeSeparator(url, placeholder))
.map(part -> StringUtils.isBlank(part) ? part : Pattern.quote(part))
.collect(Collectors.joining(".*?"));
r... | @Test
public void createRegexForTemplateUrl() {
String url = "https://example.com/api/lookup?key=message_key&a=b&c=message_key&e=f";
String template = "https://example.com/api/lookup?key=${key}&a=b&c=${key}&e=f";
String expected = "^\\Qhttps://example.com/api/lookup?key=\\E.*?\\Q&a=b&c=\\E.*... |
@Override
public boolean hasContent() {
switch (super.getVersion()) {
case DEFAULT_VERSION:
return true;
default:
return true;
}
} | @Test
public void testHasContent() {
assertTrue(verDefault.hasContent());
assertTrue(verCurrent.hasContent());
} |
public ClientFailoverConfig setClientConfigs(List<ClientConfig> clientConfigs) {
clientConfigs.forEach(this::validateClientConfig);
this.clientConfigs = clientConfigs;
return this;
} | @Test
public void testSetClientConfigs_WithOffReconnectMode_ShouldThrowInvalidConfigException() {
ClientConfig clientConfig1 = new ClientConfig();
ClientConfig clientConfig2 = new ClientConfig()
.setConnectionStrategyConfig(new ClientConnectionStrategyConfig().setReconnectMode(OFF));... |
@Override
public Serde.Deserializer deserializer(String topic, Serde.Target type) {
return new Serde.Deserializer() {
@SneakyThrows
@Override
public DeserializeResult deserialize(RecordHeaders headers, byte[] data) {
try {
UnknownFieldSet unknownFields = UnknownFi... | @Test
void deserializeInvalidMessage() {
var deserializer = serde.deserializer(DUMMY_TOPIC, Serde.Target.VALUE);
assertThatThrownBy(() -> deserializer.deserialize(null, new byte[] { 1, 2, 3 }))
.isInstanceOf(ValidationException.class)
.hasMessageContaining("Protocol message contained an invali... |
@Deprecated
public void add(Promise promise) {
add((Future) promise);
} | @Test
public void testAddNullPromise() {
assertThrows(NullPointerException.class, new Executable() {
@Override
public void execute() {
combiner.add(null);
}
});
} |
@Override
public Mono<ListResult<CategoryVo>> list(Integer page, Integer size) {
var listOptions = new ListOptions();
listOptions.setFieldSelector(FieldSelector.of(
notEqual("spec.hideFromList", BooleanUtils.TRUE)
));
return client.listBy(Category.class, listOptions,
... | @Test
void list() {
ListResult<Category> categories = new ListResult<>(1, 10, 3,
categories().stream()
.sorted(CategoryFinderImpl.defaultComparator())
.toList());
when(client.listBy(eq(Category.class), any(ListOptions.class), any(PageRequest.class)))
... |
long nextRecordingId()
{
return nextRecordingId;
} | @Test
void shouldReadNextRecordingIdFromCatalogHeader() throws IOException
{
final long nextRecordingId = 10101010;
setNextRecordingId(nextRecordingId);
try (Catalog catalog = new Catalog(archiveDir, null, 0, CAPACITY, clock, null, segmentFileBuffer))
{
assertEquals(... |
public static String parsingEndpointRule(String endpointUrl) {
// If entered in the configuration file, the priority in ENV will be given priority.
if (endpointUrl == null || !PATTERN.matcher(endpointUrl).find()) {
// skip retrieve from system property and retrieve directly from system env
... | @Test
void testParsingEndpointRuleFromSystemWithParam() {
System.setProperty(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_ENDPOINT_URL, "alibaba_aliware_endpoint_url");
assertEquals("alibaba_aliware_endpoint_url", ParamUtil.parsingEndpointRule("${abc:xxx}"));
} |
public RuntimeOptionsBuilder parse(String... args) {
return parse(Arrays.asList(args));
} | @Test
void clobbers_line_filters_from_cli_if_tags_are_specified_in_env() {
RuntimeOptions runtimeOptions = parser
.parse("file:path/to.feature")
.build();
RuntimeOptions options = new CucumberPropertiesParser()
.parse(singletonMap(FILTER_TAGS_PROPERTY... |
public static Builder forCurrentMagic(ProduceRequestData data) {
return forMagic(RecordBatch.CURRENT_MAGIC_VALUE, data);
} | @Test
public void shouldBeFlaggedAsIdempotentWhenIdempotentRecords() {
final MemoryRecords memoryRecords = MemoryRecords.withIdempotentRecords(1, Compression.NONE, 1L,
(short) 1, 1, 1, simpleRecord);
final ProduceRequest request = ProduceRequest.forCurrentMagic(new ProduceRequestData... |
@Override
public ServletStream stream() {
return stream;
} | @Test
public void set_status() {
underTest.stream().setStatus(404);
verify(response).setStatus(404);
} |
@Override
public Number getMetricValue() {
long currentCount = counter.getCount();
long difference = currentCount - lastReportCount;
currentReportCount = currentCount;
return difference;
} | @Test
void testGetMetricValue() {
final Counter backingCounter = new SimpleCounter();
final DCounter counter =
new DCounter(
backingCounter, "counter", "localhost", Collections.emptyList(), () -> 0);
// sane initial state
assertThat(counter.ge... |
@Override
public String getApiUrl() {
return endpoint.getApiUri();
} | @Test
public void testServerGithubEnterpriseTopLevelUrl() throws Exception {
// Create a server
Map resp = request()
.status(400)
.jwtToken(token)
.crumb( crumb )
.data(MapsHelper.of(
"name", "My Server",
"apiUrl", getAp... |
@Override
public Local create(final Path file) {
return this.create(String.format("%s-%s", new AlphanumericRandomStringService().random(), file.getName()));
} | @Test
public void testCreateContainer() {
final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator);
final String s = System.getProperty("file.separator");
final Path file = new Path("/container", EnumSet.of(Path.Type.directory));
file.attributes... |
static int decodeLiteral(byte tag, ByteBuf in, ByteBuf out) {
in.markReaderIndex();
int length;
switch(tag >> 2 & 0x3F) {
case 60:
if (!in.isReadable()) {
return NOT_ENOUGH_INPUT;
}
length = in.readUnsignedByte();
break;
... | @Test
public void testDecodeLiteral() throws Exception {
ByteBuf in = Unpooled.wrappedBuffer(new byte[] {
0x05, // preamble length
0x04 << 2, // literal tag + length
0x6e, 0x65, 0x74, 0x74, 0x79 // "netty"
});
ByteBuf out = Unpooled.buffer(5);
snap... |
public ScriptBuilder number(long num) {
return number(chunks.size(), num);
} | @Test
public void testNumber() {
for (int i = -100; i <= 100; i++) {
Script s = new ScriptBuilder().number(i).build();
for (ScriptChunk ch : s.chunks()) {
assertTrue(Integer.toString(i), ch.isShortestPossiblePushData());
}
}
} |
@Override
public boolean isDetected() {
return !isEmpty(system.envVariable("FCI_BUILD_ID"));
} | @Test
public void isDetected_givenNoEnvVariable_dontDetectCodeMagic() {
assertThat(underTest.isDetected()).isFalse();
} |
@Override
public void shutdown() {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void shutdown() {
client().getCluster().shutdown();
} |
@Override
public SmileResponse<T> handle(Request request, Response response)
{
byte[] bytes = readResponseBytes(response);
String contentType = response.getHeader(CONTENT_TYPE);
if ((contentType == null) || !MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) {
return new Smil... | @Test
public void testInvalidSmileGetValue()
{
byte[] invalidSmileBytes = "test".getBytes(UTF_8);
SmileResponse<User> response = handler.handle(null, mockResponse(OK, MEDIA_TYPE_SMILE, invalidSmileBytes));
try {
response.getValue();
fail("expected exception");
... |
@Override
public boolean add(final Integer value) {
return add(value.intValue());
} | @Test
public void addingAnElementTwiceDoesNothing() {
assertTrue(set.add(1));
assertFalse(set.add(1));
} |
public String encode(String name, String value) {
return encode(new DefaultCookie(name, value));
} | @Test
public void testRejectCookieValueWithSemicolon() {
assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() {
ClientCookieEncoder.STRICT.encode(new DefaultCookie("myCookie", "foo;bar"));
}
});
} |
public static <K> KStreamHolder<K> build(
final KStreamHolder<K> stream,
final StreamSelectKey<K> selectKey,
final RuntimeBuildContext buildContext
) {
return build(stream, selectKey, buildContext, PartitionByParamsFactory::build);
} | @Test
public void shouldReturnCorrectSchema() {
// When:
final KStreamHolder<GenericKey> result = StreamSelectKeyBuilder
.build(stream, selectKey, buildContext, paramBuilder);
// Then:
assertThat(result.getSchema(), is(RESULT_SCHEMA));
} |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 0 && "getDays".equals(methodName)) {
return SelLong.of((long) val.getDays());
} else if (args.length == 2 && "daysBetween".equals(methodName)) {
return new SelJodaDateTimeDays(
Days.daysBetween(
... | @Test(expected = UnsupportedOperationException.class)
public void testInvalidCallArg() {
one.call("getDays", new SelType[] {SelType.NULL});
} |
public static KafkaPool fromCrd(
Reconciliation reconciliation,
Kafka kafka,
KafkaNodePool pool,
NodeIdAssignment idAssignment,
Storage oldStorage,
OwnerReference ownerReference,
SharedEnvironmentProvider sharedEnvironmentProvider
)... | @Test
public void testKafkaPoolConfigureOptionsConflict() {
KafkaNodePool pool = new KafkaNodePoolBuilder(POOL)
.editSpec()
.withResources(new ResourceRequirementsBuilder().withRequests(Map.of("cpu", new Quantity("4"), "memory", new Quantity("16Gi"))).build())
... |
@Override
public FTPFile parseFTPEntry(String entry) {
if(matches(entry)) {
String typeStr = group(1);
String usr = group(15);
String grp = group(16);
String filesize = group(17);
String datestr = group(18) + " " + group(19);
String nam... | @Test
public void testParse() {
FTPFile parsed;
//#1213
parsed = parser.parseFTPEntry(
"-rw-r--r-- FTP User 10439 Apr 20 05:29 ASCheckbox_2_0.zip"
);
assertNotNull(parsed);
assertEquals("ASCheckbox_2_0.zip", parsed.getName());
assertEquals... |
@Bean("MigrationSteps")
public MigrationSteps provide(InternalMigrationStepRegistry migrationStepRegistry, DbVersion... dbVersions) {
Arrays.stream(dbVersions).forEach(dbVersion -> dbVersion.addSteps(migrationStepRegistry));
return migrationStepRegistry.build();
} | @Test
public void provide_calls_DbVersion_addStep_in_order() {
DbVersion dbVersion1 = newMockFailingOnSecondBuildCall();
DbVersion dbVersion2 = newMockFailingOnSecondBuildCall();
DbVersion dbVersion3 = newMockFailingOnSecondBuildCall();
InOrder inOrder = inOrder(dbVersion1, dbVersion2, dbVersion3);
... |
@Override
public void onProcessingTime(long time) throws IOException {
for (FileWriterBucket<IN> bucket : activeBuckets.values()) {
bucket.onProcessingTime(time);
}
registerNextBucketInspectionTimer();
} | @Test
void testOnProcessingTime(@TempDir java.nio.file.Path tempDir) throws Exception {
Path path = new Path(tempDir.toUri());
// Create the processing timer service starts from 10.
ManuallyTriggeredProcessingTimeService processingTimeService =
new ManuallyTriggeredProcessin... |
public static URI buildExternalUri(@NotNull MultivaluedMap<String, String> httpHeaders, @NotNull URI defaultUri) {
Optional<URI> externalUri = Optional.empty();
final List<String> headers = httpHeaders.get(HttpConfiguration.OVERRIDE_HEADER);
if (headers != null && !headers.isEmpty()) {
... | @Test
public void buildEndpointUriEnsuresTrailingSlash() {
final MultivaluedMap<String, String> httpHeaders = new MultivaluedHashMap<>();
final URI endpointUri = URI.create("http://graylog.example.com");
final URI endpointUri2 = URI.create("http://graylog.example.com/");
assertThat(... |
@Override
public void onDataReceived(@NonNull final BluetoothDevice device, @NonNull final Data data) {
super.onDataReceived(device, data);
if (data.size() != 1) {
onInvalidDataReceived(device, data);
return;
}
final int type = data.getIntValue(Data.FORMAT_UINT8, 0);
onTemperatureTypeReceived(device,... | @Test
public void onMeasurementIntervalReceived() {
final ProfileReadResponse response = new TemperatureTypeDataCallback() {
@Override
public void onTemperatureTypeReceived(@NonNull final BluetoothDevice device,
final int type) {
called = true;
assertEquals("Temperature Type", HealthTher... |
public static ClusterAllocationDiskSettings create(boolean enabled, String low, String high, String floodStage) {
if (!enabled) {
return ClusterAllocationDiskSettings.create(enabled, null);
}
return ClusterAllocationDiskSettings.create(enabled, createWatermarkSettings(low, high, floo... | @Test
public void createWithoutSettingsWhenThresholdDisabled() throws Exception {
ClusterAllocationDiskSettings settings = ClusterAllocationDiskSettingsFactory.create(false, "", "", "");
assertThat(settings).isInstanceOf(ClusterAllocationDiskSettings.class);
assertThat(settings.ThresholdEna... |
protected void copyAndClose( InputStream inputStream, OutputStream outputStream ) throws IOException {
IOUtils.copy( inputStream, outputStream );
outputStream.flush();
IOUtils.closeQuietly( outputStream );
} | @Test
public void testCopyAndClose() throws Exception {
try ( MockedStatic<IOUtils> ioUtilsMockedStatic1 = mockStatic( IOUtils.class ) ) {
int bytesCopied = 10;
ioUtilsMockedStatic1.when( () -> IOUtils.copy( any( InputStream.class ), any( OutputStream.class ) ) ).thenReturn( bytesCopied );
// V... |
@SuppressWarnings("unchecked")
@Override
public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues(
MoveApplicationAcrossQueuesRequest request) throws YarnException {
ApplicationId applicationId = request.getApplicationId();
UserGroupInformation callerUGI = getCallerUgi(applicationId,
... | @Test
public void testMoveApplicationAdminTargetQueue() throws Exception {
ApplicationId applicationId = getApplicationId(1);
UserGroupInformation aclUGI = UserGroupInformation.getCurrentUser();
QueueACLsManager queueAclsManager = getQueueAclManager("allowed_queue",
QueueACL.ADMINISTER_QUEUE, aclU... |
public int login(final String username, final String password)
throws SQLException {
var sql = "select count(*) from USERS where username=? and password=?";
ResultSet resultSet = null;
try (var connection = dataSource.getConnection();
var preparedStatement =
connection.pr... | @Test
void loginShouldFail() throws SQLException {
var dataSource = createDataSource();
var userTableModule = new UserTableModule(dataSource);
var user = new User(1, "123456", "123456");
assertEquals(0, userTableModule.login(user.getUsername(),
user.getPassword()));
} |
@Override
public PathAttributes find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return PathAttributes.EMPTY;
}
if(containerService.isContainer(file)) {
final PathAttributes attributes = new PathAttributes();
... | @Test
public void testDeletedWithMarker() throws Exception {
final Path bucket = new Path("versioning-test-eu-central-1-cyberduck", EnumSet.of(Path.Type.volume, Path.Type.directory));
final Path test = new S3TouchFeature(session, new S3AccessControlListFeature(session)).touch(new Path(bucket, new Al... |
@Override
public boolean containsValue(final Object value)
{
return containsValue(((Long)value).longValue());
} | @Test
public void shouldNotContainValueForAMissingEntry() {
assertFalse(map.containsValue(1L));
} |
@PostMapping("")
public ShenyuAdminResult createRule(@Valid @RequestBody final RuleDTO ruleDTO) {
Integer createCount = ruleService.createOrUpdate(ruleDTO);
return ShenyuAdminResult.success(ShenyuResultMessage.CREATE_SUCCESS, createCount);
} | @Test
public void testCreateRule() throws Exception {
RuleConditionDTO ruleConditionDTO = RuleConditionDTO.builder()
.id("888")
.ruleId("666")
.paramType("uri")
.operator("match")
.paramName("/")
.paramValue("tes... |
@Override
public AppResponse process(Flow flow, MijnDigidSessionRequest request) throws FlowNotDefinedException, IOException, NoSuchAlgorithmException, SharedServiceClientException {
appSession = appSessionService.getSession(request.getMijnDigidSessionId());
appAuthenticator = appAuthenticatorServic... | @Test
public void appSwitchDisabledTest() throws FlowNotDefinedException, SharedServiceClientException, IOException, NoSuchAlgorithmException {
//given
when(appSessionService.getSession(any())).thenReturn(mockedAppSession);
when(appAuthenticatorService.findByUserAppId(any())).thenReturn(mock... |
@Override // SELECT 场景
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
// 获得 Mapper 对应的数据权限的规则
List<DataPermissionRule> rules = ruleFactory.getDataPermissionRule(ms.getId());
if (mappedSta... | @Test // 不存在规则,且不匹配
public void testBeforeQuery_withoutRule() {
try (MockedStatic<PluginUtils> pluginUtilsMock = mockStatic(PluginUtils.class)) {
// 准备参数
MappedStatement mappedStatement = mock(MappedStatement.class);
BoundSql boundSql = mock(BoundSql.class);
... |
public ArtifactResolveRequest startArtifactResolveProcess(HttpServletRequest httpServletRequest) throws SamlParseException {
try {
final var artifactResolveRequest = validateRequest(httpServletRequest);
final var samlSession = updateArtifactResolveRequestWithSamlSession(artifactResolveRe... | @Test
void parseArtifactResolveWithWrongConnectionEntityId() throws SamlSessionException {
samlSession.setConnectionEntityId("wrongConnectionEntityId");
when(samlSessionServiceMock.loadSession(anyString())).thenReturn(samlSession);
SamlParseException exception = assertThrows(SamlParseExcept... |
public static String validColumnName(String identifier)
{
if (identifier.isEmpty() || identifier.equals(EMPTY_COLUMN_NAME)) {
return "\"\"";
}
return validIdentifier(identifier);
} | @Test
public void testValidColumnName()
{
assertEquals("foo", validColumnName("foo"));
assertEquals("\"\"", validColumnName(CassandraCqlUtils.EMPTY_COLUMN_NAME));
assertEquals("\"\"", validColumnName(""));
assertEquals("\"select\"", validColumnName("select"));
} |
@Udf
public String ucase(
@UdfParameter(description = "The string to upper-case") final String input) {
if (input == null) {
return null;
}
return input.toUpperCase();
} | @Test
public void shouldConvertToUpperCase() {
final String result = udf.ucase("FoO bAr");
assertThat(result, is("FOO BAR"));
} |
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, ... | @Test
public void unorderedFlattenIndex_with_valueFunction_fails_if_value_function_returns_null() {
assertThatThrownBy(() -> SINGLE_ELEMENT2_LIST.stream().collect(unorderedFlattenIndex(MyObj2::getId, s -> null)))
.isInstanceOf(NullPointerException.class)
.hasMessage("Value function can't return null")... |
public static LogCollector<ShenyuRequestLog> getInstance() {
return INSTANCE;
} | @Test
public void testAbstractLogCollector() throws Exception {
PulsarLogCollector.getInstance().start();
Field field1 = AbstractLogCollector.class.getDeclaredField("started");
field1.setAccessible(true);
Assertions.assertEquals(field1.get(PulsarLogCollector.getInstance()).toString()... |
@Override
public void handleWayTags(int edgeId, EdgeIntAccess edgeIntAccess, ReaderWay readerWay, IntsRef relationFlags) {
List<Map<String, Object>> nodeTags = readerWay.getTag("node_tags", null);
if (nodeTags == null)
return;
for (int i = 0; i < nodeTags.size(); i++) {
... | @Test
public void testMarked() {
EdgeIntAccess edgeIntAccess = new ArrayEdgeIntAccess(1);
int edgeId = 0;
parser.handleWayTags(edgeId, edgeIntAccess, createReader(new HashMap<>()), null);
assertEquals(Crossing.MISSING, crossingEV.getEnum(false, edgeId, edgeIntAccess));
parse... |
@Override
public Iterator<Object> iterateObjects() {
return new CompositeObjectIterator(concreteStores, true);
} | @Test
public void iterateObjectsReturnsObjectsOfAllTypes() throws Exception {
String aStringValue = "a string";
BigDecimal bigDecimalValue = new BigDecimal("1");
insertObjectWithFactHandle(aStringValue);
insertObjectWithFactHandle(bigDecimalValue);
Collection<Object> result... |
@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 testMissedDoubleMatch() {
StreamRule rule = getSampleRule();
rule.setValue("25");
Message msg = getSampleMessage();
msg.addField("something", "27.45");
StreamRuleMatcher matcher = getMatcher(rule);
assertFalse(matcher.match(msg, rule));
} |
public static ResourceBundleUtil getInstance() {
return INSTANCE;
} | @Test
void getInstance() {
Assertions.assertNotNull(ResourceBundleUtil.getInstance());
} |
public void schedule(final ScheduledHealthCheck check, final boolean healthy) {
unschedule(check.getName());
final Duration interval;
if (healthy) {
interval = check.getSchedule().getCheckInterval();
} else {
interval = check.getSchedule().getDowntimeInterval();
... | @Test
void shouldRescheduleCheckForHealthyDependency() {
final String name = "test";
final Schedule schedule = new Schedule();
final ScheduledFuture future = mock(ScheduledFuture.class);
when(future.cancel(true)).thenReturn(true);
final ScheduledHealthCheck check = mock(Sch... |
public MessageListener messageListener(MessageListener messageListener, boolean addConsumerSpan) {
if (messageListener instanceof TracingMessageListener) return messageListener;
return new TracingMessageListener(messageListener, this, addConsumerSpan);
} | @Test void messageListener_traces() {
jmsTracing.messageListener(mock(MessageListener.class), false)
.onMessage(message);
assertThat(testSpanHandler.takeLocalSpan().name()).isEqualTo("on-message");
} |
void shutdown(@Observes ShutdownEvent event) {
if (jobRunrBuildTimeConfiguration.backgroundJobServer().enabled()) {
backgroundJobServerInstance.get().stop();
}
if (jobRunrBuildTimeConfiguration.dashboard().enabled()) {
dashboardWebServerInstance.get().stop();
}
... | @Test
void jobRunrStarterDoesNotStopBackgroundJobServerIfNotConfigured() {
when(backgroundJobServerConfiguration.enabled()).thenReturn(false);
jobRunrStarter.shutdown(new ShutdownEvent());
verify(backgroundJobServerInstance, never()).get();
} |
public int poll(final FragmentHandler fragmentHandler, final int fragmentLimit)
{
if (isClosed)
{
return 0;
}
final long position = subscriberPosition.get();
return TermReader.read(
activeTermBuffer(position),
(int)position & termLengthMa... | @Test
void shouldReportCorrectPositionOnReception()
{
final long initialPosition = computePosition(INITIAL_TERM_ID, 0, POSITION_BITS_TO_SHIFT, INITIAL_TERM_ID);
position.setOrdered(initialPosition);
final Image image = createImage();
insertDataFrame(INITIAL_TERM_ID, offsetForFra... |
@ConstantFunction(name = "bitShiftRightLogical", argTypes = {SMALLINT, BIGINT}, returnType = SMALLINT)
public static ConstantOperator bitShiftRightLogicalSmallInt(ConstantOperator first, ConstantOperator second) {
short s = first.getSmallint();
int i = s >= 0 ? s : (((int) s) + 65536);
retur... | @Test
public void bitShiftRightLogicalSmallInt() {
assertEquals(1, ScalarOperatorFunctions.bitShiftRightLogicalSmallInt(O_SI_10, O_BI_3).getSmallint());
} |
@Override
public TGetDictQueryParamResponse getDictQueryParam(TGetDictQueryParamRequest request) throws TException {
Database db = GlobalStateMgr.getCurrentState().getDb(request.getDb_name());
if (db == null) {
throw new SemanticException("Database %s is not found", request.getDb_name())... | @Test
public void testgetDictQueryParam() throws TException {
FrontendServiceImpl impl = new FrontendServiceImpl(exeEnv);
TGetDictQueryParamRequest request = new TGetDictQueryParamRequest();
request.setDb_name("test");
request.setTable_name("site_access_auto");
TGetDictQuery... |
static int run(File buildResult, Path root) throws IOException {
// parse included dependencies from build output
final Map<String, Set<Dependency>> modulesWithBundledDependencies =
combineAndFilterFlinkDependencies(
ShadeParser.parseShadeOutput(buildResult.toPath... | @Test
void testRunSkipsNonDeployedModules() throws IOException {
final String moduleName = "test";
final Dependency bundledDependency = Dependency.create("a", "b", "c", null);
final Map<String, Set<Dependency>> bundleDependencies = new HashMap<>();
bundleDependencies.put(moduleName, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.