focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public AdAuthentication resolveAuthenticationResult(String httpSessionId) throws AdException {
AdSession session = getAdSession(httpSessionId);
AdAuthentication adAuthentication = new AdAuthentication();
adAuthentication.setLevel(session.getAuthenticationLevel());
adAuthentication.setSt... | @Test
public void resolveAuthenticationResultFailed() {
Exception result = assertThrows(AdException.class,
() -> adService.resolveAuthenticationResult("httpSessionId"));
assertEquals(result.getMessage(), "no adSession found");
} |
public static KTableHolder<GenericKey> build(
final KGroupedTableHolder groupedTable,
final TableAggregate aggregate,
final RuntimeBuildContext buildContext,
final MaterializedFactory materializedFactory) {
return build(
groupedTable,
aggregate,
buildContext,
... | @Test
public void shouldBuildMaterializationCorrectlyForAggregate() {
// When:
final KTableHolder<?> result = aggregate.build(planBuilder, planInfo);
// Then:
assertThat(result.getMaterializationBuilder().isPresent(), is(true));
final MaterializationInfo info = result.getMaterializationBuilder()... |
@Override
public OutputCommitter getOutputCommitter(TaskAttemptContext context) throws IOException {
return new CopyCommitter(getOutputPath(context), context);
} | @Test
public void testGetOutputCommitter() {
try {
TaskAttemptContext context = new TaskAttemptContextImpl(new Configuration(),
new TaskAttemptID("200707121733", 1, TaskType.MAP, 1, 1));
context.getConfiguration().set("mapred.output.dir", "/out");
Assert.assertTrue(new CopyOutputFormat()... |
@Override
public void login(final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
final Credentials credentials = authorizationService.validate();
try {
if(log.isInfoEnabled()) {
log.info(String.format("Attempt authentication with %s", cred... | @Test(expected = LoginCanceledException.class)
public void testConnectInvalidRefreshToken() throws Exception {
final ProtocolFactory factory = new ProtocolFactory(new HashSet<>(Collections.singleton(new HubicProtocol())));
final Profile profile = new ProfilePlistReader(factory).read(
... |
@SuppressWarnings("PMD.UndefineMagicConstantRule")
public static Member singleParse(String member) {
// Nacos default port is 8848
int defaultPort = EnvUtil.getProperty(SERVER_PORT_PROPERTY, Integer.class, DEFAULT_SERVER_PORT);
// Set the default Raft port information for securit
... | @Test
void testSingleParseWithoutPort() {
Member actual = MemberUtil.singleParse(IP);
assertEquals(IP, actual.getIp());
assertEquals(PORT, actual.getPort());
assertEquals(IP + ":" + PORT, actual.getAddress());
assertEquals(NodeState.UP, actual.getState());
assertTrue(... |
public static Config merge(Config config, Config fallback) {
var root1 = config.root();
var root2 = fallback.root();
var origin = new ContainerConfigOrigin(config.origin(), fallback.origin());
var path = ConfigValuePath.root();
var newRoot = mergeObjects(origin, path, root1, roo... | @Test
void testMergeRoots() {
var config1 = MapConfigFactory.fromMap(Map.of(
"field1", "value1"
));
var config2 = MapConfigFactory.fromMap(Map.of(
"field2", "value2"
));
var config = MergeConfigFactory.merge(config1, config2);
assertThat(conf... |
@Override
public MaterializedTable nonWindowed() {
return new KsqlMaterializedTable(inner.nonWindowed());
} | @SuppressWarnings("OptionalGetWithoutIsPresent")
@Test
public void shouldReturnSelectTransformedFromNonWindowed() {
// Given:
final MaterializedTable table = materialization.nonWindowed();
givenNoopFilter();
when(project.apply(any(), any(), any())).thenReturn(Optional.of(transformed));
// When:... |
public Map<COSObjectKey, COSBase> parseAllObjects() throws IOException
{
Map<COSObjectKey, COSBase> allObjects = new HashMap<>();
try
{
Map<Integer, Long> objectNumbers = privateReadObjectOffsets();
// count the number of object numbers eliminating double entries
... | @Test
void testParseAllObjectsIndexed() throws IOException
{
COSStream stream = new COSStream();
stream.setItem(COSName.N, COSInteger.THREE);
stream.setItem(COSName.FIRST, COSInteger.get(13));
OutputStream outputStream = stream.createOutputStream();
// use object number 4... |
public void execute(){
logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages);
long startTime = System.currentTimeMillis();
long executionTime = 0;
int i = 0;
int exceptionsSwallowedCount = 0;
int operationsCompleted =... | @Test(timeout = 1000L)
public void execute_negtime(){
Long timeMillis = -100L;
CountingPageOperation op = new CountingPageOperation(Integer.MAX_VALUE,timeMillis);
op.execute();
assertEquals(0L, op.getCounter());
} |
public static Schema getPinotSchemaFromJsonFile(File jsonFile,
@Nullable Map<String, FieldSpec.FieldType> fieldTypeMap, @Nullable TimeUnit timeUnit,
@Nullable List<String> fieldsToUnnest, String delimiter,
ComplexTypeConfig.CollectionNotUnnestedToJson collectionNotUnnestedToJson)
throws IOExcept... | @Test
public void testInferSchema()
throws Exception {
ClassLoader classLoader = JsonUtilsTest.class.getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource(JSON_FILE)).getFile());
Map<String, FieldSpec.FieldType> fieldSpecMap =
ImmutableMap.of("d1", FieldSpec.F... |
public SymmetricEncryptionConfig setPassword(String password) {
this.password = password;
return this;
} | @Test
public void testSetPassword() {
config.setPassword("myPassword");
assertEquals("myPassword", config.getPassword());
} |
@Override
public DeleteRecordsResult deleteRecords(final Map<TopicPartition, RecordsToDelete> recordsToDelete,
final DeleteRecordsOptions options) {
SimpleAdminApiFuture<TopicPartition, DeletedRecords> future = DeleteRecordsHandler.newFuture(recordsToDelete.keySe... | @Test
public void testDeleteRecords() throws Exception {
HashMap<Integer, Node> nodes = new HashMap<>();
nodes.put(0, new Node(0, "localhost", 8121));
List<PartitionInfo> partitionInfos = new ArrayList<>();
partitionInfos.add(new PartitionInfo("my_topic", 0, nodes.get(0), new Node[] ... |
public static void validateKerberosPrincipal(
KerberosPrincipal kerberosPrincipal) throws IOException {
if (!StringUtils.isEmpty(kerberosPrincipal.getPrincipalName())) {
if (!kerberosPrincipal.getPrincipalName().contains("/")) {
throw new IllegalArgumentException(String.format(
RestA... | @Test
public void testKerberosPrincipal() throws IOException {
SliderFileSystem sfs = ServiceTestUtils.initMockFs();
Service app = createValidApplication("comp-a");
KerberosPrincipal kp = new KerberosPrincipal();
kp.setKeytab("file:///tmp/a.keytab");
kp.setPrincipalName("user/_HOST@domain.com");
... |
@Override
public Set<Long> calculateUsers(DelegateExecution execution, String param) {
Set<Long> deptIds = StrUtils.splitToLongSet(param);
List<DeptRespDTO> depts = deptApi.getDeptList(deptIds).getCheckedData();
return convertSet(depts, DeptRespDTO::getLeaderUserId);
} | @Test
public void testCalculateUsers() {
// 准备参数
String param = "1,2";
// mock 方法
DeptRespDTO dept1 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(11L));
DeptRespDTO dept2 = randomPojo(DeptRespDTO.class, o -> o.setLeaderUserId(22L));
when(deptApi.getDeptList(e... |
public String getClassName() {
return classname;
} | @Test
public void testGetClassName() {
Permission permission = new Permission("classname", "name");
assertEquals("classname", permission.getClassName());
} |
static long sizeOf(Mutation m) {
if (m.getOperation() == Mutation.Op.DELETE) {
return sizeOf(m.getKeySet());
}
long result = 0;
for (Value v : m.getValues()) {
switch (v.getType().getCode()) {
case ARRAY:
result += estimateArrayValue(v);
break;
case STRUCT... | @Test
public void deleteKeyRanges() throws Exception {
Mutation range =
Mutation.delete("test", KeySet.range(KeyRange.openOpen(Key.of(1L), Key.of(4L))));
assertThat(MutationSizeEstimator.sizeOf(range), is(16L));
} |
public void parse(DataByteArrayInputStream input, int readSize) throws Exception {
if (currentParser == null) {
currentParser = initializeHeaderParser();
}
// Parser stack will run until current incoming data has all been consumed.
currentParser.parse(input, readSize);
} | @Test
public void testEmptyConnectBytes() throws Exception {
CONNECT connect = new CONNECT();
connect.cleanSession(true);
connect.clientId(new UTF8Buffer(""));
DataByteArrayOutputStream output = new DataByteArrayOutputStream();
wireFormat.marshal(connect.encode(), output);
... |
@Override
public HttpResponseOutputStream<Node> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
final CreateFileUploadResponse uploadResponse = upload.start(file, status);
final String uploadUrl = uploadResponse.getUploadUrl();
... | @Test
public void testReadWrite() throws Exception {
final SDSNodeIdProvider nodeid = new SDSNodeIdProvider(session);
final Path room = new SDSDirectoryFeature(session, nodeid).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory, Path.Type.v... |
public List<String> column(final int column) {
return new ColumnView(column);
} | @Test
void column_should_throw_for_negative_row_value() {
assertThrows(IndexOutOfBoundsException.class, () -> createSimpleTable().column(0).get(-1));
} |
@Override
public synchronized ManagerSpec getManagerSpec()
{
Set<Long> rootGroupIds = new HashSet<>();
Map<Long, ResourceGroupSpec> resourceGroupSpecMap = new HashMap<>();
Map<Long, ResourceGroupIdTemplate> resourceGroupIdTemplateMap = new HashMap<>();
Map<Long, ResourceGroupSpec... | @Test
public void testEnvironments()
{
H2DaoProvider daoProvider = setup("test_configuration");
H2ResourceGroupsDao dao = daoProvider.get();
dao.createResourceGroupsGlobalPropertiesTable();
dao.createResourceGroupsTable();
dao.createSelectorsTable();
String prodEn... |
public byte[] readEvent() throws IOException {
try {
if (!channel.isOpen() || !consumeToStartOfEvent()) {
return null;
}
RecordHeader header = RecordHeader.get(currentBlock);
streamPosition += RECORD_HEADER_SIZE;
int cumReadSize = 0;
... | @Test
public void testReadWhileWriteAcrossBoundary() throws Exception {
char[] tooBig = fillArray( BLOCK_SIZE/4);
StringElement input = new StringElement(new String(tooBig));
byte[] inputSerialized = input.serialize();
try(RecordIOWriter writer = new RecordIOWriter(file);
... |
public boolean deleteGroupCapacity(final String group) {
try {
GroupCapacityMapper groupCapacityMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant.GROUP_CAPACITY);
PreparedStatementCreator preparedStatementCreator = connection -> {
... | @Test
void testDeleteGroupCapacity() {
when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenReturn(1);
assertTrue(service.deleteGroupCapacity("test"));
//mock get connection fail
when(jdbcTemplate.update(any(PreparedStatementCreator.class))).thenThrow(... |
public Span nextSpan(TraceContextOrSamplingFlags extracted) {
if (extracted == null) throw new NullPointerException("extracted == null");
TraceContext context = extracted.context();
if (context != null) return newChild(context);
TraceIdContext traceIdContext = extracted.traceIdContext();
if (traceI... | @Test void localRootId_nextSpan_sampled() {
TraceContext context1 = TraceContext.newBuilder().traceId(1).spanId(2).sampled(true).build();
TraceContext context2 = TraceContext.newBuilder().traceId(1).spanId(3).sampled(true).build();
localRootId(context1, context2, ctx -> tracer.nextSpan(ctx));
} |
@Override
public Long sendSingleNotifyToMember(Long userId, String templateCode, Map<String, Object> templateParams) {
return sendSingleNotify(userId, UserTypeEnum.MEMBER.getValue(), templateCode, templateParams);
} | @Test
public void testSendSingleNotifyToMember() {
// 准备参数
Long userId = randomLongId();
String templateCode = randomString();
Map<String, Object> templateParams = MapUtil.<String, Object>builder().put("code", "1234")
.put("op", "login").build();
// mock Notif... |
public static ConnectToSqlTypeConverter connectToSqlConverter() {
return CONNECT_TO_SQL_CONVERTER;
} | @Test
public void shouldConvertNestedComplexToSql() {
assertThat(SchemaConverters.connectToSqlConverter().toSqlType(NESTED_LOGICAL_TYPE), is(NESTED_SQL_TYPE));
} |
public static <T> T newInstanceOrNull(Class<? extends T> clazz, Object... params) {
Constructor<T> constructor = selectMatchingConstructor(clazz, params);
if (constructor == null) {
return null;
}
try {
return constructor.newInstance(params);
} catch (Ill... | @Test
public void newInstanceOrNull_primitiveArgInConstructorPassingNull() {
ClassWithTwoConstructorsIncludingPrimitives instance = InstantiationUtils.newInstanceOrNull(
ClassWithTwoConstructorsIncludingPrimitives.class,
42, null);
assertNotNull(instance);
} |
public static boolean isFloatingNumber(String text) {
final int startPos = findStartPosition(text);
if (startPos < 0) {
return false;
}
boolean dots = false;
for (int i = startPos; i < text.length(); i++) {
char ch = text.charAt(i);
if (!Chara... | @Test
@DisplayName("Tests that isFloatingNumber returns true for floats")
void isFloatingNumberFloats() {
assertTrue(ObjectHelper.isFloatingNumber("12.34"));
assertTrue(ObjectHelper.isFloatingNumber("-12.34"));
assertTrue(ObjectHelper.isFloatingNumber("1.0"));
assertTrue(ObjectHe... |
@VisibleForTesting
int getSleepDuration() {
return sleepDuration;
} | @Test
public void testNoMetricUpdatesThenNoWaiting() {
AbfsClientThrottlingAnalyzer analyzer = new AbfsClientThrottlingAnalyzer(
"test", abfsConfiguration);
validate(0, analyzer.getSleepDuration());
sleep(ANALYSIS_PERIOD_PLUS_10_PERCENT);
validate(0, analyzer.getSleepDuration());
} |
public boolean allSearchFiltersVisible() {
return hiddenSearchFiltersIDs.isEmpty();
} | @Test
void testAllSearchFiltersVisibleReturnsTrueOnEmptyHiddenFilters() {
toTest = new SearchFilterVisibilityCheckStatus(Collections.emptyList());
assertTrue(toTest.allSearchFiltersVisible());
} |
public CeQueueDto setSubmitterUuid(@Nullable String s) {
checkArgument(s == null || s.length() <= 255, "Value of submitter uuid is too long: %s", s);
this.submitterUuid = s;
return this;
} | @Test
void setSubmitterLogin_throws_IAE_if_value_is_41_chars() {
String str_256_chars = STR_255_CHARS + "a";
assertThatThrownBy(() -> underTest.setSubmitterUuid(str_256_chars))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of submitter uuid is too long: " + str_256_chars);
} |
@Override
public ListPartitionReassignmentsResult listPartitionReassignments(Optional<Set<TopicPartition>> partitions,
ListPartitionReassignmentsOptions options) {
final KafkaFutureImpl<Map<TopicPartition, PartitionReassignment>> partiti... | @Test
public void testListPartitionReassignments() throws Exception {
try (AdminClientUnitTestEnv env = mockClientEnv()) {
env.kafkaClient().setNodeApiVersions(NodeApiVersions.create());
TopicPartition tp1 = new TopicPartition("A", 0);
OngoingPartitionReassignment tp1Par... |
static String isHostParam(final String given) {
final String hostUri = StringHelper.notEmpty(given, "host");
final Matcher matcher = HOST_PATTERN.matcher(given);
if (!matcher.matches()) {
throw new IllegalArgumentException(
"host must be an absolute URI (e.g. ht... | @Test
public void nullHostParamsAreNotAllowed() {
assertThrows(IllegalArgumentException.class,
() -> RestOpenApiHelper.isHostParam(null));
} |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST,
allEntries = true) // allEntries 清空所有缓存,因为操作一个部门,涉及到多个缓存
public void deleteDept(Long id) {
// 校验是否存在
validateDeptExists(id);
// 校验是否有子部门
if (deptMapper.selectCountByParentId(id) > 0) {
... | @Test
public void testDeleteDept_success() {
// mock 数据
DeptDO dbDeptDO = randomPojo(DeptDO.class);
deptMapper.insert(dbDeptDO);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbDeptDO.getId();
// 调用
deptService.deleteDept(id);
// 校验数据不存在了
assertNull(d... |
public void isAnyOf(
@Nullable Object first, @Nullable Object second, @Nullable Object @Nullable ... rest) {
isIn(accumulate(first, second, rest));
} | @Test
public void isAnyOfNullFailure() {
expectFailure.whenTesting().that((String) null).isAnyOf("a", "b", "c");
} |
public static boolean updateCache(Map<String, ?> cache, LoadbalancerRule rule) {
if (!(rule instanceof ChangedLoadbalancerRule)) {
return false;
}
ChangedLoadbalancerRule changedLoadbalancerRule = (ChangedLoadbalancerRule) rule;
final String oldServiceName = changedLoadbalanc... | @Test
public void testCache() {
// judgment type test
final LoadbalancerRule newRule = new LoadbalancerRule(NEW_SERVICE_NAME, RULE);
final Map<String, Object> cache = buildCache();
Assert.assertFalse(CacheUtils.updateCache(cache, newRule));
// test cleanup data
final ... |
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (!CollectionUtils.isEmpty(config.getAllowedOrigins()) || !CollectionUtils.isEmpty(config.getAllowedOriginPatterns... | @Test
void shouldCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.ge... |
public static void upgradeConfigurationAndVersion(RuleNode node, RuleNodeClassInfo nodeInfo) {
JsonNode oldConfiguration = node.getConfiguration();
int configurationVersion = node.getConfigurationVersion();
int currentVersion = nodeInfo.getCurrentVersion();
var configClass = nodeInfo.ge... | @Test
public void testUpgradeRuleNodeConfigurationWithInvalidConfigAndOldConfigVersion() throws Exception {
// GIVEN
var node = new RuleNode();
var nodeInfo = mock(RuleNodeClassInfo.class);
var nodeConfigClazz = TbGetEntityDataNodeConfiguration.class;
var annotation = mock(or... |
@Override
public PageResult<DiyTemplateDO> getDiyTemplatePage(DiyTemplatePageReqVO pageReqVO) {
return diyTemplateMapper.selectPage(pageReqVO);
} | @Test
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
public void testGetDiyTemplatePage() {
// mock 数据
DiyTemplateDO dbDiyTemplate = randomPojo(DiyTemplateDO.class, o -> { // 等会查询到
o.setName(null);
o.setUsed(null);
o.setUsedTime(null);
o.setRe... |
public static String commandTopic(final KsqlConfig ksqlConfig) {
return toKsqlInternalTopic(ksqlConfig, KSQL_COMMAND_TOPIC_SUFFIX);
} | @Test
public void shouldReturnCommandTopic() {
// Given/When
final String commandTopic = ReservedInternalTopics.commandTopic(ksqlConfig);
// Then
assertThat(commandTopic, is("_confluent-ksql-default__command_topic"));
} |
@Override
protected double maintain() {
if ( ! nodeRepository().nodes().isWorking()) return 0.0;
// Don't need to maintain spare capacity in dynamically provisioned zones; can provision more on demand.
if (nodeRepository().zone().cloud().dynamicProvisioning()) return 1.0;
NodeList ... | @Test
public void testEmpty() {
var tester = new SpareCapacityMaintainerTester();
tester.maintainer.maintain();
assertEquals(0, tester.deployer.activations);
assertEquals(0, tester.nodeRepository.nodes().list().retired().size());
} |
public static String[] splitOnSpace(String s)
{
return PATTERN_SPACE.split(s);
} | @Test
void testSplitOnSpace_onlySpaces()
{
String[] result = StringUtil.splitOnSpace(" ");
assertArrayEquals(new String[] {}, result);
} |
public int[] findMatchingLines(List<String> left, List<String> right) {
int[] index = new int[right.size()];
int dbLine = left.size();
int reportLine = right.size();
try {
PathNode node = new MyersDiff<String>().buildPath(left, right);
while (node.prev != null) {
PathNode prevNode ... | @Test
public void shouldIgnoreDeletedLinesAtEndOfFile() {
List<String> database = new ArrayList<>();
database.add("line - 0");
database.add("line - 1");
database.add("line - 2");
database.add("line - 3");
database.add("line - 4");
List<String> report = new ArrayList<>();
report.add("l... |
public EnumSet<E> get() {
return value;
} | @SuppressWarnings("unchecked")
@Test
public void testSerializeAndDeserializeNull() throws IOException {
boolean gotException = false;
try {
new EnumSetWritable<TestEnumSet>(null);
} catch (RuntimeException e) {
gotException = true;
}
assertTrue(
"Instantiation of empty Enum... |
public void update(ResourceDesc resourceDesc) throws DdlException {
Preconditions.checkState(name.equals(resourceDesc.getName()));
Map<String, String> properties = resourceDesc.getProperties();
if (properties == null) {
return;
}
// update spark configs
if (... | @Test
public void testUpdate(@Injectable BrokerMgr brokerMgr, @Mocked GlobalStateMgr globalStateMgr)
throws UserException {
new Expectations() {
{
globalStateMgr.getBrokerMgr();
result = brokerMgr;
brokerMgr.containsBroker(broker);
... |
static void register(String type, Class<?> clazz) {
if (Modifier.isAbstract(clazz.getModifiers())) {
return;
}
if (REGISTRY_REQUEST.containsKey(type)) {
throw new RuntimeException(String.format("Fail to register, type:%s ,clazz:%s ", type, clazz.getName()));
}
... | @Test
void testRegisterDuplicated() {
assertThrows(RuntimeException.class, () -> {
PayloadRegistry.register("ErrorResponse", ErrorResponse.class);
});
} |
public static void localRunnerNotification(JobConf conf, JobStatus status) {
JobEndStatusInfo notification = createNotification(conf, status);
if (notification != null) {
do {
try {
int code = httpNotification(notification.getUri(),
notification.getTimeout());
if ... | @Test
public void testLocalJobRunnerRetryCount() throws InterruptedException {
int retryAttempts = 3;
JobStatus jobStatus = createTestJobStatus(
"job_20130313155005308_0001", JobStatus.SUCCEEDED);
JobConf jobConf = createTestJobConf(
new Configuration(), retryAttempts, baseUrl + "fail");
... |
public static PodTemplateSpec createPodTemplateSpec(
String workloadName,
Labels labels,
PodTemplate template,
Map<String, String> defaultPodLabels,
Map<String, String> podAnnotations,
Affinity affinity,
List<Container> initContainers,
... | @Test
public void testCreatePodTemplateSpecWithTemplate() {
PodTemplateSpec pod = WorkloadUtils.createPodTemplateSpec(
NAME,
LABELS,
new PodTemplateBuilder()
.withNewMetadata()
.withLabels(Map.of("label-3", ... |
@Override
public void start() {
this.all = registry.meter(name(getName(), "all"));
this.trace = registry.meter(name(getName(), "trace"));
this.debug = registry.meter(name(getName(), "debug"));
this.info = registry.meter(name(getName(), "info"));
this.warn = registry.meter(nam... | @Test
public void usesSharedRegistries() {
String registryName = "registry";
SharedMetricRegistries.add(registryName, registry);
final InstrumentedAppender shared = new InstrumentedAppender(registryName);
shared.start();
when(event.getLevel()).thenReturn(Level.INFO);
... |
@Override
public Map<String, String> getAllVariables() {
return internalGetAllVariables(0, Collections.emptySet());
} | @Test
void testGetAllVariablesWithExclusions() {
MetricRegistry registry = NoOpMetricRegistry.INSTANCE;
AbstractMetricGroup<?> group = new ProcessMetricGroup(registry, "host");
assertThat(group.getAllVariables(-1, Collections.singleton(ScopeFormat.SCOPE_HOST)))
.isEmpty();
... |
@Override
public MetadataNode child(String name) {
if (name.equals("name")) {
return new MetadataLeafNode(image.name());
} else if (name.equals("id")) {
return new MetadataLeafNode(image.id().toString());
} else {
int partitionId;
try {
... | @Test
public void testNameChild() {
MetadataNode child = NODE.child("name");
assertNotNull(child);
assertEquals(MetadataLeafNode.class, child.getClass());
} |
public String getExpiration() {
return expiration;
} | @Test
void claims_dateParse_issueTime() {
try {
AwsProxyRequest req = new AwsProxyRequestBuilder().fromJsonString(USER_POOLS_REQUEST).build();
assertEquals(EXP_TIME, req.getRequestContext().getAuthorizer().getClaims().getExpiration());
assertNotNull(req.getRequestContext... |
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
} | @Test
public void leftShift() {
assertUnifiesAndInlines(
"4 << 17", UBinary.create(Kind.LEFT_SHIFT, ULiteral.intLit(4), ULiteral.intLit(17)));
} |
@Override
// Camel calls this method if the endpoint isSynchronous(), as the
// KafkaEndpoint creates a SynchronousDelegateProducer for it
public void process(Exchange exchange) throws Exception {
// is the message body a list or something that contains multiple values
Message message = exch... | @Test
public void processSendsMessageWithListOfExchangesWithOverrideTopicHeaderOnEveryExchange() throws Exception {
endpoint.getConfiguration().setTopic("someTopic");
Mockito.when(exchange.getIn()).thenReturn(in);
Mockito.when(exchange.getMessage()).thenReturn(in);
// we set the ini... |
public void resolveAssertionConsumerService(AuthenticationRequest authenticationRequest) throws SamlValidationException {
// set URL if set in authnRequest
final String authnAcsURL = authenticationRequest.getAuthnRequest().getAssertionConsumerServiceURL();
if (authnAcsURL != null) {
... | @Test
void resolveAcsUrlWithoutIndexInMultiAcsNoDefaultMetadata() {
AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
AuthenticationRequest authenticationRequest = new AuthenticationRequest();
authenticationRequest.setAuthnRequest(authnRequest);
authenti... |
@VisibleForTesting
public int getNodeToLabelsFailedRetrieved() {
return numGetNodeToLabelsFailedRetrieved.value();
} | @Test
public void testGetNodeToLabelsFailed() {
long totalBadBefore = metrics.getNodeToLabelsFailedRetrieved();
badSubCluster.getNodeToLabels();
Assert.assertEquals(totalBadBefore + 1, metrics.getNodeToLabelsFailedRetrieved());
} |
public static UUIDUtils getInstance() {
return ID_WORKER_UTILS;
} | @Test
public void testConstructor() throws Exception {
Class<?> uUIDUtilsClass = UUIDUtils.getInstance().getClass();
Class<?>[] p = {long.class, long.class, long.class};
Constructor<?> constructor = uUIDUtilsClass.getDeclaredConstructor(p);
constructor.setAccessible(true);
tr... |
public SqlType getExpressionSqlType(final Expression expression) {
return getExpressionSqlType(expression, Collections.emptyMap());
} | @Test
public void shouldEvaluateTypeForArrayReferenceInStruct() {
// Given:
final SqlStruct inner = SqlTypes
.struct()
.field("IN0", SqlTypes.array(SqlTypes.INTEGER))
.build();
final LogicalSchema schema = LogicalSchema.builder()
.keyColumn(SystemColumns.ROWKEY_NAME, SqlTy... |
@Override
public LocalId toLocalId() {
return this;
} | @Test
void toLocalId() {
LocalPredictionId localPredictionId = new LocalPredictionId(fileName, name);
LocalId retrieved = localPredictionId.toLocalId();
assertThat(retrieved).isEqualTo(localPredictionId);
} |
public static NGram[][] of(Collection<String[]> sentences, int maxNGramSize, int minFrequency) {
ArrayList<Set<NGram>> features = new ArrayList<>(maxNGramSize + 1);
Set<NGram> feature = new HashSet<>();
features.add(feature);
EnglishPunctuations punctuations = EnglishPunctuations.getIns... | @Test
public void testExtract() throws IOException {
System.out.println("n-gram extraction");
String text = new String(Files.readAllBytes(smile.util.Paths.getTestData("text/turing.txt")));
PorterStemmer stemmer = new PorterStemmer();
SimpleTokenizer tokenizer = new SimpleTokenizer()... |
public float[] colMeans() {
float[] x = colSums();
for (int j = 0; j < n; j++) {
x[j] /= m;
}
return x;
} | @Test
public void testColMeans() {
System.out.println("colMeans");
float[][] A = {
{ 0.7220180f, 0.07121225f, 0.6881997f},
{-0.2648886f, -0.89044952f, 0.3700456f},
{-0.6391588f, 0.44947578f, 0.6240573f}
};
float[] r = {-0.06067647f, -... |
private static boolean canSatisfyConstraints(ApplicationId appId,
PlacementConstraint constraint, SchedulerNode node,
AllocationTagsManager atm,
Optional<DiagnosticsCollector> dcOpt)
throws InvalidAllocationTagsQueryException {
if (constraint == null) {
LOG.debug("Constraint is found e... | @Test
public void testNodeAntiAffinityAssignment()
throws InvalidAllocationTagsQueryException {
PlacementConstraintManagerService pcm =
new MemoryPlacementConstraintManager();
AllocationTagsManager tm = new AllocationTagsManager(rmContext);
// Register App1 with anti-affinity constraint map
... |
@Override
public byte[] serialize(final String topic, final List<?> values) {
if (values == null) {
return null;
}
final T single = extractOnlyColumn(values, topic);
return inner.serialize(topic, single);
} | @Test
public void shouldThrowIfWrongType() {
// Then:
final Exception e = assertThrows(
SerializationException.class,
() -> serializer.serialize("t", ImmutableList.of(12))
);
// Then:
assertThat(e.getMessage(), is("value does not match expected type. "
+ "expected: String,... |
public SchemaObject findFunction(String functionName) {
return getDefaultSchema().findFunction(functionName);
} | @Test
public void testFindFunction() {
SchemaRepository repository = new SchemaRepository(JdbcConstants.MYSQL);
SQLCreateFunctionStatement stmt = new SQLCreateFunctionStatement();
String funcName = "Test";
stmt.setName(new SQLIdentifierExpr(funcName));
repository.acceptCreate... |
@Override
public void updateIndices(SegmentDirectory.Writer segmentWriter)
throws Exception {
Map<String, List<Operation>> columnOperationsMap = computeOperations(segmentWriter);
if (columnOperationsMap.isEmpty()) {
return;
}
for (Map.Entry<String, List<Operation>> entry : columnOperation... | @Test
public void testEnableDictionaryForSortedColumn()
throws Exception {
IndexLoadingConfig indexLoadingConfig = new IndexLoadingConfig(null, _tableConfig);
for (int i = 0; i < RAW_SORTED_INDEX_COLUMNS.size(); i++) {
SegmentMetadataImpl existingSegmentMetadata = new SegmentMetadataImpl(_segment... |
public void checkAgainstThreshold() throws ThresholdExceedException {
int recentEvents = getEventCountsRecentInterval();
if (recentEvents >= maxEventsPerInterval) {
throw new ThresholdExceedException(
String.format(
"%d events detected in the r... | @Test
void testCheckAgainstThreshold() {
final ThresholdMeter thresholdMeter = createSmallThresholdMeter();
// first THRESHOLD_SMALL - 1 events should not exceed threshold
for (int i = 0; i < THRESHOLD_SMALL - 1; ++i) {
thresholdMeter.markEvent();
clock.advanceTime(S... |
public static void evalPlaceholders(Map<String, Object> headersMap, String path, String consumerPath) {
evalPlaceholders(headersMap::put, path, consumerPath);
} | @Test
@DisplayName("Test that the placeholders can eval if the given path is greater than the consumer path")
void testEvalPlaceholdersOutOfBound2() {
Map<String, Object> headers = new HashMap<>();
assertDoesNotThrow(() -> HttpHelper.evalPlaceholders(headers, "/some/url/value", "/some/{key}"),
... |
@Override
public CompletableFuture<Void> quiesce() {
if (!quiesced) {
quiesced = true;
if (numRunningTimers.get() == 0) {
quiesceCompletedFuture.complete(null);
}
}
return quiesceCompletedFuture;
} | @Test
void testQuiesceWhenNoRunningTimers() {
ProcessingTimeServiceImpl processingTimeService =
new ProcessingTimeServiceImpl(timerService, v -> v);
assertThat(processingTimeService.quiesce()).isDone();
} |
public int readInt(InputStream in) throws IOException {
return ((byte) in.read() & 0xff) << 24
| ((byte) in.read() & 0xff) << 16
| ((byte) in.read() & 0xff) << 8
| (byte) in.read() & 0xff;
} | @Test
public void readInt() throws Exception {
} |
public static List<String> finalDestination(List<String> elements) {
if (isMagicPath(elements)) {
List<String> destDir = magicPathParents(elements);
List<String> children = magicPathChildren(elements);
checkArgument(!children.isEmpty(), "No path found under the prefix " +
MAGIC_PATH_PREF... | @Test
public void testFinalDestinationBaseDirectChild() {
finalDestination(l(MAGIC_PATH_PREFIX, BASE, "3.txt"));
} |
static S3ResourceId fromUri(String uri) {
Matcher m = S3_URI.matcher(uri);
checkArgument(m.matches(), "Invalid S3 URI: [%s]", uri);
String scheme = m.group("SCHEME");
String bucket = m.group("BUCKET");
String key = Strings.nullToEmpty(m.group("KEY"));
if (!key.startsWith("/")) {
key = "/" ... | @Test
public void testResourceIdTester() {
S3Options options = PipelineOptionsFactory.create().as(S3Options.class);
options.setAwsRegion(Region.US_WEST_1);
FileSystems.setDefaultPipelineOptions(options);
ResourceIdTester.runResourceIdBattery(S3ResourceId.fromUri("s3://bucket/foo/"));
} |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void stopMessageLiveLocation() {
BaseResponse response = bot.execute(new StopMessageLiveLocation(chatId, 10009));
if (!response.isOk()) {
assertEquals(400, response.errorCode());
assertEquals("Bad Request: message can't be edited", response.description());
... |
long timeToNextHeartbeat(long now) {
update(now);
return heartbeatTimer.remainingMs();
} | @Test
public void testTimeToNextHeartbeat() {
heartbeat.sentHeartbeat(time.milliseconds());
assertEquals(heartbeatIntervalMs, heartbeat.timeToNextHeartbeat(time.milliseconds()));
time.sleep(heartbeatIntervalMs);
assertEquals(0, heartbeat.timeToNextHeartbeat(time.milliseconds()));
... |
@Override
public boolean deletesAreDetected(final int type) {
return false;
} | @Test
void assertDeletesAreDetected() {
assertFalse(metaData.deletesAreDetected(0));
} |
protected void read(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
String l;
while((l = in.readLine()) != null) {
... | @Test(expected = AccessDeniedException.class)
public void testParseNotFound() throws Exception {
new FireFtpBookmarkCollection().read(new ProtocolFactory(Collections.emptySet()), new Local(System.getProperty("java.io.tmpdir"), "f"));
} |
public Option<Dataset<Row>> loadAsDataset(SparkSession spark, List<CloudObjectMetadata> cloudObjectMetadata,
String fileFormat, Option<SchemaProvider> schemaProviderOption, int numPartitions) {
if (LOG.isDebugEnabled()) {
LOG.debug("Extracted distinct files " + clou... | @Test
public void partitionValueAddedToRow() {
List<CloudObjectMetadata> input = Collections.singletonList(new CloudObjectMetadata("src/test/resources/data/partitioned/country=US/state=CA/data.json", 1));
TypedProperties properties = new TypedProperties();
properties.put("hoodie.streamer.source.cloud.dat... |
public static Map<String, ActiveRuleParamDto> groupByKey(Collection<ActiveRuleParamDto> params) {
Map<String, ActiveRuleParamDto> result = new HashMap<>();
for (ActiveRuleParamDto param : params) {
result.put(param.getKey(), param);
}
return result;
} | @Test
void groupByKey() {
assertThat(ActiveRuleParamDto.groupByKey(Collections.emptyList())).isEmpty();
Collection<ActiveRuleParamDto> dtos = Arrays.asList(
new ActiveRuleParamDto().setKey("foo"), new ActiveRuleParamDto().setKey("bar"));
Map<String, ActiveRuleParamDto> group = ActiveRuleParamDto.gr... |
public static JsonNode buildResponseJsonSchema(String schemaText, String query) throws IOException {
TypeDefinitionRegistry registry = new SchemaParser().parse(schemaText);
GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, RuntimeWiring.MOCKED_WIRING);
Document graphqlReques... | @Test
void testBuildResponseJsonSchema() {
String schemaText;
String queryText = "{\n" + " hero {\n" + " name\n" + " email\n" + " family\n" + " affiliate\n"
+ " movies {\n" + " title\n" + " }\n" + " }\n" + "}";
JsonNode responseSchema = null;
try {
... |
@SuppressWarnings({
"nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public static TableReference parseTableSpec(String tableSpec) {
Matcher match = BigQueryIO.TABLE_SPEC.matcher(tableSpec);
if (!match.matches()) {
throw new IllegalArgumentException(
String.format(
... | @Test
public void testTableParsing_noProjectId() {
TableReference ref = BigQueryHelpers.parseTableSpec("data_set.table_name");
assertEquals(null, ref.getProjectId());
assertEquals("data_set", ref.getDatasetId());
assertEquals("table_name", ref.getTableId());
} |
public static String getDateFormatByRegex( String regex ) {
return getDateFormatByRegex( regex, null );
} | @Test
public void testGetDateFormatByRegex() {
assertNull( DateDetector.getDateFormatByRegex( null ) );
assertEquals( SAMPLE_DATE_FORMAT, DateDetector.getDateFormatByRegex( SAMPLE_REGEXP ) );
} |
@Override
public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) {
StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[0];
StreamObserver<T> requestObserver = func.apply(responseObserver);
return CompletableFuture.completedFuture(requestObserver);
} | @Test
void invoke() throws ExecutionException, InterruptedException, TimeoutException {
StreamObserver<String> responseObserver = Mockito.mock(StreamObserver.class);
BiStreamMethodHandler<String, String> handler = new BiStreamMethodHandler<>(o -> responseObserver);
CompletableFuture<StreamOb... |
@Transactional
public AccessKey create(String appId, AccessKey entity) {
long count = accessKeyRepository.countByAppId(appId);
if (count >= ACCESSKEY_COUNT_LIMIT) {
throw new BadRequestException("AccessKeys count limit exceeded");
}
entity.setId(0L);
entity.setAppId(appId);
entity.setDa... | @Test
public void testCreate() {
String appId = "someAppId";
String secret = "someSecret";
AccessKey entity = assembleAccessKey(appId, secret);
AccessKey accessKey = accessKeyService.create(appId, entity);
assertNotNull(accessKey);
} |
@Operation(summary = "list", description = "List host-components")
@GetMapping("/hosts/{hostId}")
public ResponseEntity<List<HostComponentVO>> listByHost(@PathVariable Long clusterId, @PathVariable Long hostId) {
return ResponseEntity.success(hostComponentService.listByHost(clusterId, hostId));
} | @Test
void listByHostReturnsHostComponentsForHost() {
Long clusterId = 1L;
Long hostId = 1L;
List<HostComponentVO> hostComponents = Arrays.asList(new HostComponentVO(), new HostComponentVO());
when(hostComponentService.listByHost(clusterId, hostId)).thenReturn(hostComponents);
... |
@Override
public Object evaluate(EvaluationContext ctx) {
try {
ctx.enterFrame();
List<Object> toReturn = new ArrayList<>();
ctx.setValue("partial", toReturn);
populateToReturn(0, ctx, toReturn);
LOG.trace("returning {}", toReturn);
ret... | @Test
void evaluateSimpleArray() {
IterationContextNode x = getIterationContextNode("x", getListNode("[ 1, 2, 3, 4 ]", Arrays.asList("1", "2", "3", "4")), "x in [ 1, 2, 3, 4 ]");
IterationContextNode y = getIterationContextNode("y", getNameRefNode(BuiltInType.UNKNOWN, "x"), "y in x");
ForExp... |
@DELETE
@Path("{networkId}")
public Response removeVirtualNetwork(@PathParam("networkId") long networkId) {
NetworkId nid = NetworkId.networkId(networkId);
vnetAdminService.removeVirtualNetwork(nid);
return Response.noContent().build();
} | @Test
public void testDeleteVirtualNetwork() {
mockVnetAdminService.removeVirtualNetwork(anyObject());
expectLastCall();
replay(mockVnetAdminService);
WebTarget wt = target()
.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
Response resp... |
@Override
public String getSerializableForm(boolean includeConfidence) {
/*
* Note: Due to the sparse implementation of MultiLabel, all 'key=value' pairs will have value=true. That is,
* say 'all possible labels' for a dataset are {R1,R2} but this particular example has label set = {R1}. T... | @Test
public void getsCorrectSerializableForm() {
MultiLabel abc = new MultiLabel(mkLabelSet("a", "b", "c"));
assertEquals("a=true,b=true,c=true", abc.getSerializableForm(false));
assertEquals("a=true,b=true,c=true:NaN", abc.getSerializableForm(true));
MultiLabel scored = new MultiL... |
public static QueryOptimizer newOptimizer(HazelcastProperties properties) {
HazelcastProperty property = ClusterProperty.QUERY_OPTIMIZER_TYPE;
String string = properties.getString(property);
Type type;
try {
type = Type.valueOf(string);
} catch (IllegalArgumentExcepti... | @Test(expected = IllegalArgumentException.class)
public void newOptimizer_whenUnknownValue_thenThrowIllegalArgumentException() {
HazelcastProperties hazelcastProperties = createMockHazelcastProperties(QUERY_OPTIMIZER_TYPE, "foo");
QueryOptimizerFactory.newOptimizer(hazelcastProperties);
} |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testCustomArrayWithTypeVariable() {
RichMapFunction<CustomArrayObject2<Boolean>[], ?> function =
new IdentityMapper<CustomArrayObject2<Boolean>[]>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
... |
@Override
public List<Intent> compile(MultiPointToSinglePointIntent intent, List<Intent> installable) {
Map<DeviceId, Link> links = new HashMap<>();
ConnectPoint egressPoint = intent.egressPoint();
final boolean allowMissingPaths = intentAllowsPartialFailure(intent);
boolean hasPath... | @Test
public void testPartialFailureConstraintFailure() {
Set<FilteredConnectPoint> ingress = ImmutableSet.of(
new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)),
new FilteredConnectPoint(new ConnectPoint(DID_5, PORT_1)));
FilteredConnectPoint egress =
... |
@Override
public void apply(ProcessRoutersRequest request, PolarisRouterContext routerContext) {
//1. get feature env router label key
String envLabelKey = routerContext.getLabel(LABEL_KEY_FEATURE_ENV_ROUTER_KEY);
if (StringUtils.isBlank(envLabelKey)) {
envLabelKey = DEFAULT_FEATURE_ENV_ROUTER_LABEL;
}
/... | @Test
public void testNotExistedEnvLabel() {
Map<String, String> labels = new HashMap<>();
labels.put("system-feature-env-router-label", "specify-env");
PolarisRouterContext routerContext = new PolarisRouterContext();
routerContext.putLabels(RouterConstant.ROUTER_LABELS, labels);
ProcessRoutersRequest reque... |
public Map<String, String> pukRequestAllowed(PukRequest request) throws PukRequestException {
final PenRequestStatus result = repository.findFirstByBsnAndDocTypeAndSequenceNoOrderByRequestDatetimeDesc(request.getBsn(), request.getDocType(), request.getSequenceNo());
checkExpirationDatePen(result);
... | @Test
public void pukRequestAllowedOnlyPossibleAfterPenRequest() throws PukRequestException {
Mockito.when(mockRepository.findFirstByBsnAndDocTypeAndSequenceNoOrderByRequestDatetimeDesc(request.getBsn(), request.getDocType(), request.getSequenceNo())).thenReturn(null);
Exception exception = assertT... |
@Override
public Optional<ConfigTable> readConfig(Set<String> keys) {
removeUninterestedKeys(keys);
registerKeyListeners(keys);
final ConfigTable table = new ConfigTable();
configItemKeyedByName.forEach((key, value) -> {
if (value.isPresent()) {
table.a... | @Test
public void shouldUpdateCachesWhenNotified() {
cacheByKey = new ConcurrentHashMap<>();
configItemKeyedByName = new ConcurrentHashMap<>();
Whitebox.setInternalState(register, "cachesByKey", cacheByKey);
Whitebox.setInternalState(register, "configItemKeyedByName", configItemKeyed... |
public static String getUserId() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
return request.getHeader(CommonConstants.USER_ID_HEADER... | @Test
public void testGetUserIdFromHeaderWhenMissing() {
// Prepare the scenario where the header is missing
when(request.getHeader(CommonConstants.USER_ID_HEADER)).thenReturn(null);
// Call the method under test
String userId = HeaderUtil.getUserId();
// Assert that an emp... |
public static synchronized BigInteger getMaxTaskUsage(final Metrics metricRegistry) {
final Collection<KafkaMetric> taskMetrics = metricRegistry
.metrics()
.entrySet()
.stream()
.filter(e -> e.getKey().name().contains(TASK_STORAGE_USED_BYTES))
.collect(Collectors.toMap(Map.En... | @Test
public void shouldRecordMaxTaskUsageWithNoTasks() {
// Given:
when(metrics.metrics()).thenReturn(Collections.emptyMap());
// When:
// Then:
BigInteger maxVal = StorageUtilizationMetricsReporter.getMaxTaskUsage(metrics);
assertEquals(maxVal, BigInteger.valueOf(0));
} |
public static SchemaKStream<?> buildSource(
final PlanBuildContext buildContext,
final DataSource dataSource,
final QueryContext.Stacker contextStacker
) {
final boolean windowed = dataSource.getKsqlTopic().getKeyFormat().isWindowed();
switch (dataSource.getDataSourceType()) {
case KST... | @Test
public void shouldThrowOnV1TableSourceWithPseudoColumnVersionGreaterThanZero() {
// Given:
givenNonWindowedTable();
givenExistingQueryWithOldPseudoColumnVersion(tableSourceV1);
when(tableSourceV1.getPseudoColumnVersion()).thenReturn(CURRENT_PSEUDOCOLUMN_VERSION_NUMBER);
// When:
final E... |
public final ThreadProperties threadProperties() {
ThreadProperties threadProperties = this.threadProperties;
if (threadProperties == null) {
Thread thread = this.thread;
if (thread == null) {
assert !inEventLoop();
submit(NOOP_TASK).syncUninterrup... | @Test
public void testThreadProperties() {
final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
SingleThreadEventExecutor executor = new SingleThreadEventExecutor(
null, new DefaultThreadFactory("test"), false) {
@Override
protected void ru... |
@Override
public Closeable enter() {
// Only update status from tracked thread to avoid race condition and inconsistent state updates
if (executionContext.getExecutionStateTracker().getTrackedThread() != Thread.currentThread()) {
return () -> {};
}
updateCurrentStateIfOutdated();
return exec... | @Test
public void testEnterEntersStateIfCalledFromTrackedThread() {
DataflowExecutionContext mockedExecutionContext = mock(DataflowExecutionContext.class);
DataflowOperationContext mockedOperationContext = mock(DataflowOperationContext.class);
final int siIndexId = 3;
ExecutionStateTracker mockedExec... |
@Override
public String getCommandName() {
return COMMAND_NAME;
} | @Test
public void backupCmdExecuted()
throws IOException, AlluxioException, NoSuchFieldException, IllegalAccessException {
CollectEnvCommand cmd = new CollectEnvCommand(FileSystemContext.create());
// Write to temp dir
File targetDir = InfoCollectorTestUtils.createTemporaryDirectory();
Comm... |
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(expected = RuntimeException.class)
public void testNextCapacity_withLong_shouldThrowIfMaxCapacityReached() {
long capacity = Long.highestOneBit(Long.MAX_VALUE - 1);
nextCapacity(capacity);
} |
@Override
public void accept(T t) {
updateTimeHighWaterMark(t.time());
shortTermStorage.add(t);
drainDueToLatestInput(t); //standard drain policy
drainDueToTimeHighWaterMark(); //prevent blow-up when data goes backwards in time
sizeHighWaterMark = Math.max(sizeHighWaterMa... | @Test
public void testAllPointsWithinWindow() {
/*
* Confirm that no points are emitted when all the points occur within the time window
*/
Duration maxLag = Duration.ofMinutes(5);
ApproximateTimeSorter<TimePojo> sorter = new ApproximateTimeSorter<>(
maxLag,
... |
@VisibleForTesting
public static String expandEnvironment(String var,
Path containerLogDir) {
var = var.replace(ApplicationConstants.LOG_DIR_EXPANSION_VAR,
containerLogDir.toString());
var = var.replace(ApplicationConstants.CLASS_PATH_SEPARATOR,
File.pathSeparator);
if (Shell.isJavaVers... | @Test(timeout = 10000)
public void testEnvExpansion() throws IOException {
Path logPath = new Path("/nm/container/logs");
String input =
Apps.crossPlatformify("HADOOP_HOME") + "/share/hadoop/common/*"
+ ApplicationConstants.CLASS_PATH_SEPARATOR
+ Apps.crossPlatformify("HADOOP_H... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.