focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public static SimpleTransform add(double operand) {
return new SimpleTransform(Operation.add,operand);
} | @Test
public void testAdd() {
TransformationMap t = new TransformationMap(Collections.singletonList(SimpleTransform.add(5)),new HashMap<>());
testSimple(t,(double a) -> a + 5);
} |
@Override
public void onEvent(ReplicaMigrationEvent event) {
switch (event.getPartitionId()) {
case MIGRATION_STARTED_PARTITION_ID:
migrationListener.migrationStarted(event.getMigrationState());
break;
case MIGRATION_FINISHED_PARTITION_ID:
... | @Test
public void test_migrationProcessStarted() {
MigrationState migrationSchedule = new MigrationStateImpl();
ReplicaMigrationEvent event = new ReplicaMigrationEventImpl(migrationSchedule, MIGRATION_STARTED_PARTITION_ID, 0, null, null, true, 0L);
adapter.onEvent(event);
verify(lis... |
public static void bind(ServerSocket socket, InetSocketAddress address,
int backlog) throws IOException {
bind(socket, address, backlog, null, null);
} | @Test
public void testBindError() throws Exception {
Configuration conf = new Configuration();
ServerSocket socket = new ServerSocket();
InetSocketAddress address = new InetSocketAddress("0.0.0.0",0);
socket.bind(address);
try {
int min = socket.getLocalPort();
conf.set("TestRange", mi... |
public List<HDPath> ancestors() {
return ancestors(false);
} | @Test
public void testAncestors() {
HDPath path = HDPath.parsePath("m/0H/1H/0H/1/0");
List<HDPath> ancestors = path.ancestors();
assertEquals(4, ancestors.size());
assertEquals(HDPath.parsePath("m/0H"), ancestors.get(0));
assertEquals(HDPath.parsePath("m/0H/1H"... |
public boolean filterMatchesEntry(String filter, FeedEntry entry) throws FeedEntryFilterException {
if (StringUtils.isBlank(filter)) {
return true;
}
Script script;
try {
script = ENGINE.createScript(filter);
} catch (JexlException e) {
throw new FeedEntryFilterException("Exception while parsing exp... | @Test
void dotClassIsDisabled() throws FeedEntryFilterException {
Assertions.assertTrue(service.filterMatchesEntry("null eq ''.class", entry));
} |
@Override
public List<Decorator> findForStream(String streamId) {
return toInterfaceList(coll.find(DBQuery.is(DecoratorImpl.FIELD_STREAM, Optional.of(streamId))).toArray());
} | @Test
@MongoDBFixtures("DecoratorServiceImplTest.json")
public void findForStreamReturnsDecoratorsForStream() {
assertThat(decoratorService.findForStream("000000000000000000000001"))
.hasSize(2)
.extracting(Decorator::id)
.containsExactly("588bcafebabedead... |
@Override
public void readData(ObjectDataInput in) throws IOException {
throw new UnsupportedOperationException();
} | @Test(expected = UnsupportedOperationException.class)
public void testReadData() throws Exception {
dataEvent.readData(null);
} |
public static BeamSqlEnvBuilder builder(TableProvider tableProvider) {
return new BeamSqlEnvBuilder(tableProvider);
} | @Test
public void testCreateExternalTableInNestedTableProvider() throws Exception {
TestTableProvider root = new TestTableProvider();
TestTableProvider nested = new TestTableProvider();
TestTableProvider anotherOne = new TestTableProvider();
BeamSqlEnv env =
BeamSqlEnv.builder(root)
... |
protected Dependency getMainGemspecDependency(Dependency dependency1, Dependency dependency2) {
if (dependency1 != null && dependency2 != null
&& Ecosystem.RUBY.equals(dependency1.getEcosystem())
&& Ecosystem.RUBY.equals(dependency2.getEcosystem())
&& isSameRubyGe... | @Test
public void testGetMainGemspecDependency() {
Dependency dependency1 = null;
Dependency dependency2 = null;
DependencyMergingAnalyzer instance = new DependencyMergingAnalyzer();
Dependency expResult = null;
Dependency result = instance.getMainGemspecDependency(dependency... |
@GetMapping("/list")
@Secured(action = ActionTypes.READ, signType = SignType.CONFIG)
public Result<Page<ConfigHistoryInfo>> listConfigHistory(@RequestParam("dataId") String dataId,
@RequestParam("group") String group,
@RequestParam(value = "namespaceId", required = false, defaultValue = ... | @Test
void testListConfigHistoryWhenNameSpaceIsPublic() throws Exception {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setDataId(TEST_DATA_ID);
configHistoryInfo.setGroup(TEST_GROUP);
configHistoryInfo.setContent(TEST_CONTENT);
co... |
@Override
public ExportResult<MediaContainerResource> export(UUID jobId, AD authData,
Optional<ExportInformation> exportInfo) throws Exception {
ExportResult<PhotosContainerResource> per = exportPhotos(jobId, authData, exportInfo);
if (per.getThrowable().isPresent()) {
return new ExportResult<>(pe... | @Test
public void shouldHandleErrorInVideos() throws Exception {
Exception throwable = new Exception();
mediaExporter =
new MediaExporterDecorator<>(photosExporter, (id, ad, ei) -> new ExportResult<>(throwable));
MediaContainerResource mcr = new MediaContainerResource(albums, photos, videos);
... |
public void isNotEqualTo(@Nullable Object unexpected) {
standardIsNotEqualTo(unexpected);
} | @SuppressWarnings("TruthSelfEquals")
@Test
public void isNotEqualToSameInstanceBadEqualsImplementation() {
Object o = new ThrowsOnEquals();
expectFailure.whenTesting().that(o).isNotEqualTo(o);
} |
public List<PlatformSpec> getPlatforms() {
return platforms;
} | @Test
public void testBaseImageSpec_nullCollections() throws JsonProcessingException {
String data = "image: gcr.io/example/jib\n";
BaseImageSpec baseImageSpec = mapper.readValue(data, BaseImageSpec.class);
Assert.assertEquals(ImmutableList.of(), baseImageSpec.getPlatforms());
} |
@Override
public CompletableFuture<SendPushNotificationResult> sendNotification(final PushNotification notification) {
final String topic = switch (notification.tokenType()) {
case APN -> bundleId;
case APN_VOIP -> bundleId + ".voip";
default -> throw new IllegalArgumentException("Unsupported to... | @Test
void testGenericFailure() {
PushNotificationResponse<SimpleApnsPushNotification> response = mock(PushNotificationResponse.class);
when(response.isAccepted()).thenReturn(false);
when(response.getRejectionReason()).thenReturn(Optional.of("BadTopic"));
when(apnsClient.sendNotification(any(SimpleAp... |
public boolean initWithCommittedOffsetsIfNeeded(Timer timer) {
final Set<TopicPartition> initializingPartitions = subscriptions.initializingPartitions();
final Map<TopicPartition, OffsetAndMetadata> offsets = fetchCommittedOffsets(initializingPartitions, timer);
// "offsets" will be null if the... | @Test
public void testNoCoordinatorDiscoveryIfPositionsKnown() {
assertTrue(coordinator.coordinatorUnknown());
subscriptions.assignFromUser(singleton(t1p));
subscriptions.seek(t1p, 500L);
coordinator.initWithCommittedOffsetsIfNeeded(time.timer(Long.MAX_VALUE));
assertEquals... |
List<DataflowPackage> stageClasspathElements(
Collection<StagedFile> classpathElements, String stagingPath, CreateOptions createOptions) {
return stageClasspathElements(classpathElements, stagingPath, DEFAULT_SLEEPER, createOptions);
} | @Test
public void testPackageUploadIsNotSkippedWhenSizesAreDifferent() throws Exception {
Pipe pipe = Pipe.open();
File tmpDirectory = tmpFolder.newFolder("folder");
tmpFolder.newFolder("folder", "empty_directory");
tmpFolder.newFolder("folder", "directory");
makeFileWithContents("folder/file.txt"... |
public static List<Type> decode(String rawInput, List<TypeReference<Type>> outputParameters) {
return decoder.decodeFunctionResult(rawInput, outputParameters);
} | @Test
@SuppressWarnings("unchecked")
public void testDecodeDynamicStructDynamicArray2() {
String rawInput =
"0x0000000000000000000000000000000000000000000000000000000000000020"
+ "0000000000000000000000000000000000000000000000000000000000000003"
... |
public static String toLowerCase(@Nullable String value) {
if (value == null) {
throw new IllegalArgumentException("String value cannot be null");
}
return value.toLowerCase(Locale.ENGLISH);
} | @Test
public void testToLowerCase() {
//noinspection DataFlowIssue
assertThatThrownBy(() -> toLowerCase(null)).isInstanceOf(IllegalArgumentException.class);
assertThat(toLowerCase("")).isEqualTo("");
assertThat(toLowerCase(" ")).isEqualTo(" ");
assertThat(toLowerCase("Hello")... |
public Set<? extends AuthenticationRequest> getRequest(final Host bookmark, final LoginCallback prompt)
throws LoginCanceledException {
final StringBuilder url = new StringBuilder();
url.append(bookmark.getProtocol().getScheme().toString()).append("://");
url.append(bookmark.getHostn... | @Test
public void testGetDefault2() throws Exception {
final SwiftAuthenticationService s = new SwiftAuthenticationService();
final SwiftProtocol protocol = new SwiftProtocol() {
@Override
public String getContext() {
return "/v2.0/tokens";
}
... |
@DataPermission(enable = false) // 忽略数据权限,避免因为过滤,导致找不到候选人
public Set<Long> calculateUsers(DelegateExecution execution) {
Integer strategy = BpmnModelUtils.parseCandidateStrategy(execution.getCurrentFlowElement());
String param = BpmnModelUtils.parseCandidateParam(execution.getCurrentFlowElement());
... | @Test
public void testCalculateUsers() {
// 准备参数
String param = "1,2";
DelegateExecution execution = mock(DelegateExecution.class);
// mock 方法(DelegateExecution)
UserTask userTask = mock(UserTask.class);
when(execution.getCurrentFlowElement()).thenReturn(userTask);
... |
@Override
public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) throws
RemotingCommandException {
final RemotingCommand response = RemotingCommand.createResponseCommand(null);
final EndTransactionRequestHeader requestHeader =
(EndTransactionReq... | @Test
public void testProcessRequest() throws RemotingCommandException {
when(transactionMsgService.commitMessage(any(EndTransactionRequestHeader.class))).thenReturn(createResponse(ResponseCode.SUCCESS));
when(messageStore.putMessage(any(MessageExtBrokerInner.class)))
.thenReturn(new... |
@Override
@MethodNotAvailable
public CompletionStage<Boolean> deleteAsync(K key) {
throw new MethodNotAvailableException();
} | @Test(expected = MethodNotAvailableException.class)
public void testDeleteAsync() {
adapter.deleteAsync(23);
} |
@Override
public SelType call(String methodName, SelType[] args) {
if (args.length == 1) {
if ("dateIntToTs".equals(methodName)) {
return dateIntToTs(args[0]);
} else if ("tsToDateInt".equals(methodName)) {
return tsToDateInt(args[0]);
}
} else if (args.length == 2) {
i... | @Test(expected = ClassCastException.class)
public void testCallIncrementDateIntInvalid() {
SelUtilFunc.INSTANCE.call(
"incrementDateInt", new SelType[] {SelString.of("20190101"), SelString.of("5")});
} |
@Asn1Property(tagNo = 0x30, converter = DigestsConverter.class)
public Map<Integer, byte[]> getDigests() {
return digests;
} | @Test
public void readDl1Cms() throws Exception {
final LdsSecurityObject ldsSecurityObject = mapper.read(
readFromCms("dl1"), LdsSecurityObject.class);
assertEquals(ImmutableSet.of(1, 5, 6, 11, 12, 13), ldsSecurityObject.getDigests().keySet());
} |
@VisibleForTesting
void retryRebalanceTable(String tableNameWithType, Map<String, Map<String, String>> allJobMetadata)
throws Exception {
// Skip retry for the table if rebalance job is still running or has completed, in specific:
// 1) Skip retry if any rebalance job is actively running. Being actively... | @Test
public void testRetryRebalance()
throws Exception {
String tableName = "table01";
LeadControllerManager leadController = mock(LeadControllerManager.class);
ControllerMetrics metrics = mock(ControllerMetrics.class);
ExecutorService exec = MoreExecutors.newDirectExecutorService();
Contro... |
@Override
public int hashCode() {
return Objects.hash(path, json);
} | @Test
void testHashCode() {
ArchivedJson original = new ArchivedJson("path", "json");
ArchivedJson twin = new ArchivedJson("path", "json");
assertThat(original).isEqualTo(original);
assertThat(twin).isEqualTo(original);
assertThat(twin).hasSameHashCodeAs(original);
} |
@SafeVarargs
public static <T> Set<T> intersectionDistinct(Collection<T> coll1, Collection<T> coll2, Collection<T>... otherColls) {
final Set<T> result;
if (isEmpty(coll1) || isEmpty(coll2)) {
// 有一个空集合就直接返回空
return new LinkedHashSet<>();
} else {
result = new LinkedHashSet<>(coll1);
}
if (ArrayUti... | @Test
public void intersectionDistinctTest() {
final ArrayList<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final ArrayList<String> list3 = CollUtil.newArrayList();
final Collection<String> intersectio... |
Collection<OutputFile> compile() {
List<OutputFile> out = new ArrayList<>(queue.size() + 1);
for (Schema schema : queue) {
out.add(compile(schema));
}
if (protocol != null) {
out.add(compileInterface(protocol));
}
return out;
} | @Test
void logicalTypesWithMultipleFieldsDateTime() throws Exception {
Schema logicalTypesWithMultipleFields = new Schema.Parser()
.parse(new File("src/test/resources/logical_types_with_multiple_fields.avsc"));
assertCompilesWithJavaCompiler(new File(this.outputFile, "testLogicalTypesWithMultipleField... |
public Rule<ProjectNode> projectNodeRule()
{
return new PullUpExpressionInLambdaProjectNodeRule();
} | @Test
public void testIfExpressionOnValue()
{
tester().assertThat(new PullUpExpressionInLambdaRules(getFunctionManager()).projectNodeRule())
.setSystemProperty(PULL_EXPRESSION_FROM_LAMBDA_ENABLED, "true")
.on(p ->
{
p.variable("col1", n... |
@Override
public void write(T record) {
recordConsumer.startMessage();
try {
messageWriter.writeTopLevelMessage(record);
} catch (RuntimeException e) {
Message m = (record instanceof Message.Builder) ? ((Message.Builder) record).build() : (Message) record;
LOG.error("Cannot write message... | @Test
public void testProto3DateTimeMessageRoundTrip() throws Exception {
Timestamp timestamp = Timestamps.parse("2021-05-02T15:04:03.748Z");
LocalDate date = LocalDate.of(2021, 5, 2);
LocalTime time = LocalTime.of(15, 4, 3, 748_000_000);
com.google.type.Date protoDate = com.google.type.Date.newBuilde... |
@Override
public void updateInputPartitions(final Set<TopicPartition> topicPartitions, final Map<String, List<String>> allTopologyNodesToSourceTopics) {
super.updateInputPartitions(topicPartitions, allTopologyNodesToSourceTopics);
partitionGroup.updatePartitions(topicPartitions, recordQueueCreator::... | @Test
public void shouldUpdatePartitions() {
when(stateManager.taskId()).thenReturn(taskId);
when(stateManager.taskType()).thenReturn(TaskType.ACTIVE);
task = createStatelessTask(createConfig());
final Set<TopicPartition> newPartitions = new HashSet<>(task.inputPartitions());
... |
@PublicAPI(usage = ACCESS)
public URI asURI() {
return uri.toURI();
} | @Test
public void asUri() throws URISyntaxException {
URL url = getClass().getResource(".");
assertThat(Location.of(url).asURI()).isEqualTo(url.toURI());
} |
public static Object convert(final Object o) {
if (o == null) {
return RubyUtil.RUBY.getNil();
}
final Class<?> cls = o.getClass();
final Valuefier.Converter converter = CONVERTER_MAP.get(cls);
if (converter != null) {
return converter.convert(o);
... | @Test
public void testArrayJavaProxy() {
IRubyObject[] array = new IRubyObject[]{RubyString.newString(RubyUtil.RUBY, "foo")};
RubyClass proxyClass = (RubyClass) Java.getProxyClass(RubyUtil.RUBY, String[].class);
ArrayJavaProxy ajp = new ArrayJavaProxy(RubyUtil.RUBY, proxyClass, array);
... |
public QueuePath getParentObject() {
return hasParent() ? new QueuePath(parent) : null;
} | @Test
public void testGetParentObject() {
Assert.assertEquals(new QueuePath("root.level_1.level_2"),
TEST_QUEUE_PATH.getParentObject());
Assert.assertEquals(ROOT_PATH, new QueuePath("root.level_1").getParentObject());
Assert.assertNull(ROOT_PATH.getParentObject());
} |
public static String getScesimFileName(String fileFullPath) {
if (fileFullPath == null) {
return null;
}
int idx = fileFullPath.replace("\\", "/").lastIndexOf('/');
String fileName = idx >= 0 ? fileFullPath.substring(idx + 1) : fileFullPath;
return fileName.endsWith(C... | @Test
public void getScesimFileName() {
assertThat(AbstractScenarioRunner.getScesimFileName("src/test/Test.scesim")).isEqualTo("Test");
assertThat(AbstractScenarioRunner.getScesimFileName("Test.scesim")).isEqualTo("Test");
assertThat(AbstractScenarioRunner.getScesimFileName("Test")).isEqualT... |
@Override
public DbEntitiesCatalog get() {
final Stopwatch stopwatch = Stopwatch.createStarted();
final DbEntitiesCatalog catalog = scan(packagesToScan, packagesToExclude, chainingClassLoader);
stopwatch.stop();
LOG.info("{} entities have been scanned and added to DB Entity Catalog, ... | @Test
void testScansEntitiesWithCustomTitleFieldProperly() {
DbEntitiesScanner scanner = new DbEntitiesScanner(new String[]{"org.graylog2.users"}, new String[]{});
final DbEntitiesCatalog dbEntitiesCatalog = scanner.get();
final DbEntityCatalogEntry entryByCollectionName = dbEntitiesCatalog... |
@Override
public ProjectRepositories load(String projectKey, @Nullable String branchBase) {
GetRequest request = new GetRequest(getUrl(projectKey, branchBase));
try (WsResponse response = wsClient.call(request)) {
try (InputStream is = response.contentStream()) {
return processStream(is);
... | @Test
public void passAndEncodeProjectKeyParameter() {
loader.load(PROJECT_KEY, null);
WsTestUtil.verifyCall(wsClient, "/batch/project.protobuf?key=foo%3F");
} |
void handleLine(final String line) {
final String trimmedLine = Optional.ofNullable(line).orElse("").trim();
if (trimmedLine.isEmpty()) {
return;
}
handleStatements(trimmedLine);
} | @Test
public void shouldThrowWhenTryingToSetDeniedProperty() throws Exception {
// Given
final KsqlRestClient mockRestClient = givenMockRestClient();
when(mockRestClient.makeIsValidRequest("ksql.service.id"))
.thenReturn(RestResponse.erroneous(
NOT_ACCEPTABLE.code(),
new Ks... |
@Override
public String lbType() {
return "Random";
} | @Test
public void lbType() {
Assert.assertEquals(new RandomLoadbalancer().lbType(), "Random");
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为操作一个部门,涉及到多个缓存
public Long createDept(DeptSaveReqVO createReqVO) {
if (createReqVO.getParentId() == null) {
createReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
... | @Test
public void testCreateDept() {
// 准备参数
DeptSaveReqVO reqVO = randomPojo(DeptSaveReqVO.class, o -> {
o.setId(null); // 防止 id 被设置
o.setParentId(DeptDO.PARENT_ID_ROOT);
o.setStatus(randomCommonStatus());
});
// 调用
Long deptId = deptServ... |
@Override
public boolean put(K key, V value) {
return get(putAsync(key, value));
} | @Test
public void testPut() {
RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("{multi.map}.some.key");
map.put(new SimpleKey("0"), new SimpleValue("1"));
map.put(new SimpleKey("0"), new SimpleValue("2"));
map.put(new SimpleKey("0"), new SimpleValue("3"));
... |
public List<StorageLocation> check(
final Configuration conf,
final Collection<StorageLocation> dataDirs)
throws InterruptedException, IOException {
final HashMap<StorageLocation, Boolean> goodLocations =
new LinkedHashMap<>();
final Set<StorageLocation> failedLocations = new HashSet<... | @Test(timeout=30000)
public void testFailedLocationsBelowThreshold() throws Exception {
final List<StorageLocation> locations =
makeMockLocations(HEALTHY, HEALTHY, FAILED); // 2 healthy, 1 failed.
final Configuration conf = new HdfsConfiguration();
conf.setInt(DFS_DATANODE_FAILED_VOLUMES_TOLERATED... |
@Override
public MaterialPollResult responseMessageForLatestRevisionsSince(String responseBody) {
if (isEmpty(responseBody)) return new MaterialPollResult();
Map responseBodyMap = getResponseMap(responseBody);
return new MaterialPollResult(toMaterialDataMap(responseBodyMap), toSCMRevisions(r... | @Test
public void shouldBuildNullSCMRevisionFromLatestRevisionsSinceWhenEmptyResponse() throws Exception {
MaterialPollResult pollResult = messageHandler.responseMessageForLatestRevisionsSince("");
assertThat(pollResult.getRevisions(), nullValue());
assertThat(pollResult.getMaterialData(), n... |
@Deprecated
@Override
public ProducerBuilder<T> maxPendingMessagesAcrossPartitions(int maxPendingMessagesAcrossPartitions) {
conf.setMaxPendingMessagesAcrossPartitions(maxPendingMessagesAcrossPartitions);
return this;
} | @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "maxPendingMessagesAcrossPartitions needs to be >= maxPendingMessages")
public void testProducerBuilderImplWhenMaxPendingMessagesAcrossPartitionsPropertyIsInvalidErrorMessages() {
producerBuilderImpl.maxPendingMessa... |
@Override
@Nonnull
public <T> T invokeAny(@Nonnull Collection<? extends Callable<T>> tasks)
throws ExecutionException {
throwRejectedExecutionExceptionIfShutdown();
Exception exception = null;
for (Callable<T> task : tasks) {
try {
return task.ca... | @Test
void testInvokeAny() {
final CompletableFuture<Thread> future = new CompletableFuture<>();
testTaskSubmissionBeforeShutdown(
testInstance -> testInstance.invokeAny(callableCollectionFromFuture(future)));
assertThat(future).isCompletedWithValue(Thread.currentThread());
... |
public static void checkSchemaCompatible(
Schema tableSchema,
Schema writerSchema,
boolean shouldValidate,
boolean allowProjection,
Set<String> dropPartitionColNames) throws SchemaCompatibilityException {
if (!allowProjection) {
List<Schema.Field> missingFields = findMissingFiel... | @Test
public void testBrokenSchema() {
assertThrows(SchemaBackwardsCompatibilityException.class,
() -> AvroSchemaUtils.checkSchemaCompatible(FULL_SCHEMA, BROKEN_SCHEMA, true, false, Collections.emptySet()));
} |
public static void validateHostAndPort(final String type, final PluginConfiguration pluginConfig) {
validateHost(type, pluginConfig);
validatePort(type, pluginConfig);
} | @Test
void assertValidateHostAndPortSuccess() {
PluginConfigurationValidator.validateHostAndPort("foo_type", new PluginConfiguration("localhost", 8080, "pwd", null));
} |
public static ImmutableSet<HttpUrl> allSubPaths(String url) {
return allSubPaths(HttpUrl.parse(url));
} | @Test
public void allSubPaths_whenInvalidUrl_returnsEmptyList() {
assertThat(allSubPaths("invalid_url")).isEmpty();
} |
@VisibleForTesting
static Object scalarToProtoValue(FieldType beamFieldType, Object value) {
if (beamFieldType.getTypeName() == TypeName.LOGICAL_TYPE) {
@Nullable LogicalType<?, ?> logicalType = beamFieldType.getLogicalType();
if (logicalType == null) {
throw new RuntimeException("Unexpectedly... | @Test
public void testScalarToProtoValue() {
Map<FieldType, Iterable<Pair<Object, Object>>> testCases =
ImmutableMap.<FieldType, Iterable<Pair<Object, Object>>>builder()
.put(
FieldType.BYTES,
ImmutableList.of(
Pair.create(BYTES, ByteString.c... |
public static int indexOf(byte[] array, byte[] target) {
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
... | @Test
public void testIndexOf() {
byte[] array = new byte[] {(byte) 0x9b, 0, 0x18, 0x65, 0x2e, (byte) 0xf3};
assertEquals(0, IOUtils.indexOf(array, new byte[] {}));
assertEquals(0, IOUtils.indexOf(array, new byte[] {(byte) 0x9b, 0}));
assertEquals(2, IOUtils.indexOf(array, new byte[] {0x18, 0x65, 0x2e... |
@Deprecated
public static String updateSerializedOptions(
String serializedOptions, Map<String, String> runtimeValues) {
ObjectNode root, options;
try {
root = PipelineOptionsFactory.MAPPER.readValue(serializedOptions, ObjectNode.class);
options = (ObjectNode) root.get("options");
chec... | @Test
public void testUpdateSerializeExistingValue() throws Exception {
TestOptions submitOptions =
PipelineOptionsFactory.fromArgs("--string=baz", "--otherString=quux").as(TestOptions.class);
String serializedOptions = MAPPER.writeValueAsString(submitOptions);
String updatedOptions =
Valu... |
@SuppressWarnings("WeakerAccess")
public Map<String, Object> getMainConsumerConfigs(final String groupId, final String clientId, final int threadIdx) {
final Map<String, Object> consumerProps = getCommonConsumerConfigs();
// Get main consumer override configs
final Map<String, Object> mainC... | @SuppressWarnings("deprecation")
@Test
public void shouldNotSetInternalThrowOnFetchStableOffsetUnsupportedConfigToFalseInConsumerForEosBeta() {
props.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, EXACTLY_ONCE_BETA);
final StreamsConfig streamsConfig = new StreamsConfig(props);
final Map... |
public static Class<?> getLiteral(String className, String literal) {
LiteralAnalyzer analyzer = ANALYZERS.get( className );
Class result = null;
if ( analyzer != null ) {
analyzer.validate( literal );
result = analyzer.getLiteral();
}
return result;
} | @Test
public void testIntegerLiteralFromJLS() {
// largest positive int: dec / octal / int / binary
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( getLiteral( int.class.getCanonicalName(), "2147483647" ) ).isNotNull();
assertThat( get... |
@Override
public ExecutionResult execute(final TaskConfig config, final TaskExecutionContext taskExecutionContext) {
return pluginRequestHelper.submitRequest(pluginId, TaskExtension.EXECUTION_REQUEST, new DefaultPluginInteractionCallback<>() {
@Override
public String requestBody(Stri... | @Test
public void shouldConstructExecutionRequestWithRequiredDetails() {
String workingDir = "working-dir";
com.thoughtworks.go.plugin.api.task.Console console = mock(com.thoughtworks.go.plugin.api.task.Console.class);
when(context.workingDir()).thenReturn(workingDir);
EnvironmentVar... |
public Number evaluate(final List<KiePMMLDefineFunction> defineFunctions,
final List<KiePMMLDerivedField> derivedFields,
final List<KiePMMLOutputField> outputFields,
final Map<String, Object> inputData) {
final List<KiePMMLNameValu... | @Test
void evaluateFromConstant() {
// <ComplexPartialScore>
// <Constant>100.0</Constant>
// </ComplexPartialScore>
final KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant(PARAM_1, Collections.emptyList(), value1, null);
final KiePMMLComplexPartialScore complexParti... |
@Override
public GetClusterNodesResponse getClusterNodes(GetClusterNodesRequest request)
throws YarnException, IOException {
if (request == null) {
routerMetrics.incrClusterNodesFailedRetrieved();
String msg = "Missing getClusterNodes request.";
RouterAuditLogger.logFailure(user.getShortUs... | @Test
public void testGetClusterNodesRequest() throws Exception {
LOG.info("Test FederationClientInterceptor : Get Cluster Nodes request.");
// null request
LambdaTestUtils.intercept(YarnException.class, "Missing getClusterNodes request.",
() -> interceptor.getClusterNodes(null));
// normal re... |
@Override
public Appender<ILoggingEvent> build(LoggerContext context, String applicationName, LayoutFactory<ILoggingEvent> layoutFactory,
LevelFilterFactory<ILoggingEvent> levelFilterFactory, AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {
final SyslogApp... | @Test
void appenderContextIsSet() {
final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
final SyslogAppenderFactory appenderFactory = new SyslogAppenderFactory();
final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "tes... |
@Override
public String[] split(String text) {
for (Pattern regexp : CONTRACTIONS2)
text = regexp.matcher(text).replaceAll("$1 $2");
for (Pattern regexp : CONTRACTIONS3)
text = regexp.matcher(text).replaceAll("$1 $2 $3");
text = DELIMITERS[0].matcher(text).replaceAl... | @Test
public void testTokenizeDiacritizedWords() {
System.out.println("tokenize words with diacritized chars (both composite and combining)");
String text = "The naïve résumé of Raúl Ibáñez; re\u0301sume\u0301.";
String[] expResult = {"The", "naïve", "résumé", "of", "Raúl", "Ibáñez", ";", "r... |
public static List<String> detectClassPathResourcesToStage(
ClassLoader classLoader, PipelineOptions options) {
PipelineResourcesOptions artifactsRelatedOptions = options.as(PipelineResourcesOptions.class);
List<String> detectedResources =
artifactsRelatedOptions.getPipelineResourcesDetector().de... | @Test
public void testDetectedResourcesListDoNotContainNotStageableResources() throws IOException {
File unstageableResource = tmpFolder.newFolder(".gradle/wrapper/unstageableResource");
URLClassLoader classLoader =
new URLClassLoader(new URL[] {unstageableResource.toURI().toURL()});
PipelineResou... |
public boolean matches(String groupAccessCode) {
return code.equals(Encoder.encode(groupAccessCode));
} | @Test
void 코드_일치_여부를_판단한다() {
// given
String code = "hello";
GroupAccessCode groupAccessCode = new GroupAccessCode(code);
// when, then
assertThat(groupAccessCode.matches("hello")).isTrue();
} |
public static String[] splitByComma(String input, boolean allowEmpty) {
if (input == null) {
return null;
}
String[] splitWithEmptyValues = trim(input).split("\\s*,\\s*", -1);
return allowEmpty ? splitWithEmptyValues : subtraction(splitWithEmptyValues, new String[]{""});
... | @Test
void testSplitByComma() {
assertNull(StringUtil.splitByComma(null, true));
assertArrayEquals(arr(""), StringUtil.splitByComma("", true));
assertArrayEquals(arr(""), StringUtil.splitByComma(" ", true));
assertArrayEquals(arr(), StringUtil.splitByComma(" ", false));
asser... |
@Override
public Optional<AuthenticatedDevice> authenticate(BasicCredentials basicCredentials) {
boolean succeeded = false;
String failureReason = null;
try {
final UUID accountUuid;
final byte deviceId;
{
final Pair<String, Byte> identifierAndDeviceId = getIdentifierAndDeviceId... | @Test
void testAuthenticateNonDefaultDevice() {
final UUID uuid = UUID.randomUUID();
final byte deviceId = 2;
final String password = "12345";
final Account account = mock(Account.class);
final Device device = mock(Device.class);
final SaltedTokenHash credentials = mock(SaltedTokenHash.class)... |
@Deprecated
public static void validateEntityId(EntityId entityId, String errorMessage) {
if (entityId == null || entityId.getId() == null) {
throw new IncorrectParameterException(errorMessage);
}
} | @Test
void validateEntityIdTest() {
Validator.validateEntityId(TenantId.SYS_TENANT_ID, id -> "Incorrect entityId " + id);
Validator.validateEntityId(goodDeviceId, id -> "Incorrect entityId " + id);
assertThatThrownBy(() -> Validator.validateEntityId(null, id -> "Incorrect entityId " + id))
... |
public static String convertToHtml(String input) {
return new Markdown().convert(StringEscapeUtils.escapeHtml4(input));
} | @Test
public void shouldDecorateBlockquote() {
assertThat(Markdown.convertToHtml("> Yesterday <br/> it worked\n> Today it is not working\r\n> Software is like that\r"))
.isEqualTo("<blockquote>Yesterday <br/> it worked<br/>\nToday it is not working<br/>\r\nSoftware is like that<br/>\r</blockquote>")... |
public String getServiceUUID(Connection connection, String serviceEntityId, int consumingServiceIdx) {
if (connection == null || serviceEntityId == null)
return null;
EntityDescriptor serviceEntityDescriptor = resolveEntityDescriptorFromMetadata(connection, serviceEntityId);
if (se... | @Test
void getServiceUUID() throws InitializationException {
setupParserPool();
String result = metadataRetrieverServiceMock.getServiceUUID(newConnection(SAML_COMBICONNECT, true, true, true), newMetadataRequest().getServiceEntityId(), 0);
assertEquals("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"... |
public @Nullable String formatDiff(A actual, E expected) {
return null;
} | @Test
public void testFormattingDiffsUsing_formatDiff() {
assertThat(LENGTHS_WITH_DIFF.formatDiff("foo", 4)).isEqualTo("-1");
assertThat(LENGTHS_WITH_DIFF.formatDiff("foot", 3)).isEqualTo("1");
} |
public static Object withCompatibleSchema(final Schema schema, final Object object) {
if (object == null) {
return null;
}
switch (schema.type()) {
case ARRAY:
final List<Object> ksqlArray = new ArrayList<>(((List) object).size());
((List) object).forEach(
e -> ksqlAr... | @Test
public void shouldMakeStructSchemaCompatible() {
// Given:
final Schema oldSchema = new ConnectSchema(
Type.STRUCT, false, null, "oldSchema", 1, "");
final Struct struct = new Struct(oldSchema);
// When:
final Schema newSchema = new ConnectSchema(
Type.STRUCT, false, null, "n... |
public long remainingMs() {
timer.update();
return timer.remainingMs();
} | @Test
public void testRemainingMs() {
TimedRequestState state = new TimedRequestState(
new LogContext(),
this.getClass().getSimpleName(),
100,
1000,
time.timer(DEFAULT_TIMEOUT_MS)
);
assertEquals(DEFAULT_TIMEOUT_MS, state.remainingM... |
public void resolveDcMetadata(SamlRequest samlRequest) throws DienstencatalogusException {
final DcMetadataResponse metadataFromDc = dienstencatalogusClient.retrieveMetadataFromDc(samlRequest);
if (samlRequest instanceof AuthenticationRequest) {
dcMetadataResponseMapper.dcMetadataToAuthent... | @Test
public void resolveAuthenticationDcMetadataTest() throws DienstencatalogusException {
when(dienstencatalogusClientMock.retrieveMetadataFromDc(any(SamlRequest.class))).thenReturn(stubDcResponse());
SamlRequest request = new AuthenticationRequest();
request.setConnectionEntityId(CONNECTI... |
public List<ShardingCondition> createShardingConditions(final InsertStatementContext sqlStatementContext, final List<Object> params) {
List<ShardingCondition> result = null == sqlStatementContext.getInsertSelectContext()
? createShardingConditionsWithInsertValues(sqlStatementContext, params)
... | @Test
void assertCreateShardingConditionsWithCaseSensitiveField() {
when(shardingRule.findShardingColumn("foo_Col_3", "foo_table")).thenReturn(Optional.of("foo_Col_3"));
List<ShardingCondition> actual = shardingConditionEngine.createShardingConditions(insertStatementContext, Collections.emptyList())... |
public static String buildApiPath(String interfaceName, String version, String methodName) {
if (version == null || "".equals(version) || ABSENT_VERSION.equals(version)) {
return interfaceName + "." + methodName;
}
// io.sermant.dubbotest.service.CTest:version.methodName
ret... | @Test
public void testBuildPath() {
Assert.assertEquals(
ConvertUtils.buildApiPath("com.test.interface", "1.0.0", "methodName"),
"com.test.interface:1.0.0.methodName");
Assert.assertEquals(
ConvertUtils.buildApiPath("com.test.interface", "", "methodName"),
... |
@Override
public <T> TableConfig set(ConfigOption<T> option, T value) {
configuration.set(option, value);
return this;
} | @Test
void testGetInvalidLocalTimeZoneUTC() {
CONFIG_BY_CONFIGURATION.set("table.local-time-zone", "UTC+8");
assertThatThrownBy(CONFIG_BY_CONFIGURATION::getLocalTimeZone)
.isInstanceOf(ValidationException.class)
.hasMessageContaining("Invalid time zone.");
} |
public static boolean isCompressionCodecSupported(InputFormat inputFormat, Path path)
{
if (inputFormat instanceof TextInputFormat) {
return getCompressionCodec((TextInputFormat) inputFormat, path)
.map(codec -> (codec instanceof GzipCodec) || (codec instanceof BZip2Codec))
... | @Test
public void testIsCompressionCodecSupported()
{
assertTrue(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject.gz")));
assertTrue(S3SelectPushdown.isCompressionCodecSupported(inputFormat, new Path("s3://fakeBucket/fakeObject")));
assertFal... |
@VisibleForTesting
Integer convertSmsTemplateAuditStatus(int templateStatus) {
switch (templateStatus) {
case 1: return SmsTemplateAuditStatusEnum.CHECKING.getStatus();
case 0: return SmsTemplateAuditStatusEnum.SUCCESS.getStatus();
case -1: return SmsTemplateAuditStatusEn... | @Test
public void testConvertSmsTemplateAuditStatus() {
assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(),
smsClient.convertSmsTemplateAuditStatus(0));
assertEquals(SmsTemplateAuditStatusEnum.CHECKING.getStatus(),
smsClient.convertSmsTemplateAuditStatus(1));... |
public static int nextCapacity(int current) {
assert current > 0 && Long.bitCount(current) == 1 : "Capacity must be a power of two.";
if (current < MIN_CAPACITY / 2) {
current = MIN_CAPACITY / 2;
}
current <<= 1;
if (current < 0) {
throw new RuntimeExcep... | @Test
public void testNextCapacity_withInt() {
int capacity = 16;
int nextCapacity = nextCapacity(capacity);
assertEquals(32, nextCapacity);
} |
public SmbFile getFile() {
return file;
} | @Test
public void getFile() {
assertEquals(file, ss.getFile());
} |
@Override
public URL getResource(final String name) {
try {
final Enumeration<URL> resources = getResources(name);
if (resources.hasMoreElements()) {
return resources.nextElement();
}
} catch (IOException ignored) {
// mimics the behavi... | @Test
void testOwnerFirstResourceFoundIgnoresComponent() throws IOException {
String resourceToLoad =
TempDirUtils.newFile(tempFolder, "tmpfile" + UUID.randomUUID()).getName();
TestUrlClassLoader owner =
new TestUrlClassLoader(resourceToLoad, RESOURCE_RETURNED_BY_OWNE... |
@Override
public void executeWithLock(Runnable task, LockConfiguration lockConfig) {
try {
executeWithLock((Task) task::run, lockConfig);
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable throwable) {
// Should not happen
throw... | @Test
void lockShouldBeReentrantForMultipleDifferentLocks() {
mockLockFor(lockConfig);
mockLockFor(lockConfig2);
AtomicBoolean called = new AtomicBoolean(false);
executor.executeWithLock(
(Runnable) () -> executor.executeWithLock((Runnable) () -> called.set(true), l... |
@Override
public void putAll(Map<? extends CharSequence, ? extends V> otherMap) {
otherMap.forEach(this::put);
} | @Test
public void testPutAll() {
CharSequenceMap<String> map = CharSequenceMap.create();
map.putAll(ImmutableMap.of("key1", "value1", "key2", "value2"));
assertThat(map).containsEntry("key1", "value1");
assertThat(map).containsEntry("key2", "value2");
} |
public boolean couldHoldIgnoringSharedMemory(NormalizedResources other, double thisTotalMemoryMb, double otherTotalMemoryMb) {
if (this.cpu < other.getTotalCpu()) {
return false;
}
return couldHoldIgnoringSharedMemoryAndCpu(other, thisTotalMemoryMb, otherTotalMemoryMb);
} | @Test
public void testCouldHoldWithMissingResource() {
NormalizedResources resources = new NormalizedResources(normalize(Collections.emptyMap()));
NormalizedResources resourcesToCheck = new NormalizedResources(normalize(Collections.singletonMap(gpuResourceName, 1)));
boolean couldHo... |
public byte[] poll(long timeout, TimeUnit unit) throws Exception {
return internalPoll(timeout, unit);
} | @Test
public void testPollWithTimeout() throws Exception {
CuratorFramework clients[] = null;
try {
String dir = "/testOffer1";
final int num_clients = 1;
clients = new CuratorFramework[num_clients];
SimpleDistributedQueue queueHandles[] = new SimpleDi... |
public static void setDeepLinkCallback(SensorsDataDeepLinkCallback callback) {
mDeepLinkCallback = callback;
} | @Test
public void setDeepLinkCallback() {
DeepLinkManager.setDeepLinkCallback(null);
} |
public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
this.jsonPath = jsonPath;
this.resultMatcher = resultMatcher;
} | @Test
public void shouldMatchExistingCompiledJsonPath() {
assertThat(BOOKS_JSON, withJsonPath(compile("$.expensive")));
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.bicycle")));
assertThat(BOOKS_JSON, withJsonPath(compile("$.store.book[2].title")));
assertThat(BOOKS_JSON, wit... |
static void publishMessagesInBatch() throws Exception {
try (Connection connection = createConnection()) {
Channel ch = connection.createChannel();
String queue = UUID.randomUUID().toString();
ch.queueDeclare(queue, false, false, true, null);
ch.confirmSelect();... | @Test
@DisplayName("publish messages in batch")
void publishMessagesInBatch() throws Exception {
Channel ch = connection.createChannel();
ch.confirmSelect();
int batchSize = 100;
int outstandingMessageCount = 0;
for (int i = 0; i < messageCount; i++) {
String ... |
@Override
public MutableNetwork<Node, Edge> apply(MapTask mapTask) {
List<ParallelInstruction> parallelInstructions = Apiary.listOrEmpty(mapTask.getInstructions());
MutableNetwork<Node, Edge> network =
NetworkBuilder.directed()
.allowsSelfLoops(false)
.allowsParallelEdges(true)... | @Test
public void testParDo() {
InstructionOutput readOutput = createInstructionOutput("Read.out");
ParallelInstruction read = createParallelInstruction("Read", readOutput);
read.setRead(new ReadInstruction());
MultiOutputInfo parDoMultiOutput = createMultiOutputInfo("output");
ParDoInstruction p... |
@Override
public void preflight(final Path workdir, final String filename) throws BackgroundException {
if(workdir.isRoot() || new DeepboxPathContainerService(session).isDeepbox(workdir) || new DeepboxPathContainerService(session).isBox(workdir)) {
throw new AccessDeniedException(MessageFormat.f... | @Test
public void testAddChildrenInbox() throws Exception {
final DeepboxIdProvider nodeid = new DeepboxIdProvider(session);
final Path folder = new Path("/ORG 4 - DeepBox Desktop App/ORG3:Box1/Inbox/", EnumSet.of(Path.Type.directory, Path.Type.volume));
final PathAttributes attributes = new... |
public static List<PropertyDefinition> all() {
return asList(
PropertyDefinition.builder(PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY)
.defaultValue("24")
.name("Keep only one analysis a day after")
.description("After this number of hours, if there are several analyses... | @Test
public void shouldGetExtensions() {
assertThat(PurgeProperties.all()).hasSize(7);
} |
static <E extends Enum<E>> int untetheredSubscriptionStateChangeLength(final E from, final E to)
{
return stateTransitionStringLength(from, to) + SIZE_OF_LONG + 2 * SIZE_OF_INT;
} | @Test
void untetheredSubscriptionStateChangeLengthComputesLengthBasedOnProvidedState()
{
final ClusterTimeUnit from = ClusterTimeUnit.MILLIS;
final ClusterTimeUnit to = ClusterTimeUnit.NANOS;
assertEquals(stateTransitionStringLength(from, to) + SIZE_OF_LONG + 2 * SIZE_OF_INT,
... |
@Override
Class<?> getReturnType() {
throw new UnsupportedOperationException();
} | @Test
public void getReturnType() {
// GIVEN
ExtractorGetter getter = new ExtractorGetter(UNUSED, mock(ValueExtractor.class), "argument");
// WHEN
assertThrows(UnsupportedOperationException.class, getter::getReturnType);
} |
public final void isNotIn(Range<T> range) {
if (range.contains(checkNotNull(actual))) {
failWithActual("expected not to be in range", range);
}
} | @Test
public void isNotInRange() {
Range<Integer> oneToFive = Range.closed(1, 5);
assertThat(6).isNotIn(oneToFive);
expectFailureWhenTestingThat(4).isNotIn(oneToFive);
assertThat(expectFailure.getFailure())
.factValue("expected not to be in range")
.isEqualTo(oneToFive.toString());
... |
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
} | @Test
public void testIsNullOrEmpty() {
assertTrue(isNullOrEmpty(null));
assertTrue(isNullOrEmpty(""));
assertTrue(isNullOrEmpty(StringUtil.EMPTY_STRING));
assertFalse(isNullOrEmpty(" "));
assertFalse(isNullOrEmpty("\t"));
assertFalse(isNullOrEmpty("\n"));
ass... |
public static String hadoopFsFilename(String fname, Configuration conf, String user)
throws URISyntaxException, FileNotFoundException, IOException,
InterruptedException {
Path p = hadoopFsPath(fname, conf, user);
if (p == null)
return null;
else
return p.toString();
} | @Test
public void testHadoopFsFilename() {
try {
String tmpFileName1 = "/tmp/testHadoopFsListAsArray1";
String tmpFileName2 = "/tmp/testHadoopFsListAsArray2";
File tmpFile1 = new File(tmpFileName1);
File tmpFile2 = new File(tmpFileName2);
tmpFile1.createNewFile();
tmpFile2.crea... |
@Override
public void smoke() {
tobacco.smoke(this);
} | @Test
void testSmokeEveryThingThroughConstructor() {
List<Tobacco> tobaccos = List.of(
new OldTobyTobacco(),
new RivendellTobacco(),
new SecondBreakfastTobacco()
);
// Verify if the wizard is smoking the correct tobacco ...
tobaccos.forEach(tobacco -> {
final GuiceWizar... |
public static boolean isValidIp(String ip) {
return VALIDATOR.isValid(ip);
} | @Test
public void isValidIp() {
String ipv4 = "192.168.1.0";
String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String invalidIp = "192.168.1.256";
String ipv4Cidr = "192.168.1.0/24";
assert IPAddressUtils.isValidIp(ipv4);
assert IPAddressUtils.isValidIp(ipv6);... |
protected boolean checkFeExistByIpOrFqdn(String ipOrFqdn) throws UnknownHostException {
Pair<String, String> targetIpAndFqdn = NetUtils.getIpAndFqdnByHost(ipOrFqdn);
for (Frontend fe : frontends.values()) {
Pair<String, String> curIpAndFqdn;
try {
curIpAndFqdn = ... | @Test
public void testCheckFeExistByIpOrFqdn() throws UnknownHostException {
NodeMgr nodeMgr = new NodeMgr();
nodeMgr.replayAddFrontend(new Frontend(FrontendNodeType.FOLLOWER, "node1", "localhost", 9010));
Assert.assertTrue(nodeMgr.checkFeExistByIpOrFqdn("localhost"));
Assert.assertT... |
@Override
public boolean unregister(final Application application) {
if(!ServiceManagementFunctions.library.SMLoginItemSetEnabled(application.getIdentifier(), false)) {
log.warn(String.format("Failed to remove %s as login item", application));
return false;
}
return t... | @Test
public void testUnregister() {
assertFalse(new ServiceManagementApplicationLoginRegistry().unregister(
new Application("bundle.helper")));
} |
@PostMapping
@Secured(resource = AuthConstants.CONSOLE_RESOURCE_NAME_PREFIX + "namespaces", action = ActionTypes.WRITE)
public Boolean createNamespace(@RequestParam("customNamespaceId") String namespaceId,
@RequestParam("namespaceName") String namespaceName,
@RequestParam(value = "namesp... | @Test
void testCreateNamespaceWithLongCustomId() throws Exception {
StringBuilder longId = new StringBuilder();
for (int i = 0; i < 129; i++) {
longId.append("a");
}
assertFalse(namespaceController.createNamespace(longId.toString(), "testName", "testDesc"));
verif... |
public boolean eval(StructLike data) {
return new EvalVisitor().eval(data);
} | @Test
public void testCaseInsensitiveNot() {
Evaluator evaluator = new Evaluator(STRUCT, not(equal("X", 7)), false);
assertThat(evaluator.eval(TestHelpers.Row.of(7))).as("not(7 == 7) => false").isFalse();
assertThat(evaluator.eval(TestHelpers.Row.of(8))).as("not(8 == 7) => false").isTrue();
Evaluator... |
@ConstantFunction(name = "bitor", argTypes = {INT, INT}, returnType = INT)
public static ConstantOperator bitorInt(ConstantOperator first, ConstantOperator second) {
return ConstantOperator.createInt(first.getInt() | second.getInt());
} | @Test
public void bitorInt() {
assertEquals(10, ScalarOperatorFunctions.bitorInt(O_INT_10, O_INT_10).getInt());
} |
RegistryEndpointProvider<URL> writer(URL location, Consumer<Long> writtenByteCountListener) {
return new Writer(location, writtenByteCountListener);
} | @Test
public void testWriter_handleResponse() throws IOException, RegistryException {
Mockito.when(mockResponse.getHeader("Location"))
.thenReturn(Collections.singletonList("https://somenewurl/location"));
GenericUrl requestUrl = new GenericUrl("https://someurl");
Mockito.when(mockResponse.getRequ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.