focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
@Override
public long arrayAppend(String path, Object... values) {
return get(arrayAppendAsync(path, values));
} | @Test
public void testArrayAppend() {
RJsonBucket<TestType> al = redisson.getJsonBucket("test", new JacksonCodec<>(TestType.class));
TestType t = new TestType();
NestedType nt = new NestedType();
nt.setValues(Arrays.asList("t1", "t2"));
t.setType(nt);
al.set(t);
... |
@Override
public PageResult<CouponTemplateDO> getCouponTemplatePage(CouponTemplatePageReqVO pageReqVO) {
return couponTemplateMapper.selectPage(pageReqVO);
} | @Test
public void testGetCouponTemplatePage() {
// mock 数据
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class, o -> { // 等会查询到
o.setName("芋艿");
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
o.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getT... |
@Override
public void validate(final Analysis analysis) {
try {
RULES.forEach(rule -> rule.check(analysis));
} catch (final KsqlException e) {
throw new KsqlException(e.getMessage() + PULL_QUERY_SYNTAX_HELP, e);
}
QueryValidatorUtil.validateNoUserColumnsWithSameNameAsPseudoColumns(analysis... | @Test
public void shouldThrowOnPartitionBy() {
// Given:
when(analysis.getPartitionBy()).thenReturn(Optional.of(new PartitionBy(
Optional.empty(),
ImmutableList.of(AN_EXPRESSION)
)));
// When:
final Exception e = assertThrows(
KsqlException.class,
() -> validator.v... |
Object getFromStep(String stepId, String paramName) {
try {
return executor
.submit(() -> fromStep(stepId, paramName))
.get(TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new MaestroInternalError(
e, "getFromStep throws an exception for stepId=... | @Test
public void testGetFromStep() throws Exception {
StepRuntimeSummary summary = loadObject(TEST_STEP_RUNTIME_SUMMARY, StepRuntimeSummary.class);
when(allStepOutputData.get("step1"))
.thenReturn(Collections.singletonMap("maestro_step_runtime_summary", summary));
assertEquals("foo", paramExtensi... |
public static <T> T head(final T[] elements) {
checkNotNull(elements);
if (elements.length == 0) {
return null;
}
return elements[0];
} | @Test
public void should_get_head() {
assertThat(Iterables.head(new Integer[]{1, 2}), is(1));
assertThat(Iterables.head(new Integer[]{1}), is(1));
assertThat(Iterables.head(new Integer[0]), nullValue());
assertThrows(NullPointerException.class, () -> Iterables.head(null));
} |
@Override
public boolean hasDesiredResources() {
final Collection<? extends SlotInfo> freeSlots =
declarativeSlotPool.getFreeSlotTracker().getFreeSlotsInformation();
return hasDesiredResources(desiredResources, freeSlots);
} | @Test
void testHasEnoughResourcesReturnsTrueIfSatisfied() {
final ResourceCounter resourceRequirement =
ResourceCounter.withResource(ResourceProfile.UNKNOWN, 1);
final Collection<TestingSlot> freeSlots =
createSlotsForResourceRequirements(resourceRequirement);
... |
public static <K, V> Read<K, V> read() {
return new AutoValue_CdapIO_Read.Builder<K, V>().build();
} | @Test
public void testReadObjectCreationFailsIfPullFrequencySecIsNull() {
assertThrows(
IllegalArgumentException.class,
() -> CdapIO.<String, String>read().withPullFrequencySec(null));
} |
@Override
public void handle(CommitterEvent event) {
try {
eventQueue.put(event);
} catch (InterruptedException e) {
throw new YarnRuntimeException(e);
}
} | @Test
public void testBasic() throws Exception {
AppContext mockContext = mock(AppContext.class);
OutputCommitter mockCommitter = mock(OutputCommitter.class);
Clock mockClock = mock(Clock.class);
CommitterEventHandler handler = new CommitterEventHandler(mockContext,
mockCommitter, new Te... |
@Override
public Optional<Map<String, EncryptionInformation>> getReadEncryptionInformation(
ConnectorSession session,
Table table,
Optional<Set<HiveColumnHandle>> requestedColumns,
Map<String, Partition> partitions)
{
Optional<DwrfTableEncryptionProperties... | @Test
public void testGetReadEncryptionInformationForPartitionedTableWithTableLevelEncryption()
{
Table table = createTable(DWRF, Optional.of(forTable("table_level_key", "algo", "provider")), true);
Optional<Map<String, EncryptionInformation>> encryptionInformation = encryptionInformationSource.... |
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
// Do not allow framing; OF-997
... | @Test
public void willRedirectARequestIfTheServletRequestAuthenticatorReturnsAnUnauthorisedUser() throws Exception {
AuthCheckFilter.SERVLET_REQUEST_AUTHENTICATOR.setValue(NormalUserServletAuthenticatorClass.class);
final AuthCheckFilter filter = new AuthCheckFilter(adminManager, loginLimitManager)... |
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \... | @Test
void testInvalidMessage() throws RemotingException {
defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null);
defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null);
given(mockChannel.attr(ChangeTelnet.SERVICE_KEY))
.willReturn(defaultAttributeMap.attr(Change... |
@Override
public ValidationResult validate(Object value) {
ValidationResult result = super.validate(value);
if (result instanceof ValidationResult.ValidationPassed) {
final String sValue = (String)value;
if (sValue.length() < minLength || sValue.length() > maxLength) {
... | @Test
public void testValidateEmptyValue() {
assertThat(new LimitedStringValidator(1, 1).validate(""))
.isInstanceOf(ValidationResult.ValidationFailed.class);
} |
@Override
public void destroy() {
ManagedExecutorService asyncExecutor = getMapStoreExecutor();
asyncExecutor.submit(() -> {
awaitInitFinished();
// Instance is not shutting down.
// Only GenericMapLoader is being closed
if (instance.isRunning()) {
... | @Test
public void whenMapLoaderDestroyOnMaster_thenDropMapping() {
objectProvider.createObject(mapName, false);
mapLoader = createMapLoader();
assertMappingCreated();
mapLoader.destroy();
assertMappingDestroyed();
} |
@Override
public Health check(Set<NodeHealth> nodeHealths) {
Set<NodeHealth> appNodes = nodeHealths.stream()
.filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION)
.collect(Collectors.toSet());
return Arrays.stream(AppNodeClusterHealthSubChecks.values())
.map(s -> s.check(ap... | @Test
public void status_YELLOW_when_single_YELLOW_application_node() {
Set<NodeHealth> nodeHealths = nodeHealths(YELLOW).collect(toSet());
Health check = underTest.check(nodeHealths);
assertThat(check)
.forInput(nodeHealths)
.hasStatus(Health.Status.YELLOW)
.andCauses(
"Status... |
@PublicEvolving
public static <IN, OUT> TypeInformation<OUT> getMapReturnTypes(
MapFunction<IN, OUT> mapInterface, TypeInformation<IN> inType) {
return getMapReturnTypes(mapInterface, inType, null, false);
} | @SuppressWarnings({"unchecked", "rawtypes"})
@Test
void testInputMismatchWithRawFuntion() {
MapFunction<?, ?> function = new MapWithResultTypeQueryable();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
(MapFunction) function, BasicTypeInfo.INT_T... |
public static Document loadXMLFrom( String xml ) throws SAXException, IOException {
return loadXMLFrom( new ByteArrayInputStream( xml.getBytes() ) );
} | @Test
public void whenLoadingLegalXmlFromStringNotNullDocumentIsReturned() throws Exception {
final String trans = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<transformation>"
+ "</transformation>";
assertNotNull( PDIImportUtil.loadXMLFrom( trans ) );
} |
static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) {
ProjectMeasuresQuery query = new ProjectMeasuresQuery();
Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids);
criteria.forEach(criterion -> processCriterion(criterion, query));... | @Test
public void filter_on_projectUuids_if_projectUuid_is_empty_and_criteria_non_empty() {
ProjectMeasuresQuery query = newProjectMeasuresQuery(singletonList(Criterion.builder().setKey("ncloc").setOperator(GT).setValue("10").build()),
emptySet());
assertThat(query.getProjectUuids()).isPresent();
} |
public Object set(final String property, final Object value) {
Objects.requireNonNull(value, "value");
final Object parsed = parser.parse(property, value);
return props.put(property, parsed);
} | @Test(expected = IllegalArgumentException.class)
public void shouldNotAllowUnknownConsumerPropertyToBeSet() {
realProps.set(StreamsConfig.CONSUMER_PREFIX + "some.unknown.prop", "some.value");
} |
@Nullable public Span currentSpan() {
TraceContext context = currentTraceContext.get();
if (context == null) return null;
// Returns a lazy span to reduce overhead when tracer.currentSpan() is invoked just to see if
// one exists, or when the result is never used.
return new LazySpan(this, context);... | @Test void currentSpan_defaultsToNull() {
assertThat(tracer.currentSpan()).isNull();
} |
public Set<FlowRule> flowtable() {
JsonNode ents = object.path(ENTRIES);
if (!ents.isArray()) {
return ImmutableSet.of();
}
ArrayNode entries = (ArrayNode) ents;
Builder<FlowRule> builder = ImmutableSet.builder();
entries.forEach(entry -> builder.add(decode(... | @Test
public void writeTest() throws JsonProcessingException, IOException {
FlowTableConfig w = new FlowTableConfig();
w.init(DID, FlowTableConfig.CONFIG_KEY, mapper.createObjectNode(), mapper, noopDelegate);
Set<FlowRule> table = ImmutableSet.of(FLOW_RULE);
w.flowtable(table);
... |
@Override
public String formatNotifyTemplateContent(String content, Map<String, Object> params) {
return StrUtil.format(content, params);
} | @Test
public void testFormatNotifyTemplateContent() {
// 准备参数
Map<String, Object> params = new HashMap<>();
params.put("name", "小红");
params.put("what", "饭");
// 调用,并断言
assertEquals("小红,你好,饭吃了吗?",
notifyTemplateService.formatNotifyTemplateContent("{na... |
Timer.Context getTimerContextFromExchange(Exchange exchange, String propertyName) {
return exchange.getProperty(propertyName, Timer.Context.class);
} | @Test
public void testGetTimerContextFromExchange() {
when(exchange.getProperty(PROPERTY_NAME, Timer.Context.class)).thenReturn(context);
assertThat(producer.getTimerContextFromExchange(exchange, PROPERTY_NAME), is(context));
inOrder.verify(exchange, times(1)).getProperty(PROPERTY_NAME, Time... |
@ApiOperation(value = "Create a user", tags = { "Users" }, code = 201)
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Indicates the user was created."),
@ApiResponse(code = 400, message = "Indicates the id of the user was missing.")
})
@PostMapping(value = "/identity/us... | @Test
public void testCreateUser() throws Exception {
try {
ObjectNode requestNode = objectMapper.createObjectNode();
requestNode.put("id", "testuser");
requestNode.put("firstName", "Frederik");
requestNode.put("lastName", "Heremans");
requestNode.... |
@Override
public Optional<Customer> findByName(String name) throws SQLException {
var sql = "select * from CUSTOMERS where name = ?;";
try (var connection = dataSource.getConnection();
var preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setString(1, name);
Resul... | @Test
void shouldFindCustomerByName() throws SQLException {
var customer = customerDao.findByName("customer");
assertTrue(customer.isEmpty());
TestUtils.executeSQL(INSERT_CUSTOMER_SQL, dataSource);
customer = customerDao.findByName("customer");
assertTrue(customer.isPresent());
assertEqual... |
@Override
public ScalarOperator visitBinaryPredicate(BinaryPredicateOperator predicate, Void context) {
return shuttleIfUpdate(predicate);
} | @Test
void testBinaryOperator() {
BinaryPredicateOperator operator = new BinaryPredicateOperator(BinaryType.EQ,
new ColumnRefOperator(1, INT, "id", true), ConstantOperator.createInt(1));
{
ScalarOperator newOperator = shuttle.visitBinaryPredicate(operator, null);
... |
public static void checkKeyParam(String dataId, String group) throws NacosException {
if (StringUtils.isBlank(dataId) || !ParamUtils.isValid(dataId)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, DATAID_INVALID_MSG);
}
if (StringUtils.isBlank(group) || !ParamUtils.i... | @Test
void testCheckKeyParam1() throws NacosException {
String dataId = "b";
String group = "c";
ParamUtils.checkKeyParam(dataId, group);
try {
dataId = "";
group = "c";
ParamUtils.checkKeyParam(dataId, group);
fail();
... |
public void checkWritePermission(String gitlabUrl, String personalAccessToken) {
String url = format("%s/markdown", gitlabUrl);
LOG.debug("verify write permission by formating some markdown : [{}]", url);
Request.Builder builder = new Request.Builder()
.url(url)
.addHeader(PRIVATE_TOKEN, person... | @Test
public void fail_check_write_permission_with_unexpected_io_exception_with_detailed_log() throws IOException {
server.shutdown();
assertThatThrownBy(() -> underTest.checkWritePermission(gitlabUrl, "token"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not validate GitLab ... |
public static <T> T createInstance(String userClassName,
Class<T> xface,
ClassLoader classLoader) {
Class<?> theCls;
try {
theCls = Class.forName(userClassName, true, classLoader);
} catch (ClassNotFoundExc... | @Test
public void testCreateTypedInstanceAbstractClass() {
try {
createInstance(AbstractClass.class.getName(), aInterface.class, classLoader);
fail("Should fail to load abstract class");
} catch (RuntimeException re) {
assertTrue(re.getCause() instanceof Instantia... |
@Udf
public Long trunc(@UdfParameter final Long val) {
return val;
} | @Test
public void shouldTruncateDoubleWithDecimalPlacesPositive() {
assertThat(udf.trunc(0d, 0), is(0d));
assertThat(udf.trunc(1.0d, 0), is(1.0d));
assertThat(udf.trunc(1.1d, 0), is(1.0d));
assertThat(udf.trunc(1.5d, 0), is(1.0d));
assertThat(udf.trunc(1.75d, 0), is(1.0d));
assertThat(udf.trun... |
public void validateSamlRequest(SamlRequest samlRequest, Signature signature) throws SamlValidationException {
try {
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
profileValidator.validate(signature);
} catch (SignatureException e) {
... | @Test
public void verifyRequestSignatureValid() throws SamlValidationException {
assertDoesNotThrow(() -> signatureService.validateSamlRequest(null, null));
} |
public List<InterpreterResultMessage> message() {
return msg;
} | @Test
void testTextType() {
InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
"this is a TEXT type");
assertEquals(InterpreterResult.Type.TEXT, result.message().get(0).getType(), "No magic");
result = new InterpreterResult(InterpreterResult.Code.SUCCESS, "%this is a... |
@Override
public void init(final InternalProcessorContext<KIn, VIn> context) {
// It is important to first create the sensor before calling init on the
// parent object. Otherwise due to backwards compatibility an empty sensor
// without parent is created with the same name.
// Once ... | @Test
public void shouldThrowStreamsExceptionOnUndefinedKeySerde() {
final InternalMockProcessorContext<String, String> context = new InternalMockProcessorContext<>();
final SourceNode<String, String> node =
new SourceNode<>(context.currentNode().name(), new TheDeserializer(), new TheDe... |
@Override
public <T> List<ExtensionWrapper<T>> find(Class<T> type) {
log.debug("Finding extensions of extension point '{}'", type.getName());
Map<String, Set<String>> entries = getEntries();
List<ExtensionWrapper<T>> result = new ArrayList<>();
// add extensions found in classpath a... | @Test
public void testFindFromClasspath() {
ExtensionFinder instance = new AbstractExtensionFinder(pluginManager) {
@Override
public Map<String, Set<String>> readPluginsStorages() {
return Collections.emptyMap();
}
@Override
publi... |
@Override
public void doPublishConfig(final String dataId, final Object data) {
this.apolloClient.createOrUpdateItem(dataId, data, "create config data");
this.apolloClient.publishNamespace("publish config data", "");
} | @Test
public void testPublishConfig() {
doNothing().when(apolloClient)
.createOrUpdateItem(Mockito.any(), Mockito.<Object>any(), Mockito.any());
doNothing().when(apolloClient).publishNamespace(Mockito.any(), Mockito.any());
apolloDataChangedListener.doPublishConfig("42", "Dat... |
@Override
public void createNamespace(Namespace namespace, Map<String, String> metadata) {
if (namespaceExists(namespace)) {
throw new AlreadyExistsException("Namespace already exists: %s", namespace);
}
Map<String, String> createMetadata;
if (metadata == null || metadata.isEmpty()) {
cre... | @Test
public void testCreateNamespace() {
Namespace testNamespace = Namespace.of("testDb", "ns1", "ns2");
assertThat(catalog.namespaceExists(testNamespace)).isFalse();
assertThat(catalog.namespaceExists(Namespace.of("testDb", "ns1"))).isFalse();
catalog.createNamespace(testNamespace);
assertThat(c... |
public Fetch<K, V> collectFetch(final FetchBuffer fetchBuffer) {
final Fetch<K, V> fetch = Fetch.empty();
final Queue<CompletedFetch> pausedCompletedFetches = new ArrayDeque<>();
int recordsRemaining = fetchConfig.maxPollRecords;
try {
while (recordsRemaining > 0) {
... | @Test
public void testFetchWithTopicAuthorizationFailed() {
buildDependencies();
assignAndSeek(topicAPartition0);
// Try to data and validate that we get an empty Fetch back.
CompletedFetch completedFetch = completedFetchBuilder
.error(Errors.TOPIC_AUTHORIZATION_FAIL... |
public static String bytesToString(List<?> bytesList) {
byte[] bytes = bytesFromList(bytesList);
return new String(bytes);
} | @Test
public void bytesFromList_SpecSymbol() {
List<String> listHex = new ArrayList<>(Arrays.asList("1D", "0x1D", "1F", "0x1F", "0x20", "0x20"));
byte[] expectedBytes = new byte[]{29, 29, 31, 31, 32, 32};
String actualStr = TbUtils.bytesToString(listHex);
byte[] actualBytes = actualS... |
public static Schema fromTableSchema(TableSchema tableSchema) {
return fromTableSchema(tableSchema, SchemaConversionOptions.builder().build());
} | @Test
public void testFromTableSchema_enum() {
Schema beamSchema = BigQueryUtils.fromTableSchema(BQ_ENUM_TYPE);
assertEquals(ENUM_STRING_TYPE, beamSchema);
} |
@Override
public boolean isTrusted(Address address) {
if (address == null) {
return false;
}
if (trustedInterfaces.isEmpty()) {
return true;
}
String host = address.getHost();
if (matchAnyInterface(host, trustedInterfaces)) {
retur... | @Test
public void givenInterfaceRangeIsConfigured_whenMessageWithMatchingHost_thenTrust() throws UnknownHostException {
AddressCheckerImpl joinMessageTrustChecker = new AddressCheckerImpl(singleton("127.0.0.1-100"), logger);
Address address = createAddress("127.0.0.2");
assertTrue(joinMessag... |
public void schedule(final ScheduledHealthCheck check, final boolean healthy) {
unschedule(check.getName());
final Duration interval;
if (healthy) {
interval = check.getSchedule().getCheckInterval();
} else {
interval = check.getSchedule().getDowntimeInterval();
... | @Test
void shouldRescheduleCheckForUnhealthyDependency() {
final String name = "test";
final Schedule schedule = new Schedule();
final ScheduledFuture future = mock(ScheduledFuture.class);
when(future.cancel(true)).thenReturn(true);
final ScheduledHealthCheck check = mock(S... |
@Bean("Configuration")
public Configuration provide(Settings settings) {
return new ServerConfigurationAdapter(settings);
} | @Test
@UseDataProvider("emptyFields2")
public void getStringArray_on_unknown_or_non_multivalue_properties_ignores_empty_fields_differently_from_settings(String emptyFields, String[] expected) {
settings.setProperty(nonDeclaredKey, emptyFields);
settings.setProperty(nonMultivalueKey, emptyFields);
Confi... |
@Override
public boolean processData(DistroData distroData) {
switch (distroData.getType()) {
case ADD:
case CHANGE:
ClientSyncData clientSyncData = ApplicationUtils.getBean(Serializer.class)
.deserialize(distroData.getContent(), ClientSyncData... | @Test
void testProcessDataForDeleteClient() {
distroData.setType(DataOperation.DELETE);
distroClientDataProcessor.processData(distroData);
verify(clientManager).clientDisconnected(CLIENT_ID);
} |
@Override
public void addPartitions(String dbName, String tableName, List<HivePartitionWithStats> partitions) {
List<org.apache.hadoop.hive.metastore.api.Partition> hivePartitions = partitions.stream()
.map(HiveMetastoreApiConverter::toMetastoreApiPartition)
.collect(Collecto... | @Test
public void testAddPartitions() {
HiveMetaClient client = new MockedHiveMetaClient();
HiveMetastore metastore = new HiveMetastore(client, "hive_catalog", MetastoreType.HMS);
HivePartition hivePartition = HivePartition.builder()
.setColumns(Lists.newArrayList(new Column(... |
public void defineDocStringType(DocStringType docStringType) {
DocStringType existing = lookupByContentTypeAndType(docStringType.getContentType(), docStringType.getType());
if (existing != null) {
throw createDuplicateTypeException(existing, docStringType);
}
Map<Type, DocStr... | @Test
void anonymous_doc_string_is_predefined() {
DocStringType docStringType = new DocStringType(
String.class,
DEFAULT_CONTENT_TYPE,
(String s) -> s);
CucumberDocStringException actualThrown = assertThrows(
CucumberDocStringException.class, () -> re... |
public List<String> getChildren(final String key) {
try {
return client.getChildren().forPath(key);
} catch (Exception e) {
LOGGER.error("zookeeper get child error=", e);
return Collections.emptyList();
}
} | @Test
void getChildren() throws Exception {
assertTrue(client.getChildren("/test").isEmpty());
GetChildrenBuilder getChildrenBuilder = mock(GetChildrenBuilder.class);
when(curatorFramework.getChildren()).thenReturn(getChildrenBuilder);
when(getChildrenBuilder.forPath(anyString())).th... |
public List<CommentSimpleResponse> findAllWithPaging(final Long boardId, final Long memberId, final Long commentId, final int pageSize) {
return jpaQueryFactory.select(constructor(CommentSimpleResponse.class,
comment.id,
comment.content,
me... | @Test
void no_offset_페이징_첫_조회() {
// given
for (long i = 1L; i <= 20L; i++) {
commentRepository.save(Comment.builder()
.id(i)
.boardId(board.getId())
.content("comment")
.writerId(member.getId())
... |
@Override
public void close() throws IOException {
close(true);
} | @Test
public void testMultipleClose() throws IOException {
S3OutputStream stream = new S3OutputStream(s3, randomURI(), properties, nullMetrics());
stream.close();
stream.close();
} |
public static List<ArtifactPlan> toArtifactPlans(ArtifactTypeConfigs artifactConfigs) {
List<ArtifactPlan> artifactPlans = new ArrayList<>();
for (ArtifactTypeConfig artifactTypeConfig : artifactConfigs) {
artifactPlans.add(new ArtifactPlan(artifactTypeConfig));
}
return arti... | @Test
public void toArtifactPlans_shouldConvertArtifactConfigsToArtifactPlanList() {
final PluggableArtifactConfig artifactConfig = new PluggableArtifactConfig("id", "storeId", create("Foo", true, "Bar"));
final ArtifactTypeConfigs artifactTypeConfigs = new ArtifactTypeConfigs(Arrays.asList(
... |
@Override
public void ping() {
try {
if (sslInfrastructureService.isRegistered()) {
AgentIdentifier agent = agentIdentifier();
LOG.trace("{} is pinging server [{}]", agent, client);
getAgentRuntimeInfo().refreshUsableSpace();
agen... | @Test
void shouldPingIfAfterRegistered() {
when(agentRegistry.uuid()).thenReturn(agentUuid);
when(sslInfrastructureService.isRegistered()).thenReturn(true);
agentController = createAgentController();
agentController.init();
agentController.ping();
verify(sslInfrastruc... |
public static Function.FunctionMetaData incrMetadataVersion(Function.FunctionMetaData existingMetaData,
Function.FunctionMetaData updatedMetaData) {
long version = 0;
if (existingMetaData != null) {
version = existingMetaData.ge... | @Test
public void testUpdate() {
long version = 5;
Function.FunctionMetaData existingMetaData = Function.FunctionMetaData.newBuilder().setFunctionDetails(
Function.FunctionDetails.newBuilder().setName("func-1").setParallelism(2)).setVersion(version).build();
Function.Function... |
@Transactional
public void deleteChecklistById(User user, long id) {
Checklist checklist = checklistRepository.getById(id);
validateChecklistOwnership(user, checklist);
checklistQuestionRepository.deleteAllByChecklistId(checklist.getId());
checklistOptionRepository.deleteAllByCheckli... | @DisplayName("체크리스트 삭제 실패 : 체크리스트 작성 유저와 삭제하려는 유저가 다른 경우")
@Test
void deleteChecklistById_notOwnedByUser_exception() {
// given
roomRepository.save(RoomFixture.ROOM_1);
Checklist checklist = checklistRepository.save(ChecklistFixture.CHECKLIST1_USER1);
// when & then
asse... |
public static String padLeft(String s, int n) {
return String.format("%1$" + n + "s", s);
} | @Test
public void testPadLeft(){
String a = "hello";
String b = StringKit.padLeft(a, 10);
Assert.assertEquals(" hello", b);
} |
public synchronized Topology addStateStore(final StoreBuilder<?> storeBuilder,
final String... processorNames) {
internalTopologyBuilder.addStateStore(storeBuilder, processorNames);
return this;
} | @Test
public void shouldNotAddNullStateStoreSupplier() {
assertThrows(NullPointerException.class, () -> topology.addStateStore(null));
} |
public static ShenyuPluginLoader getInstance() {
if (null == pluginLoader) {
synchronized (ShenyuPluginLoader.class) {
if (null == pluginLoader) {
pluginLoader = new ShenyuPluginLoader();
}
}
}
return pluginLoader;
} | @Test
public void testGetInstance() {
assertThat(shenyuPluginLoader, is(ShenyuPluginLoader.getInstance()));
} |
public static String fix(final String raw) {
if ( raw == null || "".equals( raw.trim() )) {
return raw;
}
MacroProcessor macroProcessor = new MacroProcessor();
macroProcessor.setMacros( macros );
return macroProcessor.parse( raw );
} | @Test
public void testAdd__Handle__Simple() {
String result = KnowledgeHelperFixerTest.fixer.fix( "update(myObject );" );
assertEqualsIgnoreWhitespace( "drools.update(myObject );",
result );
result = KnowledgeHelperFixerTest.fixer.fix( "update ( myObjec... |
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass != null) {
return loadedClass;
}
if (isClosed) {
throw new ClassNotFoun... | @Test
public void callingNormalMethodReturningIntegerShouldInvokeClassHandler() throws Exception {
Class<?> exampleClass = loadClass(AClassWithMethodReturningInteger.class);
classHandler.valueToReturn = 456;
Method normalMethod = exampleClass.getMethod("normalMethodReturningInteger", int.class);
Obje... |
@Override
public AttributedList<Path> search(final Path workdir, final Filter<Path> regex, final ListProgressListener listener) throws BackgroundException {
if(workdir.isRoot()) {
final AttributedList<Path> result = new AttributedList<>();
final AttributedList<Path> buckets = new Goo... | @Test
public void testSearchInDirectory() throws Exception {
final Path bucket = new Path("cyberduck-test-eu", EnumSet.of(Path.Type.directory, Path.Type.volume));
final String name = new AlphanumericRandomStringService().random();
final Path file = new GoogleStorageTouchFeature(session).touc... |
@Override
public Object evaluate(final ProcessingDTO processingDTO) {
return commonEvaluate(getValue(), dataType);
} | @Test
void evaluate() {
Object value = 234.45;
final KiePMMLConstant kiePMMLConstant1 = new KiePMMLConstant("NAME", Collections.emptyList(), value, null);
ProcessingDTO processingDTO = new ProcessingDTO(Collections.emptyList(), Collections.emptyList(),
... |
public String getClusterProfileChangedRequestBody(ClusterProfilesChangedStatus status, Map<String, String> oldClusterProfile, Map<String, String> newClusterProfile) {
return switch (status) {
case CREATED -> getClusterCreatedRequestBody(newClusterProfile);
case UPDATED -> getClusterUpdat... | @Test
public void shouldGetClusterProfilesChangedRequestBodyWhenClusterProfileIsUpdated() {
ClusterProfilesChangedStatus status = ClusterProfilesChangedStatus.UPDATED;
Map<String, String> oldClusterProfile = Map.of("old_key1", "old_key2");
Map<String, String> newClusterProfile = Map.of("key1... |
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) {
return api.send(request);
} | @Test
public void sendSpoilerMessage() {
SendResponse response = bot.execute(new SendMessage(chatId, "ok this is spoiler ha-ha-ha")
.entities(new MessageEntity(MessageEntity.Type.spoiler, 19, 8)));
MessageEntity entity = response.message().entities()[0];
assertEquals(Message... |
public File pathToFile(Path path) {
return ((RawLocalFileSystem)fs).pathToFile(path);
} | @Test
public void testFileStatusPipeFile() throws Exception {
RawLocalFileSystem origFs = new RawLocalFileSystem();
RawLocalFileSystem fs = spy(origFs);
Configuration conf = mock(Configuration.class);
fs.setConf(conf);
RawLocalFileSystem.setUseDeprecatedFileStatus(false);
Path path = new Path... |
public static <E> List<E> ensureImmutable(List<E> list) {
if (list.isEmpty()) return Collections.emptyList();
// Faster to make a copy than check the type to see if it is already a singleton list
if (list.size() == 1) return Collections.singletonList(list.get(0));
if (isImmutable(list)) return list;
... | @Test void ensureImmutable_returnsEmptyList() {
List<Object> list = Collections.emptyList();
assertThat(Lists.ensureImmutable(list))
.isSameAs(list);
} |
public static TrieRouter createRoute() {
return new TrieRouter();
} | @Test
public void testRouteMatch() {
PathKit.TrieRouter trieRouter = PathKit.createRoute();
trieRouter.addRoute("/static/**");
trieRouter.addRoute("/users/:userId");
trieRouter.addRoute("/users/**");
trieRouter.addRoute("/users/bg/**");
trieRouter.addRoute("/login");
... |
@Override
public boolean find(final Path file, final ListProgressListener listener) throws BackgroundException {
if(file.isRoot()) {
return true;
}
try {
try {
try {
final HttpHead request = new HttpHead(new DAVPathEncoder().encode(... | @Test
public void testFindNotFound() throws Exception {
assertFalse(new DAVFindFeature(session).find(new Path(new DefaultHomeFinderService(session).find(), new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.directory))));
assertFalse(new DAVFindFeature(session).find(new Path(new De... |
@Override
public void store(Measure newMeasure) {
saveMeasure(newMeasure.inputComponent(), (DefaultMeasure<?>) newMeasure);
} | @Test
public void store_whenAdhocRuleIsSpecifiedWithOptionalFieldEmpty_shouldWriteAdhocRuleWithDefaultImpactsToReport() {
underTest.store(new DefaultAdHocRule().ruleId("ruleId").engineId("engineId")
.name("name")
.description("description"));
try (CloseableIterator<ScannerReport.AdHocRule> adhocRu... |
@Override public String getLegacyColumnName( DatabaseMetaData dbMetaData, ResultSetMetaData rsMetaData, int index ) throws KettleDatabaseException {
if ( dbMetaData == null ) {
throw new KettleDatabaseException( BaseMessages.getString( PKG, "MySQLDatabaseMeta.Exception.LegacyColumnNameNoDBMetaDataException" )... | @Test
public void testGetLegacyColumnNameFieldDB() throws Exception {
assertEquals( "DB", new MariaDBDatabaseMeta().getLegacyColumnName( mock( DatabaseMetaData.class ), getResultSetMetaData(), 5 ) );
} |
static List<ProviderInfo> convertInstancesToProviders(List<Instance> allInstances) {
List<ProviderInfo> providerInfos = new ArrayList<ProviderInfo>();
if (CommonUtils.isEmpty(allInstances)) {
return providerInfos;
}
for (Instance instance : allInstances) {
String... | @Test
public void testNacosWeightWith0() {
Instance instance = new Instance();
instance.setClusterName(NacosRegistryHelper.DEFAULT_CLUSTER);
instance.setIp("1.1.1.1");
instance.setPort(12200);
instance.setServiceName("com.alipay.xxx.TestService");
instance.setWeight(0... |
public static boolean validateExecuteBitPresentIfReadOrWrite(FsAction perms) {
if ((perms == FsAction.READ) || (perms == FsAction.WRITE)
|| (perms == FsAction.READ_WRITE)) {
return false;
}
return true;
} | @Test
public void testExecutePermissionsCheck() {
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.ALL));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.NONE));
Assert.assertTrue(HCatUtil.validateExecuteBitPresentIfReadOrWrite(FsAction.EXECUTE));
A... |
Future<RecordMetadata> send(final ProducerRecord<byte[], byte[]> record,
final Callback callback) {
maybeBeginTransaction();
try {
return producer.send(record, callback);
} catch (final KafkaException uncaughtException) {
if (isRecoverable(... | @Test
public void shouldFailOnEosAbortTxFatal() {
eosAlphaMockProducer.abortTransactionException = new RuntimeException("KABOOM!");
// call `send()` to start a transaction
eosAlphaStreamsProducer.send(record, null);
final RuntimeException thrown = assertThrows(RuntimeException.class... |
@Override
public ByteBuf setIndex(int readerIndex, int writerIndex) {
if (checkBounds) {
checkIndexBounds(readerIndex, writerIndex, capacity());
}
setIndex0(readerIndex, writerIndex);
return this;
} | @Test
public void setIndexBoundaryCheck1() {
assertThrows(IndexOutOfBoundsException.class, new Executable() {
@Override
public void execute() {
buffer.setIndex(-1, CAPACITY);
}
});
} |
@Override
public List<?> deserialize(final String topic, final byte[] bytes) {
if (bytes == null) {
return null;
}
try {
final String recordCsvString = new String(bytes, StandardCharsets.UTF_8);
final List<CSVRecord> csvRecords = CSVParser.parse(recordCsvString, csvFormat)
.ge... | @Test
public void shouldDeserializeJsonCorrectlyWithEmptyFields() {
// Given:
final byte[] bytes = "1511897796092,1,item_1,,,,,,\r\n".getBytes(StandardCharsets.UTF_8);
// When:
final List<?> result = deserializer.deserialize("", bytes);
// Then:
assertThat(result, contains(1511897796092L, 1L... |
@Udf
public String extractHost(
@UdfParameter(description = "a valid URL") final String input) {
return UrlParser.extract(input, URI::getHost);
} | @Test
public void shouldExtractHostIfPresent() {
assertThat(extractUdf.extractHost("https://docs.confluent.io:8080/current/ksql/docs/syntax-reference.html#scalar-functions"), equalTo("docs.confluent.io"));
} |
public static void writeBinaryCodedLengthBytes(byte[] data, ByteArrayOutputStream out) throws IOException {
// 1. write length byte/bytes
if (data.length < 252) {
out.write((byte) data.length);
} else if (data.length < (1 << 16L)) {
out.write((byte) 252);
writ... | @Test
public void testWriteBinaryCodedLengthBytes1() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteHelper.writeBinaryCodedLengthBytes(new byte[] {2, 4}, out);
Assert.assertArrayEquals(new byte[] {2, 2, 4}, (out.toByteArray()));
} |
public AggregateAnalysisResult analyze(
final ImmutableAnalysis analysis,
final List<SelectExpression> finalProjection
) {
if (!analysis.getGroupBy().isPresent()) {
throw new IllegalArgumentException("Not an aggregate query");
}
final AggAnalyzer aggAnalyzer = new AggAnalyzer(analysis, ... | @Test
public void shouldThrowOnGroupByAggregateFunction() {
// Given:
givenGroupByExpressions(AGG_FUNCTION_CALL);
// When:
final KsqlException e = assertThrows(KsqlException.class,
() -> analyzer.analyze(analysis, selects));
// Then:
assertThat(e.getMessage(), containsString(
... |
Method findMethod(ProceedingJoinPoint pjp) {
Class<?> clazz = pjp.getTarget().getClass();
Signature pjpSignature = pjp.getSignature();
String methodName = pjp.getSignature().getName();
Class[] parameterTypes = null;
if (pjpSignature instanceof MethodSignature) {
parameterTypes = ((MethodSignat... | @Test
public void testFindMethod() throws NoSuchMethodException {
ProceedingJoinPoint mockPJP = mock(ProceedingJoinPoint.class);
MockAuditClass mockAuditClass = new MockAuditClass();
MethodSignature signature = mock(MethodSignature.class);
Method method = MockAuditClass.class.getMethod("mockAuditMetho... |
public boolean isCheckpointingEnabled() {
if (snapshotSettings == null) {
return false;
}
return snapshotSettings.getCheckpointCoordinatorConfiguration().isCheckpointingEnabled();
} | @Test
public void checkpointingIsDisabledIfIntervalIsMaxValue() {
final JobGraph jobGraph =
JobGraphBuilder.newStreamingJobGraphBuilder()
.setJobCheckpointingSettings(
createCheckpointSettingsWithInterval(Long.MAX_VALUE))
... |
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext
if (processed.get()) {
return;
}
/**
* Gets Logger After LoggingSystem configurati... | @Test
public void testOnApplicationEvent() {
Assert.assertNotNull(welcomeLogoApplicationListener.buildBannerText());
} |
@Override
public Collection<SlotOffer> offerSlots(
Collection<? extends SlotOffer> offers,
TaskManagerLocation taskManagerLocation,
TaskManagerGateway taskManagerGateway,
long currentTime) {
log.debug("Received {} slot offers from TaskExecutor {}.", offers, t... | @TestTemplate
void testOfferSlots() throws InterruptedException {
final NewSlotsService notifyNewSlots = new NewSlotsService();
final DefaultDeclarativeSlotPool slotPool =
createDefaultDeclarativeSlotPoolWithNewSlotsListener(notifyNewSlots);
final ResourceCounter resourceReq... |
@Operation(summary = "countCommandState", description = "COUNT_COMMAND_STATE_NOTES")
@GetMapping(value = "/command-state-count")
@ResponseStatus(HttpStatus.OK)
@ApiException(COMMAND_STATE_COUNT_ERROR)
public Result<List<CommandStateCount>> countCommandState(@Parameter(hidden = true) @RequestAttribute(va... | @Test
public void testCountCommandState() throws Exception {
MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/command-state-count")
.header("sessionId", sessionId))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION... |
public static PeriodDuration analyzeDataCachePartitionDuration(Map<String, String> properties) throws AnalysisException {
String text = properties.get(PROPERTIES_DATACACHE_PARTITION_DURATION);
if (text == null) {
return null;
}
properties.remove(PROPERTIES_DATACACHE_PARTITION... | @Test
public void testAnalyzeDataCachePartitionDuration() {
Map<String, String> properties = new HashMap<>();
properties.put(PropertyAnalyzer.PROPERTIES_DATACACHE_PARTITION_DURATION, "7 day");
try {
PropertyAnalyzer.analyzeDataCachePartitionDuration(properties);
} catch ... |
public static <T> T checkNotNull(T reference,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(... | @Test
void checkNotNullInputZeroNotNull0OutputZero() {
// Arrange
final Object reference = 0;
final String errorMessageTemplate = " ";
final Object[] errorMessageArgs = {};
// Act
final Object retval = Util.checkNotNull(reference, errorMessageTemplate, errorMessageArgs);
// Assert result... |
public List<Upstream> findUpstreamListBySelectorId(final String selectorId) {
return task.getHealthyUpstream().get(selectorId);
} | @Test
@Order(4)
public void findUpstreamListBySelectorIdTest() {
final UpstreamCacheManager upstreamCacheManager = UpstreamCacheManager.getInstance();
Assertions.assertNull(upstreamCacheManager.findUpstreamListBySelectorId(SELECTOR_ID));
} |
public static String replaceTokens(String template, Pattern pattern,
Map<String, String> replacements) {
StringBuffer sb = new StringBuffer();
Matcher matcher = pattern.matcher(template);
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
if (replacement == n... | @Test (timeout = 5000)
public void testReplaceTokensWinEnvVars() {
Pattern pattern = StringUtils.WIN_ENV_VAR_PATTERN;
Map<String, String> replacements = new HashMap<String, String>();
replacements.put("foo", "zoo");
replacements.put("baz", "zaz");
assertEquals("zoo", StringUtils.replaceTokens("%f... |
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public KDiag(Configuration conf,
PrintWriter out,
File keytab,
String principal,
long minKeyLength,
boolean securityRequired) {
super(conf);
this.keytab = keytab;
this.principal = principal;
this.out = out;
this.... | @Test
public void testKeytabAndPrincipal() throws Throwable {
kdiag(ARG_KEYLEN, KEYLEN,
ARG_KEYTAB, keytab.getAbsolutePath(),
ARG_PRINCIPAL, "foo@EXAMPLE.COM");
} |
@Override
public Cursor<byte[]> scan(RedisClusterNode node, ScanOptions options) {
return new ScanCursor<byte[]>(0, options) {
private RedisClient client = getEntry(node);
@Override
protected ScanIteration<byte[]> doScan(long cursorId, ScanOptions options) {... | @Test
public void testScan() {
Map<byte[], byte[]> map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
map.put(RandomString.make(32).getBytes(), RandomString.make(32).getBytes(StandardCharsets.UTF_8));
}
connection.mSet(map);
Cursor<byte[]> b = connection.sc... |
@Override
protected boolean isContextRequired() {
return false;
} | @Test
public void isContextRequiredTest() {
assertFalse(exporter.isContextRequired());
} |
public static UserGroupInformation getUGI(HttpServletRequest request,
Configuration conf) throws IOException {
return getUGI(null, request, conf);
} | @Test
public void testGetUgiDuringStartup() throws Exception {
conf.set(DFSConfigKeys.FS_DEFAULT_NAME_KEY, "hdfs://localhost:4321/");
ServletContext context = mock(ServletContext.class);
String realUser = "TheDoctor";
String user = "TheNurse";
conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION,... |
@GetMapping("/by-release")
public PageDTO<InstanceDTO> getByRelease(@RequestParam("releaseId") long releaseId,
Pageable pageable) {
Release release = releaseService.findOne(releaseId);
if (release == null) {
throw NotFoundException.releaseNotFound(releaseId);
... | @Test
public void getByRelease() throws Exception {
long someReleaseId = 1;
long someInstanceId = 1;
long anotherInstanceId = 2;
String someReleaseKey = "someKey";
Release someRelease = new Release();
someRelease.setReleaseKey(someReleaseKey);
String someAppId = "someAppId";
String ano... |
public CreateStreamCommand createStreamCommand(final KsqlStructuredDataOutputNode outputNode) {
return new CreateStreamCommand(
outputNode.getSinkName().get(),
outputNode.getSchema(),
outputNode.getTimestampColumn(),
outputNode.getKsqlTopic().getKafkaTopicName(),
Formats.from... | @Test
public void shouldThrowOnRowTimeKeyColumn() {
// Given:
final CreateStream statement = new CreateStream(
SOME_NAME,
TableElements.of(tableElement(ROWTIME_NAME.text(), new Type(BIGINT), KEY_CONSTRAINT)),
false,
true,
withProperties,
false
);
// Whe... |
public ReferenceBuilder<T> addMethods(List<MethodConfig> methods) {
if (this.methods == null) {
this.methods = new ArrayList<>();
}
this.methods.addAll(methods);
return getThis();
} | @Test
void addMethods() {
MethodConfig method = new MethodConfig();
ReferenceBuilder builder = new ReferenceBuilder();
builder.addMethods(Collections.singletonList(method));
Assertions.assertTrue(builder.build().getMethods().contains(method));
Assertions.assertEquals(1, build... |
public static boolean isLetter(CharSequence value) {
return StrUtil.isAllCharMatch(value, Character::isLetter);
} | @Test
public void isLetterTest() {
assertTrue(Validator.isLetter("asfdsdsfds"));
assertTrue(Validator.isLetter("asfdsdfdsfVCDFDFGdsfds"));
assertTrue(Validator.isLetter("asfdsdf你好dsfVCDFDFGdsfds"));
} |
public void mergeRuntimeUpdate(
List<TimelineEvent> pendingTimeline, Map<String, Artifact> pendingArtifacts) {
if (timeline.addAll(pendingTimeline)) {
synced = false;
}
if (pendingArtifacts != null && !pendingArtifacts.isEmpty()) {
for (Map.Entry<String, Artifact> entry : pendingArtifacts.... | @Test
public void testMergeTimeline() throws Exception {
StepRuntimeSummary summary =
loadObject(
"fixtures/execution/sample-step-runtime-summary-1.json", StepRuntimeSummary.class);
assertTrue(summary.isSynced());
TimelineEvent curEvent = summary.getTimeline().getTimelineEvents().get(0... |
public static MulticastMappingInstruction multicastWeight(int weight) {
return new MulticastMappingInstruction.WeightMappingInstruction(
MulticastType.WEIGHT, weight);
} | @Test
public void testMulticastWeightMethod() {
final MappingInstruction instruction = MappingInstructions.multicastWeight(2);
final MulticastMappingInstruction.WeightMappingInstruction weightMappingInstruction =
checkAndConvert(instruction,
MulticastM... |
@Override
public short getShortLE(int index) {
checkIndex(index, 2);
return _getShortLE(index);
} | @Test
public void testGetShortLEAfterRelease() {
assertThrows(IllegalReferenceCountException.class, new Executable() {
@Override
public void execute() {
releasedBuffer().getShortLE(0);
}
});
} |
public AggregationType computeAggregationType(String name) {
return this.aggregationAssessor.computeAggregationType(name);
} | @Test
public void testCanAggregateComponent() {
assertEquals(AggregationType.AS_COMPLEX_PROPERTY, setter.computeAggregationType("door"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAggregationType("count"));
assertEquals(AggregationType.AS_BASIC_PROPERTY, setter.computeAg... |
@Nonnull
public static Number shiftLeft(@Nonnull Number value, @Nonnull Number shift) {
// Check for widest types first, go down the type list to narrower types until reaching int.
if (value instanceof Long) {
return value.longValue() << shift.longValue();
} else {
return value.intValue() << shift.intValue... | @Test
void testShiftLeft() {
assertEquals(2 << 1, NumberUtil.shiftLeft(2, 1));
assertEquals(2L << 1, NumberUtil.shiftLeft(2L, 1));
} |
public static ECKeyPair decrypt(String password, WalletFile walletFile) throws CipherException {
validate(walletFile);
WalletFile.Crypto crypto = walletFile.getCrypto();
byte[] mac = Numeric.hexStringToByteArray(crypto.getMac());
byte[] iv = Numeric.hexStringToByteArray(crypto.getCiph... | @Test
public void testDecryptAes128Ctr() throws Exception {
WalletFile walletFile = load(AES_128_CTR);
ECKeyPair ecKeyPair = Wallet.decrypt(PASSWORD, walletFile);
assertEquals(Numeric.toHexStringNoPrefix(ecKeyPair.getPrivateKey()), (SECRET));
} |
public static void unbindGlobalLockFlag() {
Boolean lockFlag = (Boolean) CONTEXT_HOLDER.remove(KEY_GLOBAL_LOCK_FLAG);
if (LOGGER.isDebugEnabled() && lockFlag != null) {
LOGGER.debug("unbind global lock flag");
}
} | @Test
public void testUnBindGlobalLockFlag() {
RootContext.bindGlobalLockFlag();
assertThat(RootContext.requireGlobalLock()).isEqualTo(true);
RootContext.unbindGlobalLockFlag();
assertThat(RootContext.requireGlobalLock()).isEqualTo(false);
} |
public static Map<String, String> computeAliases(PluginScanResult scanResult) {
Map<String, Set<String>> aliasCollisions = new HashMap<>();
scanResult.forEach(pluginDesc -> {
aliasCollisions.computeIfAbsent(simpleName(pluginDesc), ignored -> new HashSet<>()).add(pluginDesc.className());
... | @Test
public void testMultiVersionAlias() {
SortedSet<PluginDesc<SinkConnector>> sinkConnectors = new TreeSet<>();
// distinct versions don't cause an alias collision (the class name is the same)
sinkConnectors.add(new PluginDesc<>(MockSinkConnector.class, null, PluginType.SINK, MockSinkConn... |
@Override
@CacheEvict(cacheNames = RedisKeyConstants.SMS_TEMPLATE,
allEntries = true) // allEntries 清空所有缓存,因为 id 不是直接的缓存 code,不好清理
public void deleteSmsTemplate(Long id) {
// 校验存在
validateSmsTemplateExists(id);
// 更新
smsTemplateMapper.deleteById(id);
} | @Test
public void testDeleteSmsTemplate_notExists() {
// 准备参数
Long id = randomLongId();
// 调用, 并断言异常
assertServiceException(() -> smsTemplateService.deleteSmsTemplate(id), SMS_TEMPLATE_NOT_EXISTS);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.