focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public List<Object> handle(String targetName, List<Object> instances, RequestData requestData) {
if (requestData == null) {
return super.handle(targetName, instances, null);
}
if (!shouldHandle(instances)) {
return instances;
}
List<Object> r... | @Test
public void testGetTargetInstancesByRequestWithTags() {
config.setUseRequestRouter(true);
config.setRequestTags(Arrays.asList("foo", "bar", "version"));
List<Object> instances = new ArrayList<>();
ServiceInstance instance1 = TestDefaultServiceInstance.getTestDefaultServiceInsta... |
public static Getter newMethodGetter(Object object, Getter parent, Method method, String modifier) throws Exception {
return newGetter(object, parent, modifier, method.getReturnType(), method::invoke,
(t, et) -> new MethodGetter(parent, method, modifier, t, et));
} | @Test
public void newMethodGetter_whenExtractingFromEmpty_Collection_AndReducerSuffixInNotEmpty_thenReturnNullGetter()
throws Exception {
OuterObject object = OuterObject.emptyInner("name");
Getter getter = GetterFactory.newMethodGetter(object, null, innersCollectionMethod, "[any]");
... |
public static int randomInt() {
return getRandom().nextInt();
} | @Test
public void randomIntTest() {
final int c = RandomUtil.randomInt(10, 100);
assertTrue(c >= 10 && c < 100);
} |
public static void update(@NonNull SystemState systemState, @NonNull ConfigMap configMap) {
Map<String, String> data = configMap.getData();
if (data == null) {
data = new LinkedHashMap<>();
configMap.setData(data);
}
JsonNode modifiedJson = JsonUtils.mapper()
... | @Test
void update() {
SystemState newSystemState = new SystemState();
newSystemState.setIsSetup(true);
ConfigMap configMap = new ConfigMap();
SystemState.update(newSystemState, configMap);
assertThat(configMap.getData().get(SystemState.GROUP)).isEqualTo("{\"isSetup\":true}")... |
public FloatArrayAsIterable usingTolerance(double tolerance) {
return new FloatArrayAsIterable(tolerance(tolerance), iterableSubject());
} | @Test
public void usingTolerance_contains_successWithExpectedLong() {
assertThat(array(1.0f, TOLERABLE_TWO, 3.0f)).usingTolerance(DEFAULT_TOLERANCE).contains(2L);
} |
@Override
public PollResult poll(long currentTimeMs) {
return pollInternal(
prepareFetchRequests(),
this::handleFetchSuccess,
this::handleFetchFailure
);
} | @Test
public void testFetchMaxPollRecords() {
buildFetcher(2);
assignFromUser(singleton(tp0));
subscriptions.seek(tp0, 1);
client.prepareResponse(matchesOffset(tidp0, 1), fullFetchResponse(tidp0, records, Errors.NONE, 100L, 0));
client.prepareResponse(matchesOffset(tidp0, 4... |
public List<Search> getAllForUser(SearchPermissions searchPermissions, Predicate<ViewDTO> viewReadPermission) {
return dbService.streamAll()
.filter(s -> hasReadPermissionFor(searchPermissions, viewReadPermission, s))
.collect(Collectors.toList());
} | @Test
public void includesSearchesPermittedViaViewsInList() {
final Search permittedSearch = mockSearchWithOwner("someone else");
mockSearchWithOwner("someone else");
final SearchUser searchUser = mock(SearchUser.class);
final ViewDTO viewDTO = mock(ViewDTO.class);
when(view... |
public static SerializableFunction<Row, Mutation> beamRowToMutationFn(
Mutation.Op operation, String table) {
return (row -> {
switch (operation) {
case INSERT:
return MutationUtils.createMutationFromBeamRows(Mutation.newInsertBuilder(table), row);
case DELETE:
return... | @Test
public void testCreateReplaceMutationFromRowWithNulls() {
Mutation expectedMutation = createMutationNulls(Mutation.Op.REPLACE);
Mutation mutation = beamRowToMutationFn(Mutation.Op.REPLACE, TABLE).apply(WRITE_ROW_NULLS);
assertEquals(expectedMutation, mutation);
} |
public Optional<Object> get(String path) {
if (path == null || path.trim().isEmpty()) {
throw new IllegalArgumentException(String.format("path [%s] is invalid", path));
}
path = validatePath(path);
if (path.equals("/")) {
return Optional.of(map);
}
... | @Test
public void testInvalidPaths() throws IOException {
YamlMapAccessor yamlMapAccessor = createYamlMapAccessor("/YamlMapAccessorTest.yaml");
try {
yamlMapAccessor.get("");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
... |
public static boolean isCommonFieldsEqual(Object source, Object target, String... ignoreProperties) {
if (null == source && null == target) {
return true;
}
if (null == source || null == target) {
return false;
}
final Map<String, Object> sourceFieldsMap = BeanUtil.beanToMap(source);
final Map<Strin... | @Test
public void isCommonFieldsEqualTest() {
final TestUserEntity userEntity = new TestUserEntity();
final TestUserDTO userDTO = new TestUserDTO();
userDTO.setAge(20);
userDTO.setName("takaki");
userDTO.setSex(1);
userDTO.setMobile("17812312023");
BeanUtil.copyProperties(userDTO, userEntity);
asser... |
@Override
public boolean isLoggedIn() {
return true;
} | @Test
public void isLoggedIn() {
assertThat(githubWebhookUserSession.isLoggedIn()).isTrue();
} |
public static Set<Result> anaylze(String log) {
Set<Result> results = new HashSet<>();
for (Rule rule : Rule.values()) {
Matcher matcher = rule.pattern.matcher(log);
if (matcher.find()) {
results.add(new Result(rule, log, matcher));
}
}
... | @Test
public void needJDK11() throws IOException {
CrashReportAnalyzer.Result result = findResultByRule(
CrashReportAnalyzer.anaylze(loadLog("/crash-report/need_jdk11.txt")),
CrashReportAnalyzer.Rule.NEED_JDK11);
} |
static int transformDictionaryWord(byte[] dst, int dstOffset, byte[] word, int wordOffset,
int len, Transform transform) {
int offset = dstOffset;
// Copy prefix.
byte[] string = transform.prefix;
int tmp = string.length;
int i = 0;
// In most cases tmp < 10 -> no benefits from System.arr... | @Test
public void testTrimAll() {
byte[] output = new byte[2];
byte[] input = "word".getBytes(StandardCharsets.UTF_8);
Transform transform = new Transform("[", WordTransformType.OMIT_FIRST_5, "]");
Transform.transformDictionaryWord(output, 0, input, 0, input.length, transform);
assertArrayEquals(o... |
public static <T> Map<String, T> jsonToMap(final String json, final Class<T> valueTypeRef) {
try {
JavaType t = MAPPER.getTypeFactory().constructParametricType(HashMap.class, String.class, valueTypeRef);
return MAPPER.readValue(json, t);
} catch (IOException e) {
LOG.... | @Test
public void testJsonToMap() {
Map<String, Object> stringObjectMap = JsonUtils.jsonToMap(EXPECTED_JSON);
assertEquals(stringObjectMap.get("name"), "test object");
} |
public Optional<String> getNodeName(String nodeId) {
return nodeNameCache.getUnchecked(nodeId);
} | @Test
public void getNodeNameReturnsNodeNameIfNodeIdIsValid() {
when(cluster.nodeIdToName("node_id")).thenReturn(Optional.of("Node Name"));
assertThat(nodeInfoCache.getNodeName("node_id")).contains("Node Name");
} |
@GetMapping(params = "show=all")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
public ConfigAllInfo detailConfigInfo(@RequestParam("dataId") String dataId, @RequestParam("group") String group,
@RequestParam(value = "tenant", required = false, defaultValue = StringUtils.EMPTY) Strin... | @Test
void testDetailConfigInfo() throws Exception {
ConfigAllInfo configAllInfo = new ConfigAllInfo();
configAllInfo.setDataId("test");
configAllInfo.setGroup("test");
configAllInfo.setCreateIp("localhost");
configAllInfo.setCreateUser("test");
when(configIn... |
@Override
public void delete(PageId pageId) throws IOException, PageNotFoundException {
Callable<Void> callable = () -> {
mPageStore.delete(pageId);
return null;
};
try {
mTimeLimter.callWithTimeout(callable, mTimeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
... | @Test
public void deleteTimeout() throws Exception {
mPageStore.setDeleteHanging(true);
try {
mTimeBoundPageStore.delete(PAGE_ID);
fail();
} catch (IOException e) {
assertTrue(e.getCause() instanceof TimeoutException);
}
} |
public static JoinParams create(
final ColumnName keyColName,
final LogicalSchema leftSchema,
final LogicalSchema rightSchema
) {
final boolean appendKey = neitherContain(keyColName, leftSchema, rightSchema);
return new JoinParams(
new KsqlValueJoiner(leftSchema.value().size(), right... | @Test
public void shouldBuildCorrectLeftKeyedSchema() {
// Given:
final ColumnName keyName = Iterables.getOnlyElement(LEFT_SCHEMA.key()).name();
// When:
final JoinParams joinParams = JoinParamsFactory.create(keyName, LEFT_SCHEMA, RIGHT_SCHEMA);
// Then:
assertThat(joinParams.getSchema(), is... |
public ValueAndTimestamp<V> get(final K key) {
if (timestampedStore != null) {
return timestampedStore.get(key);
}
if (versionedStore != null) {
final VersionedRecord<V> versionedRecord = versionedStore.get(key);
return versionedRecord == null
... | @Test
public void shouldGetNullFromTimestampedStore() {
givenWrapperWithTimestampedStore();
when(timestampedStore.get(KEY)).thenReturn(null);
assertThat(wrapper.get(KEY), nullValue());
} |
@EventListener(value = ContextClosedEvent.class)
public void listener() {
if (!isEnableGraceDown() || graceService == null) {
return;
}
graceService.shutdown();
} | @Test
public void listener() {
MockitoAnnotations.openMocks(this);
final GraceConfig graceConfig = new GraceConfig();
try (final MockedStatic<PluginServiceManager> pluginServiceManagerMockedStatic =
Mockito.mockStatic(PluginServiceManager.class);
final MockedStati... |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
if(file.isPlaceholder()) {
final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
if(DescriptiveUrl.... | @Test
public void testReadPath() throws Exception {
final DriveFileIdProvider fileid = new DriveFileIdProvider(session);
final Path directory = new DriveDirectoryFeature(session, fileid).mkdir(new Path(DriveHomeFinderService.MYDRIVE_FOLDER, new AlphanumericRandomStringService().random(), EnumSet.of(... |
public String getName() {
return name;
} | @Test
public void hasAName() throws Exception {
assertThat(handler.getName())
.isEqualTo("handler");
} |
public int find(String what) {
return find(what, 0);
} | @Test
public void testFind() throws Exception {
Text text = new Text("abcd\u20acbdcd\u20ac");
assertThat(text.find("abd")).isEqualTo(-1);
assertThat(text.find("ac")).isEqualTo(-1);
assertThat(text.find("\u20ac")).isEqualTo(4);
assertThat(text.find("\u20ac", 5)).isEqualTo(11);
} |
static String toDatabaseName(Namespace namespace, boolean skipNameValidation) {
if (!skipNameValidation) {
validateNamespace(namespace);
}
return namespace.level(0);
} | @Test
public void testToDatabaseNameFailure() {
List<Namespace> badNames =
Lists.newArrayList(
Namespace.of("db", "a"),
Namespace.of("db-1"),
Namespace.empty(),
Namespace.of(""),
Namespace.of(new String(new char[600]).replace("\0", "a")));
fo... |
@Override
public int compareTo(ResourceConfig other) {
return name.compareTo(other.name);
} | @Test
public void shouldCompareBasedOnName() {
ResourceConfig resourceConfigA = new ResourceConfig("aaa");
ResourceConfig resourceConfigB = new ResourceConfig("bbb");
assertThat(resourceConfigA.compareTo(resourceConfigB), is(org.hamcrest.Matchers.lessThan(0)));
assertThat(resourceCon... |
public int run() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
MetricsOutput metricsInfo = new MetricsOutput(mMetricsMasterClient.getMetrics());
try {
String json = objectMapper.writeValueAsString(metricsInfo);
mPrintStream.println(json);
} catch (JsonProcessingExcepti... | @Test
public void metrics() throws IOException {
MetricsCommand metricsCommand = new MetricsCommand(mMetricsMasterClient, mPrintStream);
metricsCommand.run();
checkOutput();
} |
@ThriftConstructor
public ThriftBufferResult(
String taskInstanceId,
long token,
long nextToken,
boolean bufferComplete,
long bufferedBytes,
List<ThriftSerializedPage> thriftSerializedPages)
{
checkArgument(!isNullOrEmpty(taskInstan... | @Test
public void testThriftBufferResult()
{
BufferResult bufferResult = new BufferResult("task-instance-id", 0, 0, false, 0, ImmutableList.of());
ThriftBufferResult thriftBufferResult = fromBufferResult(bufferResult);
BufferResult newBufferResult = thriftBufferResult.toBufferResult();
... |
public static Pair<String, String> encryptHandler(String dataId, String content) {
if (!checkCipher(dataId)) {
return Pair.with("", content);
}
Optional<String> algorithmName = parseAlgorithmName(dataId);
Optional<EncryptionPluginService> optional = algorithmName.flatMap(
... | @Test
void testEncryptHandler() {
Pair<String, String> pair = EncryptionHandler.encryptHandler("test-dataId", "content");
assertNotNull(pair);
} |
public boolean cancelTimerByCorrelationId(final long correlationId)
{
final Timer removedTimer = timerByCorrelationId.remove(correlationId);
if (null == removedTimer)
{
return false;
}
final int lastIndex = --size;
final Timer lastTimer = timers[lastIndex... | @Test
void cancelTimerByCorrelationIdIsANoOpIfNoTimersRegistered()
{
final PriorityHeapTimerService timerService = new PriorityHeapTimerService(mock(TimerHandler.class));
assertFalse(timerService.cancelTimerByCorrelationId(100));
} |
Optional<TextRange> mapRegion(@Nullable Region region, InputFile file) {
if (region == null) {
return Optional.empty();
}
int startLine = Objects.requireNonNull(region.getStartLine(), "No start line defined for the region.");
int endLine = Optional.ofNullable(region.getEndLine()).orElse(startLine)... | @Test
public void mapRegion_whenNullRegion_returnsEmpty() {
assertThat(regionMapper.mapRegion(null, INPUT_FILE)).isEmpty();
} |
@VisibleForTesting
@Override
List<String> cancelNonTerminalTasks(Workflow workflow) {
List<String> erroredTasks = new ArrayList<>();
// Update non-terminal tasks' status to CANCELED
for (Task task : workflow.getTasks()) {
if (!task.getStatus().isTerminal()) {
// Cancel the ones which are n... | @Test
public void testCancelNonTerminalTasks() {
Task startTask = new Task();
startTask.setTaskId(UUID.randomUUID().toString());
startTask.setTaskType(Constants.DEFAULT_START_STEP_NAME);
startTask.setStatus(Task.Status.IN_PROGRESS);
Task maestroTask = new Task();
maestroTask.setTaskId(UUID.ra... |
public static DescriptorDigest fromHash(String hash) throws DigestException {
if (!hash.matches(HASH_REGEX)) {
throw new DigestException("Invalid hash: " + hash);
}
return new DescriptorDigest(hash);
} | @Test
public void testCreateFromHash_failIncorrectLength() {
String badHash = createGoodHash('a') + 'a';
try {
DescriptorDigest.fromHash(badHash);
Assert.fail("Invalid hash should have caused digest creation failure.");
} catch (DigestException ex) {
Assert.assertEquals("Invalid hash: "... |
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 testToObject3() {
assertEquals(Collections.singletonMap("key", "value"), JacksonUtils.toObj("{\"key\":\"value\"}".getBytes(),
TypeUtils.parameterize(Map.class, String.class, String.class)));
assertEquals(Collections.singletonList(Collections.singletonMap("key", "value")),
... |
public void wrapMultiDispatch(final MessageExtBrokerInner msg) {
String multiDispatchQueue = msg.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH);
String[] queues = multiDispatchQueue.split(MixAll.MULTI_DISPATCH_QUEUE_SPLITTER);
Long[] queueOffsets = new Long[queues.length];
if (... | @Test
public void wrapMultiDispatch() throws RocksDBException {
MessageExtBrokerInner messageExtBrokerInner = buildMessageMultiQueue();
multiDispatch.wrapMultiDispatch(messageExtBrokerInner);
assertEquals(messageExtBrokerInner.getProperty(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET), "0,0... |
@Override
protected CouchDbEndpoint createEndpoint(String uri, String remaining, Map<String, Object> params) throws Exception {
CouchDbEndpoint endpoint = new CouchDbEndpoint(uri, remaining, this);
setProperties(endpoint, params);
return endpoint;
} | @Test
void testEndpointCreated() throws Exception {
Map<String, Object> params = new HashMap<>();
String uri = "couchdb:http://localhost:5984/db";
String remaining = "http://localhost:5984/db";
CouchDbEndpoint endpoint
= context.getComponent("couchdb", CouchDbCompon... |
public TableStats merge(TableStats other, @Nullable Set<String> partitionKeys) {
if (this.rowCount < 0 || other.rowCount < 0) {
return TableStats.UNKNOWN;
}
long rowCount =
this.rowCount >= 0 && other.rowCount >= 0
? this.rowCount + other.rowCo... | @Test
void testMergeLackColumnStats() {
Map<String, ColumnStats> colStats1 = new HashMap<>();
colStats1.put("a", new ColumnStats(4L, 5L, 2D, 3, 15, 2));
colStats1.put("b", new ColumnStats(4L, 5L, 2D, 3, 15, 2));
TableStats stats1 = new TableStats(30, colStats1);
Map<String, ... |
@VisibleForTesting
static BlobKey createKey(BlobType type) {
if (type == PERMANENT_BLOB) {
return new PermanentBlobKey();
} else {
return new TransientBlobKey();
}
} | @Test
void testToFromStringPermanentKey() {
testToFromString(BlobKey.createKey(PERMANENT_BLOB));
} |
@Override
public PageStoreDir allocate(String fileId, long fileLength) {
return mDirs.get(
Math.floorMod(mHashFunction.apply(fileId),
mDirs.size()));
} | @Test
public void hashDistributionTest() {
mAllocator = new HashAllocator(mDirs);
Map<Path, Integer> result = new HashMap<>();
int numFiles = 1_000_0;
for (int i = 0; i < numFiles; i++) {
PageStoreDir dir = mAllocator.allocate(String.valueOf(i), 0);
result.put(dir.getRootPath(), result.get... |
@Override
public void close() {
close(Duration.ofMillis(0));
} | @Test
public void shouldThrowOnFenceProducerIfProducerIsClosed() {
buildMockProducer(true);
producer.close();
assertThrows(IllegalStateException.class, producer::fenceProducer);
} |
public boolean addMetadataString(String rawMetadata) throws UnmarshallingException {
InputStream inputStream = new ByteArrayInputStream(rawMetadata.getBytes(UTF_8));
XMLObject metadata = super.unmarshallMetadata(inputStream);
if (!isValid(metadata)) {
return false;
}
... | @Test
public void resolveNonExistingIdTest() throws UnmarshallingException, ResolverException {
stringMetadataResolver.addMetadataString(metadata);
CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion("urn:nl-eid-gdi:1:0:entities:0000000999999999900"));
EntityDescriptor entityDescrip... |
public Version getCassandraVersion(String clusterId) {
CqlSession session = cqlSessionFactory.get(clusterId);
return getCassandraVersionWithSession(session);
} | @Test
void get_cassandra_version() {
// when
Version version = clusterVersionGetCommander.getCassandraVersion(CLUSTER_ID);
// then
assertThat(version).isNotNull();
assertThat(version).isGreaterThanOrEqualTo(Version.parse("1.0.0"));
} |
@Override
public V getNow(V valueIfAbsent) {
// if there is an explicit value set, we use that
if (result != null) {
return (V) result;
}
// if there already is a deserialized value set, use it.
if (deserializedValue != VOID) {
return (V) deserialized... | @Test
public void getNow_cachedValue() throws Exception {
invocationFuture.complete(response);
assertTrue(delegatingFuture.isDone());
String cachedValue = delegatingFuture.get();
assertEquals(DESERIALIZED_VALUE, cachedValue);
assertSame(cachedValue, delegatingFuture.getNow(D... |
@Override
public RuleDao loadByName(String name) throws NotFoundException {
final String id = titleToId.get(name);
if (id == null) {
throw new NotFoundException("No rule with name " + name);
}
return load(id);
} | @Test
public void loadByNameNotFound() {
assertThatThrownBy(() -> service.loadByName("Foobar"))
.isInstanceOf(NotFoundException.class)
.hasMessage("No rule with name Foobar");
} |
@Override
public MetricType getType() {
return MetricType.GAUGE_NUMBER;
} | @Test
public void set() {
NumberGauge gauge = new NumberGauge("bar");
assertThat(gauge.getValue()).isNull();
gauge.set(123l);
assertThat(gauge.getValue()).isEqualTo(123l);
assertThat(gauge.getType()).isEqualTo(MetricType.GAUGE_NUMBER);
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @Test
void testFunctionDependingOnInputFromInput() {
IdentityMapper<Boolean> function = new IdentityMapper<Boolean>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(function, BasicTypeInfo.BOOLEAN_TYPE_INFO);
assertThat(ti.isBasicType()).isTrue();
assertTh... |
KafkaBasedLog<String, byte[]> setupAndCreateKafkaBasedLog(String topic, final WorkerConfig config) {
String clusterId = config.kafkaClusterId();
Map<String, Object> originals = config.originals();
Map<String, Object> producerProps = new HashMap<>(baseProducerProps);
producerProps.put(Co... | @Test
public void testConsumerPropertiesNotInsertedByDefaultWithoutExactlyOnceSourceEnabled() {
props.put(EXACTLY_ONCE_SOURCE_SUPPORT_CONFIG, "preparing");
props.remove(ISOLATION_LEVEL_CONFIG);
createStore();
configStorage.setupAndCreateKafkaBasedLog(TOPIC, config);
verifyCo... |
@Override
public RouteContext route(final ShardingRule shardingRule) {
RouteContext result = new RouteContext();
for (String each : shardingRule.getDataSourceNames()) {
if (resourceMetaData.getAllInstanceDataSourceNames().contains(each)) {
result.getRouteUnits().add(new R... | @Test
void assertRoute() {
RouteContext routeContext = shardingInstanceBroadcastRoutingEngine.route(shardingRule);
assertThat(routeContext.getRouteUnits().size(), is(1));
assertThat(routeContext.getRouteUnits().iterator().next().getDataSourceMapper().getActualName(), is(DATASOURCE_NAME));
... |
@Override
public void onUnloaded() {
timer.cancel(GROUP_EXPIRATION_KEY);
coordinatorMetrics.deactivateMetricsShard(metricsShard);
groupMetadataManager.onUnloaded();
} | @Test
public void testOnUnloaded() {
GroupMetadataManager groupMetadataManager = mock(GroupMetadataManager.class);
OffsetMetadataManager offsetMetadataManager = mock(OffsetMetadataManager.class);
Time mockTime = new MockTime();
MockCoordinatorTimer<Void, CoordinatorRecord> timer = ne... |
@Override
public void cancel(ExecutionAttemptID executionAttemptId) {
final CompletableFuture<LogicalSlot> slotFuture =
this.requestedPhysicalSlots.getValueByKeyA(executionAttemptId);
if (slotFuture != null) {
slotFuture.cancel(false);
}
} | @Test
void testLogicalSlotCancellationCancelsPhysicalSlotRequest() throws Exception {
testLogicalSlotRequestCancellationOrRelease(
false,
true,
(context, slotFuture) -> {
assertThatThrownBy(
() -> {
... |
public static Build withPropertyValue(String propertyValue) {
return new Builder(propertyValue);
} | @Test
void it_should_return_client_type_when_property_value_exists() {
//GIVEN
String clientType = "https";
//WHEN
ElasticsearchClientType esClientType =
ElasticsearchClientTypeBuilder.withPropertyValue(clientType).build();
//THEN
assertEquals(HTTPS, esClientType);
} |
public double calcAzimuth(double lat1, double lon1, double lat2, double lon2) {
double orientation = Math.PI / 2 - calcOrientation(lat1, lon1, lat2, lon2);
if (orientation < 0)
orientation += 2 * Math.PI;
return Math.toDegrees(Helper.round4(orientation)) % 360;
} | @Test
public void testCalcAzimuth() {
assertEquals(45.0, AC.calcAzimuth(0, 0, 1, 1), 0.001);
assertEquals(90.0, AC.calcAzimuth(0, 0, 0, 1), 0.001);
assertEquals(180.0, AC.calcAzimuth(0, 0, -1, 0), 0.001);
assertEquals(270.0, AC.calcAzimuth(0, 0, 0, -1), 0.001);
assertEquals(0... |
public static Map<String, String> parseToMap(String attributesModification) {
if (Strings.isNullOrEmpty(attributesModification)) {
return new HashMap<>();
}
// format: +key1=value1,+key2=value2,-key3,+key4=value4
Map<String, String> attributes = new HashMap<>();
Stri... | @Test(expected = RuntimeException.class)
public void parseToMap_InvalidAddAttributeFormat_ThrowsRuntimeException() {
String attributesModification = "+key1=value1,key2=value2,-key3,+key4=value4";
AttributeParser.parseToMap(attributesModification);
} |
public static DateTime offsetMonth(Date date, int offset) {
return offset(date, DateField.MONTH, offset);
} | @Test
public void offsetMonthTest() {
final DateTime st = DateUtil.parseDate("2018-05-31");
final List<DateTime> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(DateUtil.offsetMonth(st, i));
}
assertEquals("2018-05-31 00:00:00", list.get(0).toString());
assertEquals("2018-06-30 00:00:00... |
public static Matcher<HttpRequest> pathStartsWith(String pathPrefix) {
if (pathPrefix == null) throw new NullPointerException("pathPrefix == null");
if (pathPrefix.isEmpty()) throw new NullPointerException("pathPrefix is empty");
return new PathStartsWith(pathPrefix);
} | @Test void pathStartsWith_matched_exact() {
when(httpRequest.path()).thenReturn("/foo");
assertThat(pathStartsWith("/foo").matches(httpRequest)).isTrue();
} |
@SuppressWarnings("unchecked")
@Override
public <T extends Statement> ConfiguredStatement<T> inject(
final ConfiguredStatement<T> statement
) {
if (!(statement.getStatement() instanceof CreateSource)
&& !(statement.getStatement() instanceof CreateAsSelect)) {
return statement;
}
t... | @Test
public void shouldThrowIfCtasKeyTableElementsNotCompatibleReorderedValue() {
// Given:
givenFormatsAndProps("kafka", "avro",
ImmutableMap.of("VALUE_SCHEMA_ID", new IntegerLiteral(42)));
givenDDLSchemaAndFormats(LOGICAL_SCHEMA_VALUE_REORDERED, "kafka", "avro",
SerdeFeature.UNWRAP_SING... |
@Override
public ResourceModel processSubResource(ResourceModel model, Configuration config) {
return model;
} | @Test
public void processSubResourceDoesNothing() throws Exception {
final Map<String, String> packagePrefixes = ImmutableMap.of(PACKAGE_NAME, "/test/prefix");
when(configuration.isCloud()).thenReturn(false);
final PrefixAddingModelProcessor modelProcessor = new PrefixAddingModelProcessor(pa... |
public void init(CustomModel customModel, EncodedValueLookup lookup, Map<String, JsonFeature> areas) {
this.lookup = lookup;
this.customModel = customModel;
} | @Test
public void testNegativeMax() {
CustomModel customModel = new CustomModel();
customModel.addToSpeed(If("true", LIMIT, VehicleSpeed.key("car")));
customModel.addToSpeed(If("road_class == PRIMARY", MULTIPLY, "0.5"));
customModel.addToSpeed(Else(MULTIPLY, "-0.5"));
Custom... |
@Nonnull
public static String classToPrimitive(@Nonnull String name) {
for (Type prim : PRIMITIVES) {
String className = prim.getClassName();
if (className.equals(name))
return prim.getInternalName();
}
throw new IllegalArgumentException("Descriptor was not a primitive class name!");
} | @Test
void testClassToPrimitive() {
assertEquals("V", Types.classToPrimitive("void"));
assertEquals("Z", Types.classToPrimitive("boolean"));
assertEquals("B", Types.classToPrimitive("byte"));
assertEquals("C", Types.classToPrimitive("char"));
assertEquals("S", Types.classToPrimitive("short"));
assertEquals... |
public synchronized KafkaMetric removeMetric(MetricName metricName) {
KafkaMetric metric = this.metrics.remove(metricName);
if (metric != null) {
for (MetricsReporter reporter : reporters) {
try {
reporter.metricRemoval(metric);
} catch (Ex... | @Test
public void testRemoveMetric() {
int size = metrics.metrics().size();
metrics.addMetric(metrics.metricName("test1", "grp1"), new WindowedCount());
metrics.addMetric(metrics.metricName("test2", "grp1"), new WindowedCount());
assertNotNull(metrics.removeMetric(metrics.metricName... |
public static ValidOffsetAndEpoch valid(OffsetAndEpoch offsetAndEpoch) {
return new ValidOffsetAndEpoch(Kind.VALID, offsetAndEpoch);
} | @Test
void valid() {
ValidOffsetAndEpoch validOffsetAndEpoch = ValidOffsetAndEpoch.valid(new OffsetAndEpoch(0, 0));
assertEquals(ValidOffsetAndEpoch.Kind.VALID, validOffsetAndEpoch.kind());
} |
public NotDocIdIterator(BlockDocIdIterator childDocIdIterator, int numDocs) {
_childDocIdIterator = childDocIdIterator;
_nextDocId = 0;
int currentDocIdFromChildIterator = childDocIdIterator.next();
_nextNonMatchingDocId = currentDocIdFromChildIterator == Constants.EOF ? numDocs : currentDocIdFromChild... | @Test
public void testNotDocIdIterator() {
// OR result: [0, 1, 2, 4, 5, 6, 8, 10, 13, 15, 16, 17, 18, 19, 20]
int[] docIds1 = new int[]{1, 4, 6, 10, 15, 17, 18, 20};
int[] docIds2 = new int[]{0, 1, 5, 8, 15, 18};
int[] docIds3 = new int[]{1, 2, 6, 13, 16, 19};
int[] docIds4 = new int[]{0, 1, 2, 3... |
public static Node createNodeAtPosition(Node containerNode, String nodeToCreateName, String nodeContent, Integer position) {
Node toReturn = containerNode.getOwnerDocument().createElement(nodeToCreateName);
if (nodeContent != null) {
toReturn.setTextContent(nodeContent);
}
if... | @Test
public void createNodeAtPosition() throws Exception {
String newNodeName = "NEW_NODE_NAME_0";
String newNodeValue = "NEW_NODE_VALUE_=";
Document document = DOMParserUtil.getDocument(XML);
Map<Node, List<Node>> testNodesMap = DOMParserUtil.getChildrenNodesMap(document, ... |
public KiePMMLPredicate getKiePMMLPredicate() {
return kiePMMLPredicate;
} | @Test
void getKiePMMLPredicate() {
assertThat(KIE_PMML_SEGMENT.getKiePMMLPredicate()).isEqualTo(KIE_PMML_PREDICATE);
} |
@SuppressWarnings({"SimplifyBooleanReturn"})
public static Map<String, ParamDefinition> cleanupParams(Map<String, ParamDefinition> params) {
if (params == null || params.isEmpty()) {
return params;
}
Map<String, ParamDefinition> mapped =
params.entrySet().stream()
.collect(
... | @Test
public void testCleanupAllPresentParams() throws JsonProcessingException {
for (ParamMode mode : ParamMode.values()) {
Map<String, ParamDefinition> allParams =
parseParamDefMap(
String.format(
"{'optional': {'type': 'STRING', 'mode': '%s', 'value': 'hello'}}",... |
static <T> T executeSupplier(Observation observation, Supplier<T> supplier) {
return decorateSupplier(observation, supplier).get();
} | @Test
public void shouldExecuteSupplier() throws Throwable {
given(helloWorldService.returnHelloWorld()).willReturn("Hello world")
.willThrow(new IllegalArgumentException("BAM!"));
try {
Observations.executeSupplier(observation, helloWorldService::returnHelloWorld);
... |
public boolean hasValue(String value) {
return props.containsValue(value);
} | @Test
public void testHasValue() {
Environment environment = Environment.empty();
assertEquals(Boolean.FALSE, environment.hasValue("hello"));
} |
public static String toString(InputStream input, String encoding) throws IOException {
return (null == encoding) ? toString(new InputStreamReader(input, Constants.ENCODE))
: toString(new InputStreamReader(input, encoding));
} | @Test
void testToStringV1() {
try {
InputStream input = IOUtils.toInputStream("test", StandardCharsets.UTF_8);
String actualValue = MD5Util.toString(input, "UTF-8");
assertEquals("test", actualValue);
} catch (IOException e) {
System.out.print... |
public static String buildWebApplicationRootUrl(NetworkService networkService) {
checkNotNull(networkService);
if (!isWebService(networkService)) {
return "http://"
+ NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint())
+ "/";
}
String rootUrl =
(i... | @Test
public void buildWebApplicationRootUrl_whenHttpsWithoutRoot_buildsExpectedUrl() {
assertThat(
NetworkServiceUtils.buildWebApplicationRootUrl(
NetworkService.newBuilder()
.setNetworkEndpoint(forIpAndPort("127.0.0.1", 8443))
.setServiceName("ssl/https")
... |
public RequestSender request(HttpMethod method) {
Objects.requireNonNull(method, "method");
HttpClientFinalizer dup = new HttpClientFinalizer(new HttpClientConfig(configuration()));
dup.configuration().method = method;
return dup;
} | @Test
void testIssue694() {
disposableServer =
createServer()
.handle((req, res) -> {
req.receive()
.subscribe();
return Mono.empty();
})
.bindNow();
HttpClient client = createHttpClientForContextWithPort();
... |
@Deprecated
@Override
public Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device) {
return fromScanData(scanData, rssi, device, System.currentTimeMillis(), new AltBeacon());
} | @Test
public void testParseWrongFormatReturnsNothing() {
BeaconManager.setDebug(true);
org.robolectric.shadows.ShadowLog.stream = System.err;
LogManager.d("XXX", "testParseWrongFormatReturnsNothing start");
byte[] bytes = hexStringToByteArray("02011a1aff1801ffff2f234454cf6d4a0fadf2f4... |
public static void setZone(Map<String, String> meta) {
final String originZone = meta.get(SpringRegistryConstants.LOAD_BALANCER_ZONE_META_KEY);
if (originZone != null) {
LoggerFactory.getLogger().info(String.format(Locale.ENGLISH, "Registry instance with zone [%s]",
origi... | @Test
public void testSetZone() {
try (MockedStatic<PluginConfigManager> pluginConfigManagerMockedStatic = Mockito.mockStatic(PluginConfigManager.class)) {
final HashMap<String, String> meta = new HashMap<>(
Collections.singletonMap(SpringRegistryConstants.LOAD_BALANCER_ZONE_... |
public static String getBucketName(AlluxioURI uri) {
return uri.getAuthority().toString();
} | @Test
public void getBucketName() throws Exception {
assertEquals("s3-bucket-name",
UnderFileSystemUtils.getBucketName(new AlluxioURI("s3://s3-bucket-name/")));
assertEquals("s3a_bucket_name",
UnderFileSystemUtils.getBucketName(new AlluxioURI("s3a://s3a_bucket_name/")));
assertEquals("a.b.... |
@Override
public Object adapt(final HttpAction action, final WebContext context) {
if (action != null) {
var code = action.getCode();
val response = ((JEEContext) context).getNativeResponse();
if (code < 400) {
response.setStatus(code);
} else... | @Test
public void testActionWithContent() {
JEEHttpActionAdapter.INSTANCE.adapt(new OkAction(TestsConstants.VALUE), context);
verify(response).setStatus(200);
verify(writer).write(TestsConstants.VALUE);
} |
public EndpointGroupingRule4Openapi read() {
EndpointGroupingRule4Openapi endpointGroupingRule = new EndpointGroupingRule4Openapi();
serviceOpenapiDefMap.forEach((serviceName, openapiDefs) -> {
openapiDefs.forEach(openapiData -> {
LinkedHashMap<String, LinkedHashMap<String, L... | @Test
public void testReadingRule() throws IOException {
EndpointGroupingRuleReader4Openapi reader = new EndpointGroupingRuleReader4Openapi("openapi-definitions");
EndpointGroupingRule4Openapi rule = reader.read();
EndpointNameGrouping nameGrouping = new EndpointNameGrouping();
name... |
@GetMapping("/plugin/selector/findList")
public Mono<String> findListSelector(@RequestParam("pluginName") final String pluginName,
@RequestParam(value = "id", required = false) final String id) {
List<SelectorData> selectorDataList = BaseDataCache.getInstance().obtai... | @Test
public void testFindListSelector() throws Exception {
final String selectorPluginName = "testFindListSelector";
final String testFindListSelectorId = "testFindListSelectorId";
final SelectorData selectorData = new SelectorData();
selectorData.setPluginName(selectorPluginName);
... |
public HostProvisioner getProvisioner() { return provisioner; } | @Test
void testProvisionerIsSet() {
DeployState.Builder builder = new DeployState.Builder();
HostProvisioner provisioner = new InMemoryProvisioner(true, false, "foo.yahoo.com");
builder.modelHostProvisioner(provisioner);
DeployState state = builder.build();
assertEquals(provi... |
public int getBatchSizeInt( VariableSpace vars ) {
return Const.toInt( vars.environmentSubstitute( this.batchSize ), DEFAULT_BATCH_SIZE );
} | @Test
public void testGetBatchSizeInt() {
ElasticSearchBulkMeta esbm = new ElasticSearchBulkMeta();
int batchSize = esbm.getBatchSizeInt( new VariableSpaceImpl() );
assertEquals( batchSize, ElasticSearchBulkMeta.DEFAULT_BATCH_SIZE );
} |
@NonNull
@Override
public HealthResponse healthResponse(final Map<String, Collection<String>> queryParams) {
final String type = queryParams.getOrDefault(CHECK_TYPE_QUERY_PARAM, Collections.emptyList())
.stream()
.findFirst()
.orElse(null);
final Collection<H... | @Test
void shouldThrowExceptionWhenJsonProcessorExceptionOccurs() throws IOException {
// given
final ObjectMapper mapperMock = mock(ObjectMapper.class);
this.jsonHealthResponseProvider = new JsonHealthResponseProvider(healthStatusChecker,
healthStateAggregator, mapperMock);
... |
public boolean isValid(String value) {
if (value == null) {
return false;
}
URI uri; // ensure value is a valid URI
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return false;
}
// OK, perfom additional validatio... | @Test
public void testValidator339IDN() {
UrlValidator urlValidator = new UrlValidator();
assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without
assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with
assertFalse(urlValidat... |
public static Configuration configurePythonDependencies(ReadableConfig config) {
final PythonDependencyManager pythonDependencyManager = new PythonDependencyManager(config);
final Configuration pythonDependencyConfig = new Configuration();
pythonDependencyManager.applyToConfiguration(pythonDepen... | @Test
void testPythonFiles() {
Configuration config = new Configuration();
config.set(
PythonOptions.PYTHON_FILES,
"hdfs:///tmp_dir/test_file1.py,tmp_dir/test_file2.py,tmp_dir/test_dir,hdfs:///tmp_dir/test_file1.py");
Configuration actual = configurePythonDepe... |
public FEELFnResult<Boolean> invoke(@ParameterName( "list" ) List list) {
if ( list == null ) {
return FEELFnResult.ofError(new InvalidParametersEvent(Severity.ERROR, "list", "cannot be null"));
}
boolean result = true;
boolean containsNull = false;
// Spec. definitio... | @Test
void invokeListParamReturnTrue() {
FunctionTestUtil.assertResult(allFunction.invoke(Arrays.asList(Boolean.TRUE, Boolean.TRUE)), true);
} |
public static String entityUuidOf(String id) {
if (id.startsWith(ID_PREFIX)) {
return id.substring(ID_PREFIX.length());
}
return id;
} | @Test
public void projectUuidOf_returns_substring_if_starts_with_id_prefix() {
assertThat(AuthorizationDoc.entityUuidOf("auth_")).isEmpty();
String id = randomAlphabetic(1 + new Random().nextInt(10));
assertThat(AuthorizationDoc.entityUuidOf("auth_" + id)).isEqualTo(id);
} |
@Override
public Map<ConfigDefinitionKey, ConfigDefinition> getConfigDefinitions() {
return Collections.unmodifiableMap(configDefinitions);
} | @Test
public void testThatRepoIsCorrectlyInitialized() throws IOException {
File topDir = folder.newFolder();
File defDir = new File(topDir, "classes");
defDir.mkdir();
addFile(defDir, new ConfigDefinitionKey("foo", "foons"), "namespace=foons\nval int\n");
addFile(defDir, new... |
@Override
public int getBitsetSize() {
return this.bitset.length;
} | @Test
public void testConstructor() {
BloomFilter bloomFilter1 = new BlockSplitBloomFilter(0);
assertEquals(bloomFilter1.getBitsetSize(), BlockSplitBloomFilter.LOWER_BOUND_BYTES);
BloomFilter bloomFilter3 = new BlockSplitBloomFilter(1000);
assertEquals(bloomFilter3.getBitsetSize(), 1024);
} |
@Override
public Optional<Entity> exportEntity(EntityDescriptor entityDescriptor, EntityDescriptorIds entityDescriptorIds) {
final ModelId modelId = entityDescriptor.id();
try {
final GrokPattern grokPattern = grokPatternService.load(modelId.id());
return Optional.of(exportNa... | @Test
public void exportEntity() throws ValidationException {
grokPatternService.save(GrokPattern.create("Test1", "[a-z]+"));
grokPatternService.save(GrokPattern.create("Test2", "[a-z]+"));
final EntityDescriptor descriptor = EntityDescriptor.create("1", ModelTypes.GROK_PATTERN_V1);
... |
@Override
public String toString() {
return "QGChangeEvent{" +
"project=" + toString(project) +
", branch=" + toString(branch) +
", analysis=" + toString(analysis) +
", projectConfiguration=" + projectConfiguration +
", previousStatus=" + previousStatus +
", qualityGateSupplier... | @Test
public void overrides_toString() {
QGChangeEvent underTest = new QGChangeEvent(project, branch, analysis, configuration, previousStatus, supplier);
assertThat(underTest)
.hasToString("QGChangeEvent{project=bar:foo, branch=BRANCH:bar:doh:zop, analysis=pto:8999999765" +
", projectConfigurat... |
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "checkstyle:methodlength"})
void planMigrations(int partitionId, PartitionReplica[] oldReplicas, PartitionReplica[] newReplicas,
MigrationDecisionCallback callback) {
assert oldReplicas.length == newReplicas.leng... | @Test
public void test_MOVE_toNull() throws UnknownHostException {
final PartitionReplica[] oldReplicas = {
new PartitionReplica(new Address("localhost", 5701), uuids[0]),
new PartitionReplica(new Address("localhost", 5702), uuids[1]),
new PartitionReplica(new... |
@Override
public CommitWorkStream commitWorkStream() {
return windmillStreamFactory.createCommitWorkStream(
dispatcherClient.getWindmillServiceStub(), throttleTimers.commitWorkThrottleTimer());
} | @Test
public void testStreamingCommit() throws Exception {
ConcurrentHashMap<Long, WorkItemCommitRequest> commitRequests = new ConcurrentHashMap<>();
serviceRegistry.addService(
new CloudWindmillServiceV1Alpha1ImplBase() {
@Override
public StreamObserver<StreamingCommitWorkRequest>... |
@Override
public List<String> splitAndEvaluate() {
return Strings.isNullOrEmpty(inlineExpression) ? Collections.emptyList() : flatten(evaluate(GroovyUtils.split(handlePlaceHolder(inlineExpression))));
} | @Test
void assertEvaluateForNull() {
List<String> expected = TypedSPILoader.getService(InlineExpressionParser.class, "GROOVY", PropertiesBuilder.build(
new PropertiesBuilder.Property(InlineExpressionParser.INLINE_EXPRESSION_KEY, "t_order_${null}"))).splitAndEvaluate();
assertThat(exp... |
@Override
public void loadGlue(Glue glue, List<URI> gluePaths) {
gluePaths.stream()
.filter(gluePath -> CLASSPATH_SCHEME.equals(gluePath.getScheme()))
.map(ClasspathSupport::packageName)
.map(classFinder::scanForClassesInPackage)
.flatMap(Colle... | @Test
void finds_injector_source_impls_by_classpath_url() {
GuiceBackend backend = new GuiceBackend(factory, classLoader);
backend.loadGlue(glue, singletonList(URI.create("classpath:io/cucumber/guice/integration")));
verify(factory).addClass(YourInjectorSource.class);
} |
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY);
} | @Test
public void testProvideGap() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
co... |
public void addLastHandler(AbstractChainHandler handler) {
if (tail == null) {
tail = handler;
setNext(handler);
return;
}
tail.setNext(handler);
tail = handler;
} | @Test
public void testChain() {
final HandlerChain handlerChain = new HandlerChain();
final BulkheadRequestHandler bulkheadRequestHandler = Mockito.spy(BulkheadRequestHandler.class);
final CircuitBreakerRequestHandler circuitBreakerClientReqHandler =
Mockito.spy(CircuitBreake... |
public static Deserializer<NeighborAdvertisement> deserializer() {
return (data, offset, length) -> {
checkInput(data, offset, length, HEADER_LENGTH);
NeighborAdvertisement neighborAdvertisement = new NeighborAdvertisement();
ByteBuffer bb = ByteBuffer.wrap(data, offset, le... | @Test
public void testDeserializeBadInput() throws Exception {
PacketTestUtils.testDeserializeBadInput(NeighborAdvertisement.deserializer());
} |
@Override
public void loginFailure(HttpRequest request, AuthenticationException e) {
checkRequest(request);
requireNonNull(e, "AuthenticationException can't be null");
if (!LOGGER.isDebugEnabled()) {
return;
}
Source source = e.getSource();
LOGGER.debug("login failure [cause|{}][method|{... | @Test
public void login_failure_prevents_log_flooding_on_login_starting_from_128_chars() {
AuthenticationException exception = newBuilder()
.setSource(Source.realm(Method.BASIC, "some provider name"))
.setMessage("pop")
.setLogin(LOGIN_129_CHARS)
.build();
underTest.loginFailure(mockRe... |
public Optional<String> getDatabaseName() {
Preconditions.checkState(databaseNames.size() <= 1, "Can not support multiple different database.");
return databaseNames.isEmpty() ? Optional.empty() : Optional.of(databaseNames.iterator().next());
} | @Test
void assertGetSchemaNameWithDifferentSchemaAndSameTable() {
SimpleTableSegment tableSegment1 = createTableSegment("table_1", "tbl_1");
tableSegment1.setOwner(new OwnerSegment(0, 0, new IdentifierValue("sharding_db_1")));
SimpleTableSegment tableSegment2 = createTableSegment("table_1", ... |
@Override
public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {
requireNonNull(executor);
requireNonNull(command);
requireNonNull(unit);
if (scheduledExecutorService.isShutdown()) {
return DisabledFuture.INSTANCE;
}
return scheduledExecutorService.s... | @Test
public void scheduledExecutorService_schedule() {
ScheduledExecutorService scheduledExecutor = Mockito.mock();
var task = ArgumentCaptor.forClass(Runnable.class);
Executor executor = Mockito.mock();
Runnable command = () -> {};
var scheduler = Scheduler.forScheduledExecutorService(scheduled... |
@Override
public String getName() {
return "Dart Package Analyzer";
} | @Test
public void testDartPubspecYamlAnalyzerAddressbook() throws AnalysisException {
final Engine engine = new Engine(getSettings());
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"dart.addressbook/pubspec.yaml"));
dartAnalyzer.analyze(result, eng... |
@Override
public List<SnowflakeIdentifier> listIcebergTables(SnowflakeIdentifier scope) {
StringBuilder baseQuery = new StringBuilder("SHOW ICEBERG TABLES");
String[] queryParams = null;
switch (scope.type()) {
case ROOT:
// account-level listing
baseQuery.append(" IN ACCOUNT");
... | @SuppressWarnings("unchecked")
@Test
public void testListIcebergTablesSQLExceptionAtSchemaLevel()
throws SQLException, InterruptedException {
for (Integer errorCode : SCHEMA_NOT_FOUND_ERROR_CODES) {
Exception injectedException =
new SQLException(
String.format("SQL exception ... |
public static boolean canManage(EfestoInput toEvaluate, EfestoRuntimeContext context) {
return getGeneratedExecutableResource(toEvaluate.getModelLocalUriId(), context.getGeneratedResourcesMap()).isPresent();
} | @Test
void canManage() {
ModelLocalUriId modelLocalUriId = new ModelLocalUriId(LocalUri.parse("/drl/" + basePath));
EfestoRuntimeContext context = EfestoRuntimeContextUtils.buildWithParentClassLoader(Thread.currentThread().getContextClassLoader());
BaseEfestoInput darInputDrlMap = new Efesto... |
public int compare(Session session, PlanCostEstimate left, PlanCostEstimate right)
{
requireNonNull(session, "session is null");
requireNonNull(left, "left is null");
requireNonNull(right, "right is null");
checkArgument(!left.hasUnknownComponents() && !right.hasUnknownComponents(), ... | @Test
public void testUnknownCost()
{
CostComparator costComparator = new CostComparator(1.0, 1.0, 1.0);
Session session = testSessionBuilder().build();
assertThrows(IllegalArgumentException.class, () -> costComparator.compare(session, PlanCostEstimate.zero(), PlanCostEstimate.unknown())... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.