focal_method stringlengths 13 60.9k | test_case stringlengths 25 109k |
|---|---|
public Bson createDbQuery(final List<String> filters, final String query) {
try {
final var searchQuery = searchQueryParser.parse(query);
final var filterExpressionFilters = dbFilterParser.parse(filters, attributes);
return buildDbQuery(searchQuery, filterExpressionFilters);
... | @Test
void throwsBadRequestExceptionIfSearchQueryParserThrowsIllegalArgumentException() {
doThrow(IllegalArgumentException.class).when(searchQueryParser).parse(eq("wrong #$%#$%$ query"));
assertThrows(BadRequestException.class, () -> toTest.createDbQuery(List.of(), "wrong #$%#$%$ query"));
} |
@Operation(summary = "get", description = "Get a service")
@GetMapping("/{id}")
public ResponseEntity<ServiceVO> get(@PathVariable Long id) {
return ResponseEntity.success(serviceService.get(id));
} | @Test
void getReturnsNotFoundForInvalidId() {
Long id = 999L;
when(serviceService.get(id)).thenReturn(null);
ResponseEntity<ServiceVO> response = serviceController.get(id);
assertTrue(response.isSuccess());
assertNull(response.getData());
} |
@Description("current time with time zone")
@ScalarFunction
@SqlType(StandardTypes.TIME_WITH_TIME_ZONE)
public static long currentTime(SqlFunctionProperties properties)
{
// We do all calculation in UTC, as session.getStartTime() is in UTC
// and we need to have UTC millis for packDateTi... | @Test
public void testCurrentTime()
{
Session localSession = Session.builder(session)
// we use Asia/Kathmandu here to test the difference in semantic change of current_time
// between legacy and non-legacy timestamp
.setTimeZoneKey(KATHMANDU_ZONE_KEY)
... |
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.Ove... | @Test
public void testShouldReportOneMinuteFor89Seconds() {
assertEquals(TimeConverter.ABOUT_1_MINUTE_AGO, timeConverter.getConvertedTime(89));
} |
public static String stripTrailingSlash(String path) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(path), "path must not be null or empty");
String result = path;
while (!result.endsWith("://") && result.endsWith("/")) {
result = result.substring(0, result.length() - 1);
}
return resul... | @Test
public void testStripTrailingSlash() {
String pathWithoutTrailingSlash = "s3://bucket/db/tbl";
assertThat(LocationUtil.stripTrailingSlash(pathWithoutTrailingSlash))
.as("Should have no trailing slashes")
.isEqualTo(pathWithoutTrailingSlash);
String pathWithSingleTrailingSlash = path... |
@Override
public BundleContext bundleContext() {
if (restrictedBundleContext == null) {
throw newException();
}
return restrictedBundleContext;
} | @Test
void require_that_bundleContext_throws_exception() throws BundleException {
assertThrows(RuntimeException.class, () -> {
new DisableOsgiFramework().bundleContext();
});
} |
@Override
public boolean isDone() {
if (delegate == null) {
return isDone;
}
return delegate.isDone();
} | @Test
public void isDone() {
final Future<HttpResponse> delegate = Mockito.mock(Future.class);
FutureDecorator decorator = new FutureDecorator(null);
ReflectUtils.setFieldValue(decorator, "delegate", delegate);
decorator.isDone();
Mockito.verify(delegate, Mockito.times(1)).is... |
public static InsertRetryPolicy neverRetry() {
return new InsertRetryPolicy() {
@Override
public boolean shouldRetry(Context context) {
return false;
}
};
} | @Test
public void testNeverRetry() {
assertFalse(
InsertRetryPolicy.neverRetry()
.shouldRetry(new Context(new TableDataInsertAllResponse.InsertErrors())));
} |
long snapshotsRetrieved() {
return snapshotsRetrieved.get();
} | @Test
public void metrics_are_refreshed_on_every_update() {
assertEquals(0, nodeMetricsClient.snapshotsRetrieved());
updateSnapshot(defaultMetricsConsumerId, TTL);
assertEquals(1, nodeMetricsClient.snapshotsRetrieved());
updateSnapshot(defaultMetricsConsumerId, Duration.ZERO);
... |
public static FieldScope allowingFieldDescriptors(
FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) {
return FieldScopeImpl.createAllowingFieldDescriptors(asList(firstFieldDescriptor, rest));
} | @Test
public void testIgnoringTopLevelField_fieldScopes_allowingFieldDescriptors() {
expectThat(ignoringFieldDiffMessage)
.withPartialScope(FieldScopes.allowingFieldDescriptors(goodFieldDescriptor))
.isEqualTo(ignoringFieldMessage);
expectThat(ignoringFieldDiffMessage)
.ignoringFieldSc... |
public static byte[] compress(String urlString) throws MalformedURLException {
byte[] compressedBytes = null;
if (urlString != null) {
// Figure the compressed bytes can't be longer than the original string.
byte[] byteBuffer = new byte[urlString.length()];
int byteBu... | @Test
public void testCompressWithSubdomainsWithTrailingSlash() throws MalformedURLException {
String testURL = "http://www.forums.google.com/";
byte[] expectedBytes = {0x00, 'f', 'o', 'r', 'u', 'm', 's', '.', 'g', 'o', 'o', 'g', 'l', 'e', 0x00};
assertTrue(Arrays.equals(expectedBytes, UrlBe... |
@CanIgnoreReturnValue
public final Ordered containsExactly(@Nullable Object @Nullable ... varargs) {
List<@Nullable Object> expected =
(varargs == null) ? newArrayList((@Nullable Object) null) : asList(varargs);
return containsExactlyElementsIn(
expected, varargs != null && varargs.length == 1... | @Test
public void iterableContainsExactlyInOrderWithOneShotIterableWrongOrder() {
Iterator<Object> iterator = asList((Object) 1, null, 3).iterator();
Iterable<Object> iterable =
new Iterable<Object>() {
@Override
public Iterator<Object> iterator() {
return iterator;
... |
public Item and(Item item) {
Item result = and(getRoot(), item);
setRoot(result);
return result;
} | @Test
void addNotToNot() {
NotItem not1 = new NotItem();
not1.addPositiveItem(new WordItem("p1"));
not1.addNegativeItem(new WordItem("n1.1"));
not1.addNegativeItem(new WordItem("n1.2"));
NotItem not2 = new NotItem();
not2.addPositiveItem(new WordItem("p2"));
... |
public static ColumnSegment bind(final ColumnSegment segment, final SegmentType parentSegmentType, final SQLStatementBinderContext binderContext,
final Map<String, TableSegmentBinderContext> tableBinderContexts, final Map<String, TableSegmentBinderContext> outerTableBinderContexts) ... | @Test
void assertBindFromOuterTable() {
Map<String, TableSegmentBinderContext> outerTableBinderContexts = new LinkedHashMap<>(2, 1F);
ColumnSegment boundOrderStatusColumn = new ColumnSegment(0, 0, new IdentifierValue("status"));
boundOrderStatusColumn.setColumnBoundInfo(new ColumnSegmentBoun... |
@Override
public void execute(final ChannelHandlerContext context, final Object message, final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine, final ConnectionSession connectionSession) {
context.writeAndFlush(databaseProtocolFrontendEngine.getCommandExecuteEngine().getErrorPacket(new Circuit... | @Test
void assertExecute() {
ChannelHandlerContext channelHandlerContext = mock(ChannelHandlerContext.class);
DatabaseProtocolFrontendEngine engine = mock(DatabaseProtocolFrontendEngine.class, RETURNS_DEEP_STUBS);
ConnectionSession connectionSession = mock(ConnectionSession.class);
D... |
CompressionServletResponseWrapper(HttpServletResponse response, int compressionThreshold) {
super(response);
assert compressionThreshold >= 0;
this.compressionThreshold = compressionThreshold;
} | @Test
public void testCompressionServletResponseWrapper() throws IOException {
final CompressionServletResponseWrapper wrapper = new CompressionServletResponseWrapper(
new HttpResponse(), 1024);
wrapper.setStatus(HttpServletResponse.SC_NOT_FOUND);
assertEquals("status", HttpServletResponse.SC_NOT_FOUND, wrap... |
public RouteResult<T> route(HttpMethod method, String path) {
return route(method, path, Collections.emptyMap());
} | @Test
void testNone() {
RouteResult<String> routed = router.route(GET, "/noexist");
assertThat(routed.target()).isEqualTo("404");
} |
@Override
public void start() {
client = new NacosClient();
} | @Test
public void start() {
nacosRegister.start();
} |
@Override
public boolean equals(final Object o) {
if(this == o) {
return true;
}
if(!(o instanceof Application)) {
return false;
}
final Application that = (Application) o;
if(!Objects.equals(identifier, that.identifier)) {
return f... | @Test
public void testEquals() {
assertEquals(new Application("com.apple.textedit"), new Application("com.apple.textedit"));
assertEquals(new Application("com.apple.textedit"), new Application("com.apple.textedit", "TextEdit"));
assertEquals(new Application("com.apple.textedit"), new Applica... |
public List<Document> export(final String collectionName,
final List<String> exportedFieldNames,
final int limit,
final Bson dbFilter,
final List<Sort> sorts,
... | @Test
void testExportUsesSortAndLimitCorrectly() {
insertTestData();
simulateAdminUser();
final List<Document> exportedDocuments = toTest.export(TEST_COLLECTION_NAME,
List.of("name"),
2,
Filters.empty(),
List.of(Sort.create("age... |
@Override
public boolean matches(Issue issue) {
return !condition.matches(issue);
} | @Test
public void should_match_opposite() {
NotCondition condition = new NotCondition(target);
when(target.matches(any(Issue.class))).thenReturn(true);
assertThat(condition.matches(issue)).isFalse();
when(target.matches(any(Issue.class))).thenReturn(false);
assertThat(condition.matches(issue)).i... |
public static String substVars(String val, PropertyContainer pc1) {
return substVars(val, pc1, null);
} | @Test(timeout = 1000)
public void detectCircularReferences1() {
context.putProperty("A", "${A}a");
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Circular variable reference detected while parsing input [${A} --> ${A}]");
OptionHelper.substVars("${A}", cont... |
@Override
public Page<ConfigInfoBetaWrapper> findAllConfigInfoBetaForDumpAll(final int pageNo, final int pageSize) {
final int startRow = (pageNo - 1) * pageSize;
ConfigInfoBetaMapper configInfoBetaMapper = mapperManager.findMapper(dataSourceService.getDataSourceType(),
TableConstant... | @Test
void testFindAllConfigInfoBetaForDumpAll() {
//mock count
when(jdbcTemplate.queryForObject(anyString(), eq(Integer.class))).thenReturn(12345);
//mock page list
List<ConfigInfoBetaWrapper> mockList = new ArrayList<>();
mockList.add(new ConfigInfoBetaWrapper());
... |
public static String from(Path path) {
return from(path.toString());
} | @Test
void testTextContentType() {
assertThat(ContentType.from(Path.of("index.txt"))).isEqualTo(TEXT_PLAIN);
} |
@Override
public void updateFileConfig(FileConfigSaveReqVO updateReqVO) {
// 校验存在
FileConfigDO config = validateFileConfigExists(updateReqVO.getId());
// 更新
FileConfigDO updateObj = FileConfigConvert.INSTANCE.convert(updateReqVO)
.setConfig(parseClientConfig(config.ge... | @Test
public void testUpdateFileConfig_notExists() {
// 准备参数
FileConfigSaveReqVO reqVO = randomPojo(FileConfigSaveReqVO.class);
// 调用, 并断言异常
assertServiceException(() -> fileConfigService.updateFileConfig(reqVO), FILE_CONFIG_NOT_EXISTS);
} |
@GET
@Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 })
@Override
public ClusterInfo get() {
return getClusterInfo();
} | @Test
public void testClusterMetricsDefault() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("metrics").get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8,
resp... |
@Override
public boolean decide(final SelectStatementContext selectStatementContext, final List<Object> parameters,
final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, final ShardingRule rule, final Collection<DataNode> includedDataNodes) {
Collection<Stri... | @Test
void assertDecideWhenContainsOnlyOneTable() {
SelectStatementContext select = createStatementContext();
when(select.getTablesContext().getTableNames()).thenReturn(Collections.singletonList("t_order"));
when(select.isContainsJoinQuery()).thenReturn(true);
ShardingRule shardingRu... |
@Override
public void close() throws Exception {
super.close();
if (checkpointLock != null) {
synchronized (checkpointLock) {
issuedInstant = null;
isRunning = false;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Closed File Monitoring Source for path: " + path + ".");... | @Test
public void testConsumeFromLastCommit() throws Exception {
TestData.writeData(TestData.DATA_SET_INSERT, conf);
StreamReadMonitoringFunction function = TestUtils.getMonitorFunc(conf);
try (AbstractStreamOperatorTestHarness<MergeOnReadInputSplit> harness = createHarness(function)) {
harness.setu... |
public static Map<String, Object> coerceTypes(
final Map<String, Object> streamsProperties,
final boolean ignoreUnresolved
) {
if (streamsProperties == null) {
return Collections.emptyMap();
}
final Map<String, Object> validated = new HashMap<>(streamsProperties.size());
for (final ... | @Test
public void shouldCoerceTypes() {
// given/when:
final Map<String, Object> coerced = PropertiesUtil.coerceTypes(ImmutableMap.of(
"ksql.internal.topic.replicas", 3L,
"cache.max.bytes.buffering", "0"
), false);
// then:
assertThat(coerced.get("ksql.internal.topic.replicas"), i... |
@Override
public String toString() {
return "ResourceConfig{" +
"url=" + url +
", id='" + id + '\'' +
", resourceType=" + resourceType +
'}';
} | @Test
public void when_addNonexistentResourceWithFile_then_throwsException() {
// Given
String path = Paths.get("/i/do/not/exist").toString();
File file = new File(path);
// Then
expectedException.expect(JetException.class);
expectedException.expectMessage("Not an ex... |
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
} catch (Exception ex) {
handleReflectionException(ex);
}
throw new IllegalStateException("Should never get here");
} | @Test
void testInvokeMethod() throws Exception {
Method method = listStr.getClass().getDeclaredMethod("grow", int.class);
method.setAccessible(true);
ReflectUtils.invokeMethod(method, listStr, 4);
Object elementData = ReflectUtils.getFieldValue(listStr, "elementData");
assert... |
@VisibleForTesting
Optional<Set<String>> getSchedulerResourceTypeNamesUnsafe(final Object response) {
if (getSchedulerResourceTypesMethod.isPresent() && response != null) {
try {
@SuppressWarnings("unchecked")
final Set<? extends Enum> schedulerResourceTypes =
... | @Test
void testDoesntCallGetSchedulerResourceTypesMethodIfAbsent() {
final RegisterApplicationMasterResponseReflector
registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class);
final Optional<Set<String>... |
@Override
public Integer doCall() throws Exception {
// Operator id must be set
if (ObjectHelper.isEmpty(operatorId)) {
printer().println("Operator id must be set");
return -1;
}
delegate.setFile(name);
delegate.setSource(source);
delegate.set... | @Test
public void shouldBindWithDefaultOperatorId() throws Exception {
Bind command = createCommand("timer", "log");
command.doCall();
String output = printer.getOutput();
Assertions.assertEquals("""
apiVersion: camel.apache.org/v1
kind: Pipe
... |
public CharSequence format(Monetary monetary) {
// determine maximum number of decimals that can be visible in the formatted string
// (if all decimal groups were to be used)
int max = minDecimals;
if (decimalGroups != null)
for (int group : decimalGroups)
max... | @Test
public void sat() {
assertEquals("0", format(ZERO, 8, 0));
assertEquals("100000000", format(COIN, 8, 0));
assertEquals("2100000000000000", format(BitcoinNetwork.MAX_MONEY, 8, 0));
} |
public int readInt4() {
return byteBuf.readIntLE();
} | @Test
void assertReadInt4() {
when(byteBuf.readIntLE()).thenReturn(1);
assertThat(new MySQLPacketPayload(byteBuf, StandardCharsets.UTF_8).readInt4(), is(1));
} |
@Override
public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
if (param.getDeliveryType() == null) {
return;
}
if (DeliveryTypeEnum.PICK_UP.getType().equals(param.getDeliveryType())) {
calculateByPickUp(param);
} else if (... | @Test
@DisplayName("按件计算运费包邮的情况")
public void testCalculate_expressTemplateFree() {
// SKU 1 : 100 * 2 = 200
// SKU 2 :200 * 10 = 2000
// 运费 0
// mock 方法
// 准备运费模板包邮配置数据 包邮 订单总件数 > 包邮件数时 12 > 10
templateRespBO.setFree(randomPojo(DeliveryExpressTemplateRespBO.Fre... |
@Nullable protected TagsExtractor getQuickTextTagsSearcher() {
return mTagsExtractor;
} | @Test
public void testOnSharedPreferenceChangedCauseLoading() throws Exception {
SharedPrefsHelper.setPrefsValue(R.string.settings_key_search_quick_text_tags, false);
Assert.assertSame(
TagsExtractorImpl.NO_OP, mAnySoftKeyboardUnderTest.getQuickTextTagsSearcher());
SharedPrefsHelper.setPrefsValue(... |
public static SchemaAndValue parseString(String value) {
if (value == null) {
return NULL_SCHEMA_AND_VALUE;
}
if (value.isEmpty()) {
return new SchemaAndValue(Schema.STRING_SCHEMA, value);
}
ValueParser parser = new ValueParser(new Parser(value));
... | @Test
public void shouldParseBooleanLiteralsEmbeddedInArray() {
SchemaAndValue schemaAndValue = Values.parseString("[true, false]");
assertEquals(Type.ARRAY, schemaAndValue.schema().type());
assertEquals(Type.BOOLEAN, schemaAndValue.schema().valueSchema().type());
assertEquals(Arrays... |
public static String clean(String charsetName) {
try {
return forName(charsetName).name();
} catch (IllegalArgumentException e) {
return null;
}
} | @Test
public void testCleaningCharsetName() {
assertEquals("UTF-8", CharsetUtils.clean("utf-8"));
assertEquals(null, CharsetUtils.clean(""));
assertEquals(null, CharsetUtils.clean(null));
assertEquals("US-ASCII", CharsetUtils.clean(" us-ascii "));
assertEquals("UTF-8", Chars... |
public ServerHealthState trump(ServerHealthState otherServerHealthState) {
int result = healthStateLevel.compareTo(otherServerHealthState.healthStateLevel);
return result > 0 ? this : otherServerHealthState;
} | @Test
public void shouldTrumpSuccessIfCurrentIsSuccess() {
assertThat(SUCCESS_SERVER_HEALTH_STATE.trump(ANOTHER_SUCCESS_SERVER_HEALTH_STATE), is(
ANOTHER_SUCCESS_SERVER_HEALTH_STATE));
} |
public static String toFileURI(File file) {
URI uri = file.toURI();
String uriString = uri.toASCIIString();
return uriString.replaceAll("^file:/", "file:///");
} | @Test
@DisabledOnOs(OS.WINDOWS)
void shouldCreateFileURIForFile() {
assertThat(FileUtil.toFileURI(new File("/var/lib/foo/"))).isEqualTo("file:///var/lib/foo");
assertThat(FileUtil.toFileURI(new File("/var/a dir with spaces/foo"))).isEqualTo("file:///var/a%20dir%20with%20spaces/foo");
ass... |
private Gamma() {} | @Test
public void testExamples() {
assertEquals(Double.NaN, gamma(0.0));
assertEquals(1.77245385, gamma(0.5), 1e-8);
assertEquals(1.0, gamma(1.0));
assertEquals(24.0, gamma(5.0), 1e-8);
//some random examples betwixt -100 and 100
assertEquals(8.06474995572965e+79, ga... |
public static String printLogical(List<PlanFragment> fragments, FunctionAndTypeManager functionAndTypeManager, Session session)
{
Map<PlanFragmentId, PlanFragment> fragmentsById = Maps.uniqueIndex(fragments, PlanFragment::getId);
PlanNodeIdGenerator idGenerator = new PlanNodeIdGenerator();
... | @Test
public void testPrintLogical()
{
String actual = printLogical(
ImmutableList.of(createTestPlanFragment(0, TEST_TABLE_SCAN_NODE)),
FUNCTION_AND_TYPE_MANAGER,
testSessionBuilder().build());
String expected = join(
System.lineSep... |
@Override
public RedisScript<List<Long>> getScript() {
return script;
} | @Test
public void getScriptTest() {
DefaultRedisScript<List> redisScript = new DefaultRedisScript<>();
String scriptPath = "/META-INF/scripts/" + abstractRateLimiterAlgorithm.getScriptName();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(scriptPath)));
re... |
synchronized boolean tryToMoveTo(State to) {
boolean res = false;
State currentState = state;
if (TRANSITIONS.get(currentState).contains(to)) {
this.state = to;
res = true;
}
LOG.debug("{} tryToMoveTo from {} to {} => {}", Thread.currentThread().getName(), currentState, to, res);
ret... | @Test
@UseDataProvider("allStates")
public void RESTARTING_is_only_allowed_from_STARTING_and_OPERATIONAL(NodeLifecycle.State state) {
if (state == STARTING || state == OPERATIONAL) {
verifyMoveTo(newNodeLifecycle(state), RESTARTING);
} else {
assertThat(newNodeLifecycle(state).tryToMoveTo(RESTAR... |
public static <T> T newInstanceWithArgs(Class<T> clazz, Class<?>[] argTypes, Object[] args)
throws SofaRpcRuntimeException {
if (CommonUtils.isEmpty(argTypes)) {
return newInstance(clazz);
}
try {
if (!(clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifier... | @Test
public void testNewInstanceWithArgs() throws Exception {
Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass3.class, null, null));
Assert.assertNotNull(ClassUtils.newInstanceWithArgs(TestMemberClass3.class,
new Class[] { String.class }, new Object[] { "2222" }));
... |
public boolean verifySignature(String jwksUri, SignedJWT signedJwt) throws JOSEException, InvalidSignatureException, IOException, ParseException {
var publicKeys = getPublicKeys(jwksUri);
var kid = signedJwt.getHeader().getKeyID();
if (kid != null) {
var key = ((RSAKey) publicKeys.g... | @Test
void verifyInvalidSignatureTest() {
assertThrows(
InvalidSignatureException.class,
() -> provider.verifySignature("jwskUri", SignedJWT.parse(VALID_REQUEST))
);
} |
public static <T> T[] checkNonEmpty(T[] array, String name) {
//No String concatenation for check
if (checkNotNull(array, name).length == 0) {
throw new IllegalArgumentException("Param '" + name + "' must not be empty");
}
return array;
} | @Test
public void testCheckNonEmptyCharSequenceString() {
Exception actualEx = null;
try {
ObjectUtil.checkNonEmpty((CharSequence) NULL_CHARSEQUENCE, NULL_NAME);
} catch (Exception e) {
actualEx = e;
}
assertNotNull(actualEx, TEST_RESULT_NULLEX_OK);
... |
public static String[] split(String splittee, String splitChar, boolean truncate) { //NOSONAR
if (splittee == null || splitChar == null) {
return new String[0];
}
final String EMPTY_ELEMENT = "";
int spot;
final int splitLength = splitChar.length();
final Stri... | @Test
public void testSplitStringStringTrueWithTrailingSplitChars() {
// Test ignore trailing split characters
// Ignore adjacent delimiters
assertThat("Ignore trailing split chars", JOrphanUtils.split("a,bc,,", ",", true),
CoreMatchers.equalTo(new String[]{"a", "bc"}));
... |
public void add(T element) {
Preconditions.checkNotNull(element);
if (elements.add(element) && elements.size() > maxSize) {
elements.poll();
}
} | @Test
void testQueueWithMaxSize2() {
final BoundedFIFOQueue<Integer> testInstance = new BoundedFIFOQueue<>(2);
assertThat(testInstance).isEmpty();
testInstance.add(1);
assertThat(testInstance).contains(1);
testInstance.add(2);
assertThat(testInstance).contains(1, 2)... |
public int getColorForPoint(double x, double y, int px, int py, int plane, double brightness, ChunkMapper chunkMapper)
{
x /= 8.d;
y /= 8.d;
int centerChunkData = chunkData(px / 8, py / 8, plane, chunkMapper);
if (centerChunkData == -1)
{
// No data in the center chunk?
return 0;
}
double t = 0;
... | @Test
public void testLoadSimple() throws IOException
{
Skybox skybox = new Skybox(CharSource.wrap("bounds 0 0 100 100 #00F // R 0 0 100 100\r\nr 99 99").openStream(), "simple");
Assert.assertEquals(0, skybox.getColorForPoint(0, 0, 0, 0, 0, 1, null));
int x = (99 * 64) + 32;
int y = (99 * 64) + 32;
Assert.a... |
@Override
public void updateMember(ConsumerGroupMember newMember) {
if (newMember == null) {
throw new IllegalArgumentException("newMember cannot be null.");
}
ConsumerGroupMember oldMember = members.put(newMember.memberId(), newMember);
maybeUpdateSubscribedTopicNamesAnd... | @Test
public void testUpdateMember() {
ConsumerGroup consumerGroup = createConsumerGroup("foo");
ConsumerGroupMember member;
member = consumerGroup.getOrMaybeCreateMember("member", true);
member = new ConsumerGroupMember.Builder(member)
.setSubscribedTopicNames(Arrays.a... |
@Override
public ConnectorTableMetadata getTableMetadata(ConnectorSession session, ConnectorTableHandle table)
{
JdbcTableHandle handle = (JdbcTableHandle) table;
ImmutableList.Builder<ColumnMetadata> columnMetadata = ImmutableList.builder();
for (JdbcColumnHandle column : jdbcMetadataC... | @Test
public void getTableMetadata()
{
// known table
ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(SESSION, tableHandle);
assertEquals(tableMetadata.getTable(), new SchemaTableName("example", "numbers"));
assertEquals(tableMetadata.getColumns(), ImmutableList.... |
@Override
public String getRomOAID() {
String oaid = null;
try {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.coolpad.deviceidsupport", "com.coolpad.deviceidsupport.DeviceIdService"));
if (context.bindService(intent, service, Context.BI... | @Test
public void getRomOAID() {
CoolpadImpl coolpad = new CoolpadImpl(mApplication);
// if(coolpad.isSupported()) {
// Assert.assertNull(coolpad.getRomOAID());
// }
} |
@Override
public DataTableType dataTableType() {
return dataTableType;
} | @Test
void target_type_must_class_type() throws NoSuchMethodException {
Method method = JavaDataTableTypeDefinitionTest.class.getMethod("converts_datatable_to_optional_string",
DataTable.class);
JavaDataTableTypeDefinition definition = new JavaDataTableTypeDefinition(method, lookup, new ... |
public synchronized ListenableFuture<?> waitForMinimumWorkers()
{
if (currentWorkerCount >= workerMinCount) {
return immediateFuture(null);
}
SettableFuture<?> future = SettableFuture.create();
workerSizeFutures.add(future);
// if future does not finish in wait ... | @Test(timeOut = 60_000)
public void testWaitForMinimumWorkers()
throws InterruptedException
{
ListenableFuture<?> workersFuture = waitForMinimumWorkers();
for (int i = numWorkers.get() + 1; i < DESIRED_WORKER_COUNT - 1; i++) {
assertFalse(workersTimeout.get());
... |
@Override
public synchronized void close() {
super.close();
notifyAll();
} | @Test
public void testMetadataEquivalentResponsesBackoff() throws InterruptedException {
long time = 0;
metadata.updateWithCurrentRequestVersion(responseWithCurrentTopics(), false, time);
assertTrue(metadata.timeToNextUpdate(time) > 0, "No update needed");
metadata.requestUpdate(fals... |
public void reloadAllNotes(AuthenticationInfo subject) throws IOException {
this.noteManager.reloadNotes();
if (notebookRepo instanceof NotebookRepoSync) {
NotebookRepoSync mainRepo = (NotebookRepoSync) notebookRepo;
if (mainRepo.getRepoCount() > 1) {
mainRepo.sync(subject);
}
}
... | @Test
void testReloadAllNotes() throws IOException {
String note1Id = notebook.createNote("note1", AuthenticationInfo.ANONYMOUS);
notebook.processNote(note1Id,
note1 -> {
Paragraph p1 = note1.insertNewParagraph(0, AuthenticationInfo.ANONYMOUS);
p1.setText("%md hello world");
retu... |
@VisibleForTesting
public Map<String, HashSet<String>> runTest(Set<String> inputList, Map<String, Long> sizes) {
try {
conf = msConf;
testDatasizes = sizes;
coverageList.clear();
removeNestedStructure(inputList);
createOutputList(inputList, "test", "test");
} catch (Exception e)... | @Test
public void testGroupLocations() {
Set<String> inputLocations = new TreeSet<>();
Configuration conf = MetastoreConf.newMetastoreConf();
MetastoreConf.setBoolVar(conf, MetastoreConf.ConfVars.HIVE_IN_TEST, true);
MetaToolTaskListExtTblLocs.msConf = conf;
MetaToolTaskListExtTblLocs task = new M... |
@Override
public MapperResult findChangeConfigFetchRows(MapperContext context) {
final String tenant = (String) context.getWhereParameter(FieldConstant.TENANT);
final String dataId = (String) context.getWhereParameter(FieldConstant.DATA_ID);
final String group = (String) context.getWherePara... | @Test
void testFindChangeConfigFetchRows() {
MapperResult mapperResult = configInfoMapperByDerby.findChangeConfigFetchRows(context);
assertEquals(mapperResult.getSql(), "SELECT id,data_id,group_id,tenant_id,app_name,content,type,md5,gmt_modified FROM config_info "
+ "WHERE 1=1 AND ... |
@Override
public void deleteArticleCategory(Long id) {
// 校验存在
validateArticleCategoryExists(id);
// 校验是不是存在关联文章
Long count = articleService.getArticleCountByCategoryId(id);
if (count > 0) {
throw exception(ARTICLE_CATEGORY_DELETE_FAIL_HAVE_ARTICLES);
}
... | @Test
public void testDeleteArticleCategory_success() {
// mock 数据
ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class);
articleCategoryMapper.insert(dbArticleCategory);// @Sql: 先插入出一条存在的数据
// 准备参数
Long id = dbArticleCategory.getId();
// 调用
... |
synchronized void updateServiceStatuses(List<VespaService> services) {
try {
setStatus(services);
} catch (Exception e) {
log.log(Level.SEVERE, "Unable to update service pids from sentinel", e);
}
} | @Test
public void testElastic() {
String response = "container state=RUNNING mode=AUTO pid=14338 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"get/container.0\"\n" +
"container-clustercontroller state=RUNNING mode=AUTO pid=25020 exitstatus=0 autostart=TRUE autorestart=TRUE id=\"admin/clu... |
public static String identifyDriver(String nameContainsProductInfo) {
return DialectFactory.identifyDriver(nameContainsProductInfo);
} | @Test
public void identifyDriverTest(){
String url = "jdbc:h2:file:./db/test;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL";
String driver = DriverUtil.identifyDriver(url); // driver 返回 mysql 的 driver
assertEquals("org.h2.Driver", driver);
} |
public ProcessWrapper create(@Nullable Path baseDir, Consumer<String> stdOutLineConsumer, String... command) {
return new ProcessWrapper(baseDir, stdOutLineConsumer, Map.of(), command);
} | @Test
public void should_log_error_output_in_debug_mode() throws IOException {
logTester.setLevel(Level.DEBUG);
var root = temp.newFolder().toPath();
var processWrapper = underTest.create(root, v -> {}, Map.of("LANG", "en_US"), "git", "blame");
assertThatThrownBy(processWrapper::execute)
.isInst... |
public void onLoaded() {
groups.forEach((groupId, group) -> {
switch (group.type()) {
case CONSUMER:
ConsumerGroup consumerGroup = (ConsumerGroup) group;
log.info("Loaded consumer group {} with {} members.", groupId, consumerGroup.members().siz... | @Test
public void testOnLoaded() {
Uuid fooTopicId = Uuid.randomUuid();
String fooTopicName = "foo";
Uuid barTopicId = Uuid.randomUuid();
String barTopicName = "bar";
GroupMetadataManagerTestContext context = new GroupMetadataManagerTestContext.Builder()
.withCon... |
@Override
public DataSink createDataSink(Context context) {
FactoryHelper.createFactoryHelper(this, context)
.validateExcept(PREFIX_TABLE_PROPERTIES, PREFIX_CATALOG_PROPERTIES);
Map<String, String> allOptions = context.getFactoryConfiguration().toMap();
Map<String, String> c... | @Test
void testPrefixRequireOption() {
DataSinkFactory sinkFactory =
FactoryDiscoveryUtils.getFactoryByIdentifier("paimon", DataSinkFactory.class);
Assertions.assertThat(sinkFactory).isInstanceOf(PaimonDataSinkFactory.class);
Configuration conf =
Configuration... |
public void complete(T value) {
try {
if (value instanceof RuntimeException)
throw new IllegalArgumentException("The argument to complete can not be an instance of RuntimeException");
if (!result.compareAndSet(INCOMPLETE_SENTINEL, value))
throw new Illega... | @Test
public void invokeCompleteAfterAlreadyComplete() {
RequestFuture<Void> future = new RequestFuture<>();
future.complete(null);
assertThrows(IllegalStateException.class, () -> future.complete(null));
} |
@Override
public List<RedisClientInfo> getClientList(RedisClusterNode node) {
RedisClient entry = getEntry(node);
RFuture<List<String>> f = executorService.readAsync(entry, StringCodec.INSTANCE, RedisCommands.CLIENT_LIST);
List<String> list = syncFuture(f);
return CONVERTER.convert(l... | @Test
public void testGetClientList() {
RedisClusterNode master = getFirstMaster();
List<RedisClientInfo> list = connection.getClientList(master);
assertThat(list.size()).isGreaterThan(10);
} |
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
if (bytes == null) {
return null;
}
// don't use the JsonSchemaConverter to read this data because
// we require that the MAPPER enables USE_BIG_DECIMAL_FOR_FLOATS,
// which is not currently avail... | @Test
public void shouldTreatNullAsNull() {
// Given:
final HashMap<String, Object> mapValue = new HashMap<>();
mapValue.put("a", 1.0);
mapValue.put("b", null);
final Map<String, Object> row = new HashMap<>();
row.put("ordertime", null);
row.put("@orderid", null);
row.put("itemid", nu... |
public static MapBuilder<Schema> map() {
return builder().map();
} | @Test
void map() {
Schema intSchema = Schema.create(Schema.Type.INT);
Schema expected = Schema.createMap(intSchema);
Schema schema1 = SchemaBuilder.map().values().intType();
assertEquals(expected, schema1);
Schema schema2 = SchemaBuilder.map().values(intSchema);
assertEquals(expected, schema... |
public boolean poll(Timer timer, boolean waitForJoinGroup) {
maybeUpdateSubscriptionMetadata();
invokeCompletedOffsetCommitCallbacks();
if (subscriptions.hasAutoAssignedPartitions()) {
if (protocol == null) {
throw new IllegalStateException("User configured " + Cons... | @Test
public void testNormalHeartbeat() {
client.prepareResponse(groupCoordinatorResponse(node, Errors.NONE));
coordinator.ensureCoordinatorReady(time.timer(Long.MAX_VALUE));
// normal heartbeat
time.sleep(sessionTimeoutMs);
RequestFuture<Void> future = coordinator.sendHeart... |
Optional<DescriptorDigest> select(DescriptorDigest selector)
throws CacheCorruptedException, IOException {
Path selectorFile = cacheStorageFiles.getSelectorFile(selector);
if (!Files.exists(selectorFile)) {
return Optional.empty();
}
String selectorFileContents =
new String(Files.re... | @Test
public void testSelect() throws IOException, CacheCorruptedException {
DescriptorDigest selector = layerDigest1;
Path selectorFile = cacheStorageFiles.getSelectorFile(selector);
Files.createDirectories(selectorFile.getParent());
Files.write(selectorFile, layerDigest2.getHash().getBytes(StandardC... |
public Column getColumn(String value) {
Matcher m = PATTERN.matcher(value);
if (!m.matches()) {
throw new IllegalArgumentException("value " + value + " is not a valid column definition");
}
String name = m.group(1);
String type = m.group(6);
type = type == nu... | @Test
public void testGetColumn() {
ColumnFactory f = new ColumnFactory();
Column column = f.getColumn("column");
assertThat(column instanceof StringColumn).isTrue();
assertThat(column.getName()).isEqualTo("column");
} |
@Override
public T computeIfAbsent(String key, Function<String, T> supplier) {
return cache.compute(
key,
(String k, T current) -> {
if (isValidLongEnough(current)) {
return current;
}
return supplier.apply(key);
});
} | @Test
void fetchesRightOne() {
var ttl = Duration.ofSeconds(10);
var sut = new InMemoryCacheImpl<CacheEntry>(Clock.fixed(NOW, ZoneId.of("UTC")), ttl);
var source =
IntStream.range(0, 10)
.mapToObj(i -> CacheEntry.of(Integer.toString(i), NOW.plusSeconds(60)))
.collect(Coll... |
public StreamDestinationFilterRuleDTO createForStream(String streamId, StreamDestinationFilterRuleDTO dto) {
if (!isBlank(dto.id())) {
throw new IllegalArgumentException("id must be blank");
}
// We don't want to allow the creation of a filter rule for a different stream, so we enfo... | @Test
void createForStreamWithExistingID() {
final StreamDestinationFilterRuleDTO dto = StreamDestinationFilterRuleDTO.builder()
.id("54e3deadbeefdeadbeef0000")
.title("Test")
.description("A Test")
.streamId("stream-1")
.destin... |
@ExecuteOn(TaskExecutors.IO)
@Delete(uri = "{key}")
@Operation(tags = {"KV"}, summary = "Delete a key-value pair")
public boolean delete(
@Parameter(description = "The namespace id") @PathVariable String namespace,
@Parameter(description = "The key") @PathVariable String key
) throws IOE... | @Test
void delete() throws IOException {
storageInterface.put(
null,
toKVUri(NAMESPACE, "my-key"),
new StorageObject(
Map.of("expirationDate", Instant.now().plus(Duration.ofMinutes(5)).toString()),
new ByteArrayInputStream("\"content\"".get... |
public Serde<GenericKey> buildKeySerde(
final FormatInfo format, final PhysicalSchema schema, final QueryContext queryContext
) {
final String loggerNamePrefix = QueryLoggerUtil.queryLoggerName(queryId, queryContext);
schemas.trackKeySerdeCreation(
loggerNamePrefix,
schema.logicalSchema... | @Test
public void shouldBuildNonWindowedKeySerde() {
// Then:
runtimeBuildContext.buildKeySerde(
FORMAT_INFO,
PHYSICAL_SCHEMA,
queryContext
);
// Then:
verify(keySerdeFactory).create(
FORMAT_INFO,
PHYSICAL_SCHEMA.keySchema(),
ksqlConfig,
srC... |
public static InetSocketAddress parseAddress(String address, int defaultPort) {
return parseAddress(address, defaultPort, false);
} | @Test
void shouldParseAddressForIPv6WithoutBrackets() {
InetSocketAddress socketAddress = AddressUtils.parseAddress("1abc:2abc:3abc:0:0:0:5abc:6abc", 80);
assertThat(socketAddress.isUnresolved()).isFalse();
assertThat(socketAddress.getAddress().getHostAddress()).isEqualTo("1abc:2abc:3abc:0:0:0:5abc:6abc");
ass... |
public int runInteractively() {
displayWelcomeMessage();
RemoteServerSpecificCommand.validateClient(terminal.writer(), restClient);
boolean eof = false;
while (!eof) {
try {
handleLine(nextNonCliCommand());
} catch (final EndOfFileException exception) {
// EOF is fine, just t... | @Test
public void shouldPrintErrorOnUnsupportedAPI() throws Exception {
givenRunInteractivelyWillExit();
final KsqlRestClient mockRestClient = givenMockRestClient();
when(mockRestClient.getServerInfo()).thenReturn(
RestResponse.erroneous(
NOT_ACCEPTABLE.code(),
new KsqlErr... |
public OffsetPosition entry(int n) {
return maybeLock(lock, () -> {
if (n >= entries())
throw new IllegalArgumentException("Attempt to fetch the " + n + "th entry from index " +
file().getAbsolutePath() + ", which has size " + entries());
return parseE... | @Test
public void testEntryOverflow() {
assertThrows(IllegalArgumentException.class, () -> index.entry(0));
} |
@Override
public KsMaterializedQueryResult<Row> get(
final GenericKey key,
final int partition,
final Optional<Position> position
) {
try {
final KeyQuery<GenericKey, ValueAndTimestamp<GenericRow>> query = KeyQuery.withKey(key);
StateQueryRequest<ValueAndTimestamp<GenericRow>>
... | @Test
public void shouldThrowIfQueryFails() {
// Given:
when(stateStore.getKafkaStreams().query(any())).thenThrow(new MaterializationTimeOutException("Boom"));
// When:
final Exception e = assertThrows(
MaterializationException.class,
() -> table.get(A_KEY, PARTITION)
);
// T... |
public boolean authenticate(LDAPConnection connection, String bindDn, EncryptedValue password) throws LDAPException {
checkArgument(!isNullOrEmpty(bindDn), "Binding with empty principal is forbidden.");
checkArgument(password != null, "Binding with null credentials is forbidden.");
checkArgument... | @Test
public void authenticateThrowsIllegalArgumentExceptionIfPrincipalIsEmpty() throws LDAPException {
assertThatThrownBy(() -> connector.authenticate(connection, "", encryptedValueService.encrypt("secret")))
.hasMessageContaining("Binding with empty principal is forbidden.")
... |
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>();
if (isTrue(namespace.getBoolean("columns"))) {
compareTypes.add(Column.cla... | @Test
void testWriteToFile() throws Exception {
final File file = File.createTempFile("migration", ".xml");
dumpCommand.run(null, new Namespace(Collections.singletonMap("output", file.getAbsolutePath())), existedDbConf);
// Check that file is exist, and has some XML content (no reason to mak... |
static CatalogLoader createCatalogLoader(
String name, Map<String, String> properties, Configuration hadoopConf) {
String catalogImpl = properties.get(CatalogProperties.CATALOG_IMPL);
if (catalogImpl != null) {
String catalogType = properties.get(ICEBERG_CATALOG_TYPE);
Preconditions.checkArgum... | @Test
public void testLoadCatalogUnknown() {
String catalogName = "unknownCatalog";
props.put(FlinkCatalogFactory.ICEBERG_CATALOG_TYPE, "fooType");
assertThatThrownBy(
() -> FlinkCatalogFactory.createCatalogLoader(catalogName, props, new Configuration()))
.isInstanceOf(UnsupportedOper... |
@Override
public CiConfiguration loadConfiguration() {
String revision = system2.envVariable("BITRISE_GIT_COMMIT");
return new CiConfigurationImpl(revision, getName());
} | @Test
public void loadConfiguration() {
setEnvVariable("CI", "true");
setEnvVariable("BITRISE_IO", "true");
setEnvVariable("BITRISE_GIT_COMMIT", "abd12fc");
assertThat(underTest.loadConfiguration().getScmRevision()).hasValue("abd12fc");
} |
@ScalarFunction
@LiteralParameters("x")
@SqlType(ColorType.NAME)
public static long color(@SqlType("varchar(x)") Slice color)
{
int rgb = parseRgb(color);
if (rgb != -1) {
return rgb;
}
// encode system colors (0-15) as negative values, offset by one
... | @Test
public void testColor()
{
assertEquals(color(toSlice("black")), -1);
assertEquals(color(toSlice("red")), -2);
assertEquals(color(toSlice("green")), -3);
assertEquals(color(toSlice("yellow")), -4);
assertEquals(color(toSlice("blue")), -5);
assertEquals(color(... |
public static boolean isContentType(String contentType, Message message) {
if (contentType == null) {
return message.getContentType() == null;
} else {
return contentType.equals(message.getContentType());
}
} | @Test
public void testIsContentTypeWithNonNullStringValueAndNullMessageContentType() {
Message message = Proton.message();
assertFalse(AmqpMessageSupport.isContentType("test", message));
} |
@Override
public NativeEntity<GrokPattern> createNativeEntity(Entity entity,
Map<String, ValueReference> parameters,
Map<EntityDescriptor, Object> nativeEntities,
... | @Test
public void createNativeEntity() throws NotFoundException {
final Entity grokPatternEntity = EntityV1.builder()
.id(ModelId.of("1"))
.type(ModelTypes.GROK_PATTERN_V1)
.data(objectMapper.convertValue(GrokPatternEntity.create("Test","[a-z]+"), JsonNode.cla... |
private void jobAlreadyDone(UUID leaderSessionId) {
LOG.info(
"{} for job {} was granted leadership with leader id {}, but job was already done.",
getClass().getSimpleName(),
getJobID(),
leaderSessionId);
resultFuture.complete(
... | @Test
void testJobAlreadyDone() throws Exception {
final JobID jobId = new JobID();
final JobResult jobResult =
TestingJobResultStore.createJobResult(jobId, ApplicationStatus.UNKNOWN);
jobResultStore.createDirtyResultAsync(new JobResultEntry(jobResult)).get();
try (Jo... |
@Override
public List<Node> sniff(List<Node> nodes) {
if (attribute == null || value == null) {
return nodes;
}
return nodes.stream()
.filter(node -> nodeMatchesFilter(node, attribute, value))
.collect(Collectors.toList());
} | @Test
void returnsAllNodesIfFilterMatchesAll() throws Exception {
final List<Node> nodes = mockNodes();
final NodesSniffer nodesSniffer = new FilteredElasticsearchNodesSniffer("always", "true");
assertThat(nodesSniffer.sniff(nodes)).isEqualTo(nodes);
} |
public static DoFnInstanceManager cloningPool(DoFnInfo<?, ?> info, PipelineOptions options) {
return new ConcurrentQueueInstanceManager(info, options);
} | @Test
public void testCloningPoolTearsDownAfterAbort() throws Exception {
DoFnInfo<?, ?> info =
DoFnInfo.forFn(
initialFn,
WindowingStrategy.globalDefault(),
null /* side input views */,
null /* input coder */,
new TupleTag<>(PropertyNames.OUTPUT... |
@Override
public ClassLoaderLease registerClassLoaderLease(JobID jobId) {
synchronized (lockObject) {
return cacheEntries
.computeIfAbsent(jobId, jobID -> new LibraryCacheEntry(jobId))
.obtainLease();
}
} | @Test
public void differentLeasesForSameJob_returnSameClassLoader() throws IOException {
final BlobLibraryCacheManager libraryCacheManager = createSimpleBlobLibraryCacheManager();
final JobID jobId = new JobID();
final LibraryCacheManager.ClassLoaderLease classLoaderLease1 =
... |
public static void dumpSystemInfo() {
dumpSystemInfo(new PrintWriter(System.out));
} | @Test
@Disabled
public void dumpTest() {
SystemUtil.dumpSystemInfo();
} |
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
try {
final FileEntity entity = new FilesApi(new BrickApiClient(session))
.download(StringUtils.removeStart(file.getAbsolute(), String.v... | @Test(expected = NotfoundException.class)
public void testReadNotFound() throws Exception {
final TransferStatus status = new TransferStatus();
final Path room = new BrickDirectoryFeature(session).mkdir(
new Path(new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.direct... |
@CanIgnoreReturnValue
public final Ordered containsExactlyEntriesIn(Map<?, ?> expectedMap) {
if (expectedMap.isEmpty()) {
if (checkNotNull(actual).isEmpty()) {
return IN_ORDER;
} else {
isEmpty(); // fails
return ALREADY_FAILED;
}
}
boolean containsAnyOrder = cont... | @Test
public void containsExactlyEntriesInEmpty_fails() {
ImmutableMap<String, Integer> actual = ImmutableMap.of("jan", 1);
expectFailureWhenTestingThat(actual).containsExactlyEntriesIn(ImmutableMap.of());
assertFailureKeys("expected to be empty", "but was");
} |
@Override
public OAuth2ClientDO getOAuth2Client(Long id) {
return oauth2ClientMapper.selectById(id);
} | @Test
public void testGetOAuth2Client() {
// mock 数据
OAuth2ClientDO clientDO = randomPojo(OAuth2ClientDO.class);
oauth2ClientMapper.insert(clientDO);
// 准备参数
Long id = clientDO.getId();
// 调用,并断言
OAuth2ClientDO dbClientDO = oauth2ClientService.getOAuth2Client... |
@Override
public void handle(TaskEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing " + event.getTaskID() + " of type "
+ event.getType());
}
try {
writeLock.lock();
TaskStateInternal oldState = getInternalState();
try {
stateMachine.doTransition(eve... | @Test
/**
* Kill map attempt for succeeded map task
* {@link TaskState#SUCCEEDED}->{@link TaskState#SCHEDULED}
*/
public void testKillAttemptForSuccessfulTask() {
LOG.info("--- START: testKillAttemptForSuccessfulTask ---");
mockTask = createMockTask(TaskType.MAP);
TaskId taskId = getNewTaskID()... |
@Override
public Mono<DeleteAccountResponse> deleteAccount(final DeleteAccountRequest request) {
final AuthenticatedDevice authenticatedDevice = AuthenticationUtil.requireAuthenticatedPrimaryDevice();
return Mono.fromFuture(() -> accountsManager.getByAccountIdentifierAsync(authenticatedDevice.accountIdentifi... | @Test
void deleteAccount() {
final Account account = mock(Account.class);
when(accountsManager.getByAccountIdentifierAsync(AUTHENTICATED_ACI))
.thenReturn(CompletableFuture.completedFuture(Optional.of(account)));
when(accountsManager.delete(any(), any()))
.thenReturn(CompletableFuture.co... |
public static int availableProcessors() {
return org.infinispan.commons.jdkspecific.ProcessorInfo.availableProcessors();
} | @Test
@Category(Java11.class)
public void testCPUCount() {
assertTrue(ProcessorInfo.availableProcessors() <= Runtime.getRuntime().availableProcessors());
} |
@Override
public RuleNodePath getRuleNodePath() {
return INSTANCE;
} | @Test
void assertNew() {
RuleNodePathProvider ruleNodePathProvider = new MaskRuleNodePathProvider();
RuleNodePath actualRuleNodePath = ruleNodePathProvider.getRuleNodePath();
assertThat(actualRuleNodePath.getNamedItems().size(), is(2));
assertTrue(actualRuleNodePath.getNamedItems().c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.